text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { ParseContext, ParseContextUtils, ParseError } from "..";
import { Assert, CommonError, MapUtils } from "../../common";
import { Ast, Constant, Token } from "../../language";
import { LexerSnapshot } from "../../lexer";
import { DefaultLocale } from "../../localization";
import { Disambiguation } from "../disambiguation";
import { SequenceKind } from "../error";
import { ParseState } from "./parseState";
export function createState(lexerSnapshot: LexerSnapshot, maybeOverrides: Partial<ParseState> | undefined): ParseState {
const tokenIndex: number = maybeOverrides?.tokenIndex ?? 0;
const maybeCurrentToken: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex];
const maybeCurrentTokenKind: Token.TokenKind | undefined = maybeCurrentToken?.kind;
const contextState: ParseContext.State = maybeOverrides?.contextState ?? ParseContextUtils.createState();
const maybeCurrentContextNodeId: number | undefined =
contextState.nodeIdMapCollection.contextNodeById.size > 0
? Math.max(...contextState.nodeIdMapCollection.contextNodeById.keys())
: undefined;
const maybeCurrentContextNode: ParseContext.TNode | undefined =
maybeCurrentContextNodeId !== undefined
? MapUtils.assertGet(contextState.nodeIdMapCollection.contextNodeById, maybeCurrentContextNodeId)
: undefined;
return {
...maybeOverrides,
lexerSnapshot,
maybeCancellationToken: maybeOverrides?.maybeCancellationToken,
locale: maybeOverrides?.locale ?? DefaultLocale,
disambiguationBehavior:
maybeOverrides?.disambiguationBehavior ?? Disambiguation.DismabiguationBehavior.Thorough,
tokenIndex,
maybeCurrentToken,
maybeCurrentTokenKind,
contextState: maybeOverrides?.contextState ?? ParseContextUtils.createState(),
maybeCurrentContextNode,
};
}
// If you have a custom parser + parser state, then you'll have to create your own copyState/applyState functions.
// See `benchmark.ts` for an example.
export function applyState(state: ParseState, update: ParseState): void {
state.tokenIndex = update.tokenIndex;
state.maybeCurrentToken = update.maybeCurrentToken;
state.maybeCurrentTokenKind = update.maybeCurrentTokenKind;
state.contextState = update.contextState;
state.maybeCurrentContextNode = update.maybeCurrentContextNode;
}
// If you have a custom parser + parser state, then you'll have to create your own copyState/applyState functions.
// See `benchmark.ts` for an example.
export function copyState(state: ParseState): ParseState {
return {
...state,
contextState: ParseContextUtils.copyState(state.contextState),
};
}
export function startContext<T extends Ast.TNode>(state: ParseState, nodeKind: T["kind"]): void {
const newContextNode: ParseContext.Node<T> = ParseContextUtils.startContext(
state.contextState,
nodeKind,
state.tokenIndex,
state.maybeCurrentToken,
state.maybeCurrentContextNode,
);
state.maybeCurrentContextNode = newContextNode;
}
export function endContext<T extends Ast.TNode>(state: ParseState, astNode: T): void {
const contextNode: ParseContext.TNode = Assert.asDefined(
state.maybeCurrentContextNode,
`can't end a context if one doesn't exist`,
);
const maybeParentOfContextNode: ParseContext.TNode | undefined = ParseContextUtils.endContext(
state.contextState,
contextNode,
astNode,
);
state.maybeCurrentContextNode = maybeParentOfContextNode;
}
export function deleteContext(state: ParseState, maybeNodeId: number | undefined): void {
let nodeId: number;
if (maybeNodeId === undefined) {
nodeId = Assert.asDefined(state.maybeCurrentContextNode, `can't delete a context if one doesn't exist`).id;
} else {
nodeId = maybeNodeId;
}
state.maybeCurrentContextNode = ParseContextUtils.deleteContext(state.contextState, nodeId);
}
export function incrementAttributeCounter(state: ParseState): void {
Assert.asDefined(state.maybeCurrentContextNode, `state.maybeCurrentContextNode`).attributeCounter += 1;
}
// -------------------------
// ---------- IsX ----------
// -------------------------
export function isTokenKind(state: ParseState, tokenKind: Token.TokenKind, tokenIndex: number): boolean {
return state.lexerSnapshot.tokens[tokenIndex]?.kind === tokenKind ?? false;
}
export function isNextTokenKind(state: ParseState, tokenKind: Token.TokenKind): boolean {
return isTokenKind(state, tokenKind, state.tokenIndex + 1);
}
export function isOnTokenKind(
state: ParseState,
tokenKind: Token.TokenKind,
tokenIndex: number = state.tokenIndex,
): boolean {
return isTokenKind(state, tokenKind, tokenIndex);
}
export function isOnConstantKind(state: ParseState, constantKind: Constant.TConstant): boolean {
if (isOnTokenKind(state, Token.TokenKind.Identifier)) {
const currentToken: Token.Token = state.lexerSnapshot.tokens[state.tokenIndex];
if (currentToken?.data === undefined) {
const details: {} = { currentToken };
throw new CommonError.InvariantError(`expected data on Token`, details);
}
const data: string = currentToken.data;
return data === constantKind;
} else {
return false;
}
}
export function isOnGeneralizedIdentifierStart(state: ParseState, tokenIndex: number = state.tokenIndex): boolean {
const maybeTokenKind: Token.TokenKind | undefined = state.lexerSnapshot.tokens[tokenIndex]?.kind;
if (maybeTokenKind === undefined) {
return false;
}
switch (maybeTokenKind) {
case Token.TokenKind.Identifier:
case Token.TokenKind.KeywordAnd:
case Token.TokenKind.KeywordAs:
case Token.TokenKind.KeywordEach:
case Token.TokenKind.KeywordElse:
case Token.TokenKind.KeywordError:
case Token.TokenKind.KeywordFalse:
case Token.TokenKind.KeywordHashBinary:
case Token.TokenKind.KeywordHashDate:
case Token.TokenKind.KeywordHashDateTime:
case Token.TokenKind.KeywordHashDateTimeZone:
case Token.TokenKind.KeywordHashDuration:
case Token.TokenKind.KeywordHashInfinity:
case Token.TokenKind.KeywordHashNan:
case Token.TokenKind.KeywordHashSections:
case Token.TokenKind.KeywordHashShared:
case Token.TokenKind.KeywordHashTable:
case Token.TokenKind.KeywordHashTime:
case Token.TokenKind.KeywordIf:
case Token.TokenKind.KeywordIn:
case Token.TokenKind.KeywordIs:
case Token.TokenKind.KeywordLet:
case Token.TokenKind.KeywordMeta:
case Token.TokenKind.KeywordNot:
case Token.TokenKind.KeywordOr:
case Token.TokenKind.KeywordOtherwise:
case Token.TokenKind.KeywordSection:
case Token.TokenKind.KeywordShared:
case Token.TokenKind.KeywordThen:
case Token.TokenKind.KeywordTrue:
case Token.TokenKind.KeywordTry:
case Token.TokenKind.KeywordType:
return true;
default:
return false;
}
}
// Assumes a call to readPrimaryExpression has already happened.
export function isRecursivePrimaryExpressionNext(
state: ParseState,
tokenIndexStart: number = state.tokenIndex,
): boolean {
return (
// section-access-expression
// this.isOnTokenKind(TokenKind.Bang)
// field-access-expression
isTokenKind(state, Token.TokenKind.LeftBrace, tokenIndexStart) ||
// item-access-expression
isTokenKind(state, Token.TokenKind.LeftBracket, tokenIndexStart) ||
// invoke-expression
isTokenKind(state, Token.TokenKind.LeftParenthesis, tokenIndexStart)
);
}
// -----------------------------
// ---------- Asserts ----------
// -----------------------------
export function assertGetContextNodeMetadata(state: ParseState): ContextNodeMetadata {
const currentContextNode: ParseContext.TNode = Assert.asDefined(state.maybeCurrentContextNode);
const tokenStart: Token.Token = Assert.asDefined(currentContextNode.maybeTokenStart);
// inclusive token index
const tokenIndexEnd: number = state.tokenIndex - 1;
const tokenEnd: Token.Token = Assert.asDefined(state.lexerSnapshot.tokens[tokenIndexEnd]);
const tokenRange: Token.TokenRange = {
tokenIndexStart: currentContextNode.tokenIndexStart,
tokenIndexEnd,
positionStart: tokenStart.positionStart,
positionEnd: tokenEnd.positionEnd,
};
return {
id: currentContextNode.id,
maybeAttributeIndex: currentContextNode.maybeAttributeIndex,
tokenRange,
};
}
export function assertGetTokenAt(state: ParseState, tokenIndex: number): Token.Token {
const lexerSnapshot: LexerSnapshot = state.lexerSnapshot;
const maybeToken: Token.Token | undefined = lexerSnapshot.tokens[tokenIndex];
return Assert.asDefined(maybeToken, undefined, { tokenIndex });
}
// -------------------------------
// ---------- Csv Tests ----------
// -------------------------------
// All of these tests assume you're in a given context and have just read a `,`.
// Eg. testCsvEndLetExpression assumes you're in a LetExpression context and have just read a `,`.
export function testCsvContinuationLetExpression(
state: ParseState,
): ParseError.ExpectedCsvContinuationError | undefined {
if (state.maybeCurrentTokenKind === Token.TokenKind.KeywordIn) {
return new ParseError.ExpectedCsvContinuationError(
state.locale,
ParseError.CsvContinuationKind.LetExpression,
maybeCurrentTokenWithColumnNumber(state),
);
}
return undefined;
}
export function testCsvContinuationDanglingComma(
state: ParseState,
tokenKind: Token.TokenKind,
): ParseError.ExpectedCsvContinuationError | undefined {
if (state.maybeCurrentTokenKind === tokenKind) {
return new ParseError.ExpectedCsvContinuationError(
state.locale,
ParseError.CsvContinuationKind.DanglingComma,
maybeCurrentTokenWithColumnNumber(state),
);
} else {
return undefined;
}
}
// -------------------------------------
// ---------- Asserts / Tests ----------
// -------------------------------------
export function testIsOnTokenKind(
state: ParseState,
expectedTokenKind: Token.TokenKind,
): ParseError.ExpectedTokenKindError | undefined {
if (expectedTokenKind !== state.maybeCurrentTokenKind) {
const maybeToken: ParseError.TokenWithColumnNumber | undefined = maybeCurrentTokenWithColumnNumber(state);
return new ParseError.ExpectedTokenKindError(state.locale, expectedTokenKind, maybeToken);
} else {
return undefined;
}
}
export function testIsOnAnyTokenKind(
state: ParseState,
expectedAnyTokenKinds: ReadonlyArray<Token.TokenKind>,
): ParseError.ExpectedAnyTokenKindError | undefined {
const isError: boolean =
state.maybeCurrentTokenKind === undefined || !expectedAnyTokenKinds.includes(state.maybeCurrentTokenKind);
if (isError) {
const maybeToken: ParseError.TokenWithColumnNumber | undefined = maybeCurrentTokenWithColumnNumber(state);
return new ParseError.ExpectedAnyTokenKindError(state.locale, expectedAnyTokenKinds, maybeToken);
} else {
return undefined;
}
}
export function assertNoMoreTokens(state: ParseState): void {
if (state.tokenIndex === state.lexerSnapshot.tokens.length) {
return;
}
const token: Token.Token = assertGetTokenAt(state, state.tokenIndex);
throw new ParseError.UnusedTokensRemainError(
state.locale,
token,
state.lexerSnapshot.graphemePositionStartFrom(token),
);
}
export function assertNoOpenContext(state: ParseState): void {
Assert.isUndefined(state.maybeCurrentContextNode, undefined, {
contextNodeId: state.maybeCurrentContextNode?.id,
});
}
export function assertIsDoneParsing(state: ParseState): void {
assertNoMoreTokens(state);
assertNoOpenContext(state);
}
// -------------------------------------
// ---------- Error factories ----------
// -------------------------------------
export function unterminatedBracketError(state: ParseState): ParseError.UnterminatedSequence {
return unterminatedSequence(state, SequenceKind.Bracket);
}
export function unterminatedParenthesesError(state: ParseState): ParseError.UnterminatedSequence {
return unterminatedSequence(state, SequenceKind.Parenthesis);
}
function unterminatedSequence(state: ParseState, sequenceKind: SequenceKind): ParseError.UnterminatedSequence {
const token: Token.Token = assertGetTokenAt(state, state.tokenIndex);
return new ParseError.UnterminatedSequence(
state.locale,
sequenceKind,
token,
state.lexerSnapshot.graphemePositionStartFrom(token),
);
}
// ---------------------------------------------
// ---------- Column number factories ----------
// ---------------------------------------------
export function maybeCurrentTokenWithColumnNumber(state: ParseState): ParseError.TokenWithColumnNumber | undefined {
return maybeTokenWithColumnNumber(state, state.tokenIndex);
}
export function maybeTokenWithColumnNumber(
state: ParseState,
tokenIndex: number,
): ParseError.TokenWithColumnNumber | undefined {
const maybeToken: Token.Token | undefined = state.lexerSnapshot.tokens[tokenIndex];
if (maybeToken === undefined) {
return undefined;
}
const currentToken: Token.Token = maybeToken;
return {
token: currentToken,
columnNumber: state.lexerSnapshot.columnNumberStartFrom(currentToken),
};
}
interface ContextNodeMetadata {
readonly id: number;
readonly maybeAttributeIndex: number | undefined;
readonly tokenRange: Token.TokenRange;
} | the_stack |
import React, { useCallback } from 'react';
import { FormattedDate, defineMessages, FormattedMessage } from 'react-intl';
import {
useParams,
Switch,
Route,
useRouteMatch,
Redirect,
} from 'react-router';
import {
ColonyRole,
ColonyVersion,
Extension,
extensionsIncompatibilityMap,
} from '@colony/colony-js';
import BreadCrumb, { Crumb } from '~core/BreadCrumb';
import Heading from '~core/Heading';
import Warning from '~core/Warning';
import Icon from '~core/Icon';
import NetworkContractUpgradeDialog from '~dashboard/NetworkContractUpgradeDialog';
import { useDialog, ConfirmDialog } from '~core/Dialog';
import {
Colony,
useLoggedInUser,
useColonyExtensionQuery,
useNetworkExtensionVersionQuery,
} from '~data/index';
import { SpinnerLoader } from '~core/Preloaders';
import { DialogActionButton } from '~core/Button';
import { Table, TableBody, TableCell, TableRow } from '~core/Table';
import { useTransformer } from '~utils/hooks';
import { useEnabledExtensions } from '~utils/hooks/useEnabledExtensions';
import extensionData from '~data/staticData/extensionData';
import MaskedAddress from '~core/MaskedAddress';
import { ActionTypes } from '~redux/index';
import PermissionsLabel from '~core/PermissionsLabel';
import ExternalLink from '~core/ExternalLink';
import DetailsWidgetUser from '~core/DetailsWidgetUser';
import {
COLONY_EXTENSION_DETAILS_ROUTE,
COLONY_EXTENSION_SETUP_ROUTE,
} from '~routes/index';
import { DEFAULT_NETWORK_INFO } from '~constants';
import { checkIfNetworkIsAllowed } from '~utils/networks';
import { getAllUserRoles } from '../../../transformers';
import { hasRoot } from '../../../users/checks';
import styles from './ExtensionDetails.css';
import ExtensionActionButton from './ExtensionActionButton';
import ExtensionSetup from './ExtensionSetup';
import ExtensionStatus from './ExtensionStatus';
import ExtensionUpgrade from './ExtensionUpgrade';
import ExtensionUninstallConfirmDialog from './ExtensionUninstallConfirmDialog';
import { ExtensionsMSG } from './extensionsMSG';
const TERMS_AND_CONDITIONS_LINK = 'https://colony.io/pdf/terms.pdf';
const MSG = defineMessages({
title: {
id: 'dashboard.Extensions.ExtensionDetails.title',
defaultMessage: 'Extensions',
},
buttonAdd: {
id: 'dashboard.Extensions.ExtensionDetails.buttonAdd',
defaultMessage: 'Add',
},
status: {
id: 'dashboard.Extensions.ExtensionDetails.status',
defaultMessage: 'Status',
},
installedBy: {
id: 'dashboard.Extensions.ExtensionDetails.installedBy',
defaultMessage: 'Installed by',
},
dateCreated: {
id: 'dashboard.Extensions.ExtensionDetails.dateCreated',
defaultMessage: 'Date created',
},
dateInstalled: {
id: 'dashboard.Extensions.ExtensionDetails.dateInstalled',
defaultMessage: 'Date installed',
},
latestVersion: {
id: 'dashboard.Extensions.ExtensionDetails.latestVersion',
defaultMessage: 'Latest version',
},
versionInstalled: {
id: 'dashboard.Extensions.ExtensionDetails.versionInstalled',
defaultMessage: 'Version installed',
},
contractAddress: {
id: 'dashboard.Extensions.ExtensionDetails.contractAddress',
defaultMessage: 'Contract address',
},
developer: {
id: 'dashboard.Extensions.ExtensionDetails.developer',
defaultMessage: 'Developer',
},
permissionsNeeded: {
id: 'dashboard.Extensions.ExtensionDetails.permissionsNeeded',
defaultMessage: 'Permissions the extension needs in the colony:',
},
buttonUninstall: {
id: 'dashboard.Extensions.ExtensionDetails.buttonUninstall',
defaultMessage: 'Uninstall',
},
buttonDeprecate: {
id: 'dashboard.Extensions.ExtensionDetails.buttonDeprecate',
defaultMessage: 'Deprecate',
},
headingDeprecate: {
id: 'dashboard.Extensions.ExtensionDetails.headingDeprecate',
defaultMessage: 'Deprecate extension',
},
textDeprecate: {
id: 'dashboard.Extensions.ExtensionDetails.textDeprecate',
defaultMessage: `This extension must first be deprecated if you wish to uninstall it. After deprecation, any actions using this extension already ongoing may be completed, but it will no longer be possible to create new actions requiring this extension. Are you sure you wish to proceed?`,
},
headingUninstall: {
id: 'dashboard.Extensions.ExtensionDetails.headingUninstall',
defaultMessage: 'Uninstall extension',
},
textUninstall: {
id: 'dashboard.Extensions.ExtensionDetails.textUninstall',
defaultMessage: `This extension is currently deprecated, and may be uninstalled. Doing so will remove it from the colony and any processes requiring it will no longer work. Are you sure you wish to proceed?`,
},
setup: {
id: 'dashboard.Extensions.ExtensionDetails.setup',
defaultMessage: 'Setup',
},
warning: {
id: 'dashboard.Extensions.ExtensionDetails.warning',
defaultMessage: `This extension is incompatible with your current colony version. You must upgrade your colony before installing it.`,
},
});
interface Props {
colony: Colony;
}
const ExtensionDetails = ({
colony: { colonyAddress, version: colonyVersion },
colony,
}: Props) => {
const { colonyName, extensionId } = useParams<{
colonyName: string;
extensionId: string;
}>();
const match = useRouteMatch();
const onSetupRoute = useRouteMatch(COLONY_EXTENSION_SETUP_ROUTE);
const { walletAddress, username, ethereal, networkId } = useLoggedInUser();
const isNetworkAllowed = checkIfNetworkIsAllowed(networkId);
const openUpgradeVersionDialog = useDialog(NetworkContractUpgradeDialog);
const { isVotingExtensionEnabled } = useEnabledExtensions({
colonyAddress,
});
const handleUpgradeColony = useCallback(
() =>
openUpgradeVersionDialog({
colony,
isVotingExtensionEnabled,
}),
[colony, openUpgradeVersionDialog, isVotingExtensionEnabled],
);
const { data, loading } = useColonyExtensionQuery({
variables: { colonyAddress, extensionId },
});
const { data: networkExtensionData } = useNetworkExtensionVersionQuery({
variables: { extensionId },
});
const [networkExtension] =
networkExtensionData?.networkExtensionVersion || [];
const latestNetworkExtensionVersion = networkExtension?.version || 0;
const { contractAddressLink } = DEFAULT_NETWORK_INFO;
const hasRegisteredProfile = !!username && !ethereal;
const allUserRoles = useTransformer(getAllUserRoles, [colony, walletAddress]);
const isSupportedColonyVersion =
parseInt(colonyVersion || '1', 10) >= ColonyVersion.LightweightSpaceship;
const extension = extensionData[extensionId];
/*
* Either the current version (only if it's installed), or the latest version
* available from the network (since that's the one that it going to get
* installed)
*/
extension.currentVersion =
data?.colonyExtension?.details?.version || latestNetworkExtensionVersion;
const canInstall =
hasRegisteredProfile &&
hasRoot(allUserRoles) &&
!ethereal &&
isNetworkAllowed;
const installedExtension = data ? data.colonyExtension : null;
const extensionInstallable = !onSetupRoute && canInstall;
const extensionUninstallable = canInstall && extension?.uninstallable;
const extesionCanBeInstalled =
extensionInstallable && !installedExtension?.details?.initialized;
const extesionCanBeEnabled =
extensionInstallable &&
!!installedExtension?.details?.missingPermissions?.length;
const extesionCanBeDeprecated =
extensionUninstallable &&
installedExtension &&
!installedExtension?.details?.deprecated;
const extesionCanBeUninstalled =
extensionUninstallable && installedExtension?.details.deprecated;
const extensionCanBeUpgraded =
hasRegisteredProfile &&
!(extesionCanBeInstalled || extesionCanBeEnabled) &&
latestNetworkExtensionVersion > extension.currentVersion;
const extensionEnabled =
installedExtension &&
installedExtension.details.initialized &&
!installedExtension.details.deprecated;
const extensionCompatible = extension?.currentVersion
? !extensionsIncompatibilityMap[extensionId][extension.currentVersion].find(
(version: number) => version === parseInt(colonyVersion, 10),
)
: false;
let tableData;
if (installedExtension) {
tableData = [
{
label: MSG.status,
value: <ExtensionStatus installedExtension={installedExtension} />,
},
{
label: MSG.installedBy,
value: (
<span className={styles.installedBy}>
<DetailsWidgetUser
walletAddress={installedExtension.details.installedBy}
/>
</span>
),
},
{
label: MSG.dateInstalled,
value: <FormattedDate value={installedExtension.details.installedAt} />,
},
{
label: MSG.versionInstalled,
value: `v${extension.currentVersion}`,
},
{
label: MSG.contractAddress,
value: (
<ExternalLink
href={`${contractAddressLink}/${installedExtension.address}`}
>
<MaskedAddress address={installedExtension.address} />
</ExternalLink>
),
},
{
label: MSG.developer,
value: 'Colony',
},
];
} else {
tableData = [
{
label: MSG.status,
value: <ExtensionStatus installedExtension={installedExtension} />,
},
{
label: MSG.dateCreated,
value: <FormattedDate value={extension.createdAt} />,
},
{
label: MSG.latestVersion,
value: `v${extension.currentVersion}`,
icon: !extensionCompatible && (
<Icon name="triangle-warning" title={MSG.warning} />
),
},
{
label: MSG.developer,
value: 'Colony',
},
];
}
const extensionUrl = `/colony/${colonyName}/extensions/${extensionId}`;
const breadCrumbs: Crumb[] = [
[MSG.title, `/colony/${colonyName}/extensions`],
[extension.name, match.url === extensionUrl ? '' : extensionUrl],
];
if (match.path === COLONY_EXTENSION_SETUP_ROUTE) {
breadCrumbs.push(MSG.setup);
}
if (loading) {
return <SpinnerLoader appearance={{ theme: 'primary', size: 'massive' }} />;
}
const uninstallModalProps = {
[Extension.VotingReputation]: {
heading: ExtensionsMSG.headingVotingUninstall,
children: <Warning text={ExtensionsMSG.textVotingUninstall} />,
},
[Extension.OneTxPayment]: {
heading: ExtensionsMSG.headingDefaultUninstall,
children: <FormattedMessage {...ExtensionsMSG.textDefaultUninstall} />,
},
DEFAULT: {
heading: ExtensionsMSG.headingDefaultUninstall,
children: <FormattedMessage {...ExtensionsMSG.textDefaultUninstall} />,
},
};
return (
<div className={styles.main}>
<div>
<BreadCrumb elements={breadCrumbs} />
<hr className={styles.headerLine} />
<div>
{!extensionCompatible && (
<Warning
text={MSG.warning}
buttonText={{ id: 'button.upgrade' }}
handleClick={handleUpgradeColony}
disabled={!canInstall}
/>
)}
<Switch>
<Route
exact
path={COLONY_EXTENSION_DETAILS_ROUTE}
component={() => (
<div className={styles.extensionText}>
<Heading
tagName="h3"
appearance={{
size: 'medium',
margin: 'small',
theme: 'dark',
}}
text={extension.header || extension.name}
/>
<FormattedMessage
{...extension.descriptionLong}
values={{
h4: (chunks) => (
<Heading
tagName="h4"
appearance={{ size: 'medium', margin: 'small' }}
text={chunks}
/>
),
}}
/>
{extension.info && (
<div className={styles.extensionSubtext}>
<FormattedMessage
{...extension.info}
values={{
link: (
<ExternalLink
text={extension.termsCondition}
href={TERMS_AND_CONDITIONS_LINK}
/>
),
}}
/>
</div>
)}
{extensionEnabled &&
extension.enabledExtensionBody &&
extension.enabledExtensionBody({ colony })}
</div>
)}
/>
<Route
exact
path={COLONY_EXTENSION_SETUP_ROUTE}
component={() => {
if (
!canInstall ||
(installedExtension?.details.initialized &&
!installedExtension?.details.missingPermissions.length)
) {
return <Redirect to={extensionUrl} />;
}
return installedExtension ? (
<ExtensionSetup
extension={extension}
installedExtension={installedExtension}
colonyAddress={colonyAddress}
/>
) : (
<Redirect to={extensionUrl} />
);
}}
/>
</Switch>
</div>
</div>
<aside>
<div className={styles.extensionDetails}>
<hr className={styles.headerLine} />
<div className={styles.buttonWrapper}>
{(extesionCanBeInstalled || extesionCanBeEnabled) &&
isNetworkAllowed && (
<ExtensionActionButton
colonyAddress={colonyAddress}
colonyVersion={colonyVersion}
installedExtension={installedExtension}
extension={extension}
extensionCompatible={extensionCompatible}
/>
)}
{extensionCanBeUpgraded && isNetworkAllowed && (
<ExtensionUpgrade
colony={colony}
extension={extension}
canUpgrade={canInstall}
/>
)}
</div>
<Table appearance={{ theme: 'lined' }}>
<TableBody>
{tableData.map(({ label, value, icon }) => (
<TableRow key={label.id}>
<TableCell className={styles.cellLabel}>
<FormattedMessage {...label} />
{icon && <span className={styles.iconWrapper}>{icon}</span>}
</TableCell>
<TableCell className={styles.cellData}>{value}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{extesionCanBeDeprecated ? (
<div className={styles.buttonUninstall}>
<DialogActionButton
dialog={ConfirmDialog}
dialogProps={{
heading: MSG.headingDeprecate,
children: <FormattedMessage {...MSG.textDeprecate} />,
}}
appearance={{ theme: 'blue' }}
submit={ActionTypes.COLONY_EXTENSION_DEPRECATE}
error={ActionTypes.COLONY_EXTENSION_DEPRECATE_ERROR}
success={ActionTypes.COLONY_EXTENSION_DEPRECATE_SUCCESS}
text={MSG.buttonDeprecate}
values={{ colonyAddress, extensionId }}
disabled={!isSupportedColonyVersion || !isNetworkAllowed}
/>
</div>
) : null}
{extesionCanBeUninstalled ? (
<div className={styles.buttonUninstall}>
<DialogActionButton
dialog={ExtensionUninstallConfirmDialog}
dialogProps={
uninstallModalProps[extensionId] ||
uninstallModalProps.DEFAULT
}
appearance={{ theme: 'blue' }}
submit={ActionTypes.COLONY_EXTENSION_UNINSTALL}
error={ActionTypes.COLONY_EXTENSION_UNINSTALL_ERROR}
success={ActionTypes.COLONY_EXTENSION_UNINSTALL_SUCCESS}
text={MSG.buttonUninstall}
values={{ colonyAddress, extensionId }}
disabled={!isSupportedColonyVersion || !isNetworkAllowed}
/>
</div>
) : null}
<div className={styles.permissions}>
<Heading
appearance={{ size: 'normal' }}
tagName="h4"
text={MSG.permissionsNeeded}
/>
{extension.neededColonyPermissions.map((permission: ColonyRole) => (
<PermissionsLabel key={permission} permission={permission} />
))}
</div>
</div>
</aside>
</div>
);
};
export default ExtensionDetails; | the_stack |
import Lucky from './lucky'
import { UserConfigType, ImgType, ImgItemType, Tuple } from '../types/index'
import SlotMachineConfig, {
BlockType,
PrizeType,
SlotType,
DefaultConfigType,
DefaultStyleType,
EndCallbackType,
} from '../types/slot'
import {
get, has,
isExpectType,
removeEnter,
computePadding,
hasBackground,
computeRange,
splitText,
getSortedArrayByIndex
} from '../utils/index'
import { roundRectByArc } from '../utils/math'
import { quad } from '../utils/tween'
export default class SlotMachine extends Lucky {
// 背景
private blocks: Array<BlockType> = []
// 奖品列表
private prizes: Array<PrizeType> = []
// 插槽列表
private slots: Array<SlotType> = []
// 默认配置
private defaultConfig: DefaultConfigType = {}
private _defaultConfig: Required<DefaultConfigType> = {} as Required<DefaultConfigType>
// 默认样式
private defaultStyle: DefaultStyleType = {}
private _defaultStyle: Required<DefaultStyleType> = {} as Required<DefaultStyleType>
private endCallback: EndCallbackType = () => {}
// 离屏canvas
private _offscreenCanvas?: HTMLCanvasElement
private cellWidth = 0 // 格子宽度
private cellHeight = 0 // 格子高度
private cellAndSpacing = 0 // 格子+间距
private widthAndSpacing = 0 // 格子宽度+列间距
private heightAndSpacing = 0 // 格子高度+行间距
private FPS = 16.6 // 屏幕刷新率
private scroll: number[] = [] // 滚动的长度
private stopScroll: number[] = [] // 刻舟求剑
private endScroll: number[] = [] // 最终停止的长度
private startTime = 0 // 开始游戏的时间
private endTime = 0 // 开始停止的时间
/**
* 游戏当前的阶段
* step = 0 时, 游戏尚未开始
* step = 1 时, 此时处于加速阶段
* step = 2 时, 此时处于匀速阶段
* step = 3 时, 此时处于减速阶段
*/
private step: 0 | 1 | 2 | 3 = 0
/**
* 中奖索引
* prizeFlag = undefined 时, 处于开始抽奖阶段, 正常旋转
* prizeFlag >= 0 时, 说明stop方法被调用, 并且传入了中奖索引
* prizeFlag === -1 时, 说明stop方法被调用, 并且传入了负值, 本次抽奖无效
*/
private prizeFlag: number[] | undefined = void 0
// 奖品区域几何信息
private prizeArea?: { x: number, y: number, w: number, h: number }
// 图片缓存
private ImageCache = new Map()
/**
* 老虎机构造器
* @param config 配置项
* @param data 抽奖数据
*/
constructor (config: UserConfigType, data: SlotMachineConfig) {
super(config, {
width: data.width,
height: data.height
})
this.initData(data)
this.initWatch()
this.initComputed()
// 创建前回调函数
config.beforeCreate?.call(this)
// 首次初始化
this.init()
}
protected resize(): void {
super.resize()
this.draw()
this.config.afterResize?.()
}
protected initLucky (): void {
this.cellWidth = 0
this.cellHeight = 0
this.cellAndSpacing = 0
this.widthAndSpacing = 0
this.heightAndSpacing = 0
this.FPS = 16.6
this.scroll = []
this.stopScroll = []
this.endScroll = []
this.startTime = 0
this.endTime = 0
this.prizeFlag = void 0
this.step = 0
super.initLucky()
}
/**
* 初始化数据
* @param data
*/
private initData (data: SlotMachineConfig): void {
this.$set(this, 'width', data.width)
this.$set(this, 'height', data.height)
this.$set(this, 'blocks', data.blocks || [])
this.$set(this, 'prizes', data.prizes || [])
this.$set(this, 'slots', data.slots || [])
this.$set(this, 'defaultConfig', data.defaultConfig || {})
this.$set(this, 'defaultStyle', data.defaultStyle || {})
this.$set(this, 'endCallback', data.end)
}
/**
* 初始化属性计算
*/
private initComputed (): void {
// 默认配置
this.$computed(this, '_defaultConfig', () => {
const config = {
mode: 'vertical',
rowSpacing: 0,
colSpacing: 5,
speed: 20,
direction: 1,
accelerationTime: 2500,
decelerationTime: 2500,
...this.defaultConfig
}
config.rowSpacing = this.getLength(config.rowSpacing)
config.colSpacing = this.getLength(config.colSpacing)
return config
})
// 默认样式
this.$computed(this, '_defaultStyle', () => {
return {
borderRadius: 0,
fontColor: '#000',
fontSize: '18px',
fontStyle: 'sans-serif',
fontWeight: '400',
background: 'rgba(0,0,0,0)',
wordWrap: true,
lengthLimit: '90%',
...this.defaultStyle
}
})
}
/**
* 初始化观察者
*/
private initWatch (): void {
// 重置宽度
this.$watch('width', (newVal: string | number) => {
this.data.width = newVal
this.resize()
})
// 重置高度
this.$watch('height', (newVal: string | number) => {
this.data.height = newVal
this.resize()
})
// 监听 blocks 数据的变化
this.$watch('blocks', (newData: Array<BlockType>) => {
this.initImageCache()
}, { deep: true })
// 监听 prizes 数据的变化
this.$watch('prizes', (newData: Array<PrizeType>) => {
this.initImageCache()
}, { deep: true })
// 监听 prizes 数据的变化
this.$watch('slots', (newData: Array<PrizeType>) => {
this.drawOffscreenCanvas()
this.draw()
}, { deep: true })
this.$watch('defaultConfig', () => this.draw(), { deep: true })
this.$watch('defaultStyle', () => this.draw(), { deep: true })
this.$watch('endCallback', () => this.init())
}
/**
* 初始化 canvas 抽奖
*/
public async init (): Promise<void> {
this.initLucky()
const { config } = this
// 初始化前回调函数
config.beforeInit?.call(this)
// 先绘制一次
this.drawOffscreenCanvas()
this.draw()
// 异步加载图片
await this.initImageCache()
// 初始化后回调函数
config.afterInit?.call(this)
}
private initImageCache (): Promise<void> {
return new Promise((resolve) => {
const willUpdateImgs = {
blocks: this.blocks.map(block => block.imgs),
prizes: this.prizes.map(prize => prize.imgs),
}
;(<(keyof typeof willUpdateImgs)[]>Object.keys(willUpdateImgs)).forEach(imgName => {
const willUpdate = willUpdateImgs[imgName]
// 循环遍历所有图片
const allPromise: Promise<void>[] = []
willUpdate && willUpdate.forEach((imgs, cellIndex) => {
imgs && imgs.forEach((imgInfo, imgIndex) => {
allPromise.push(this.loadAndCacheImg(imgName, cellIndex, imgIndex))
})
})
Promise.all(allPromise).then(() => {
this.drawOffscreenCanvas()
this.draw()
resolve()
})
})
})
}
/**
* 根据索引单独加载指定图片并缓存
* @param cellName 模块名称
* @param cellIndex 模块索引
* @param imgName 模块对应的图片缓存
* @param imgIndex 图片索引
*/
private async loadAndCacheImg (
cellName: 'blocks' | 'prizes',
cellIndex: number,
imgIndex: number
): Promise<void> {
return new Promise((resolve, reject) => {
let cell: BlockType | PrizeType = this[cellName][cellIndex]
if (!cell || !cell.imgs) return
const imgInfo = cell.imgs[imgIndex]
if (!imgInfo) return
// 异步加载图片
this.loadImg(imgInfo.src, imgInfo).then(async currImg => {
if (typeof imgInfo.formatter === 'function') {
currImg = await Promise.resolve(imgInfo.formatter.call(this, currImg))
}
this.ImageCache.set(imgInfo['src'], currImg)
resolve()
}).catch(err => {
console.error(`${cellName}[${cellIndex}].imgs[${imgIndex}] ${err}`)
reject()
})
})
}
/**
* 绘制离屏canvas
*/
protected drawOffscreenCanvas (): void {
const { _defaultConfig, _defaultStyle } = this
const { w, h } = this.drawBlocks()!
// 计算单一奖品格子的宽度和高度
const prizesLen = this.prizes.length
const { cellWidth, cellHeight, widthAndSpacing, heightAndSpacing } = this.displacementWidthOrHeight()
const defaultOrder = new Array(prizesLen).fill(void 0).map((v, i) => i)
let maxOrderLen = 0, maxOffWidth = 0, maxOffHeight = 0
this.slots.forEach((slot, slotIndex) => {
// 初始化 scroll 的值
if (this.scroll[slotIndex] === void 0) this.scroll[slotIndex] = 0
// 如果没有order属性, 就填充prizes
slot.order = slot.order || defaultOrder
// 计算最大值
const currLen = slot.order.length
maxOrderLen = Math.max(maxOrderLen, currLen)
maxOffWidth = Math.max(maxOffWidth, w + widthAndSpacing * currLen)
maxOffHeight = Math.max(maxOffHeight, h + heightAndSpacing * currLen)
})
// 创建一个离屏Canvas来存储画布的内容
const { _offscreenCanvas, _ctx } = this.getOffscreenCanvas(maxOffWidth, maxOffHeight)!
this._offscreenCanvas = _offscreenCanvas
// 绘制插槽
this.slots.forEach((slot, slotIndex) => {
const cellX = cellWidth * slotIndex
const cellY = cellHeight * slotIndex
let lengthOfCopy = 0
// 绘制奖品
const newPrizes = getSortedArrayByIndex(this.prizes, slot.order!)
// 如果没有奖品则打断逻辑
if (!newPrizes.length) return
newPrizes.forEach((cell, cellIndex) => {
if (!cell) return
const orderIndex = slot.order![cellIndex]
const prizesX = widthAndSpacing * cellIndex + _defaultConfig.colSpacing / 2
const prizesY = heightAndSpacing * cellIndex + _defaultConfig.rowSpacing / 2
const [_x, _y, spacing] = this.displacement(
[cellX, prizesY, heightAndSpacing],
[prizesX, cellY, widthAndSpacing]
)
lengthOfCopy += spacing
// 绘制背景
const background = cell.background || _defaultStyle.background
if (hasBackground(background)) {
const borderRadius = this.getLength(has(cell, 'borderRadius') ? cell.borderRadius : _defaultStyle.borderRadius)
roundRectByArc(_ctx, _x, _y, cellWidth, cellWidth, borderRadius)
_ctx.fillStyle = background
_ctx.fill()
}
// 绘制图片
cell.imgs && cell.imgs.forEach((imgInfo, imgIndex) => {
const cellImg = this.ImageCache.get(imgInfo.src)
if (!cellImg) return
const [trueWidth, trueHeight] = this.computedWidthAndHeight(cellImg, imgInfo, cellWidth, cellHeight)
const [xAxis, yAxis] = [
_x + this.getOffsetX(trueWidth, cellWidth) + this.getLength(imgInfo.left, cellWidth),
_y + this.getLength(imgInfo.top, cellHeight)
]
this.drawImage(_ctx, cellImg, xAxis, yAxis, trueWidth, trueHeight)
})
// 绘制文字
cell.fonts && cell.fonts.forEach(font => {
// 字体样式
const style = font.fontStyle || _defaultStyle.fontStyle
// 字体加粗
const fontWeight = font.fontWeight || _defaultStyle.fontWeight
// 字体大小
const size = this.getLength(font.fontSize || _defaultStyle.fontSize)
// 字体行高
const lineHeight = font.lineHeight || _defaultStyle.lineHeight || font.fontSize || _defaultStyle.fontSize
const wordWrap = has(font, 'wordWrap') ? font.wordWrap : _defaultStyle.wordWrap
const lengthLimit = font.lengthLimit || _defaultStyle.lengthLimit
const lineClamp = font.lineClamp || _defaultStyle.lineClamp
_ctx.font = `${fontWeight} ${size >> 0}px ${style}`
_ctx.fillStyle = font.fontColor || _defaultStyle.fontColor
let lines = [], text = String(font.text)
// 计算文字换行
if (wordWrap) {
// 最大宽度
let maxWidth = this.getLength(lengthLimit, cellWidth)
lines = splitText(_ctx, removeEnter(text), () => maxWidth, lineClamp)
} else {
lines = text.split('\n')
}
lines.forEach((line, lineIndex) => {
_ctx.fillText(
line,
_x + this.getOffsetX(_ctx.measureText(line).width, cellWidth) + this.getLength(font.left, cellWidth),
_y + this.getLength(font.top, cellHeight) + (lineIndex + 1) * this.getLength(lineHeight)
)
})
})
})
const [_x, _y, _w, _h] = this.displacement(
[cellX, 0, cellWidth, lengthOfCopy],
[0, cellY, lengthOfCopy, cellHeight]
)
let drawLen = lengthOfCopy
while (drawLen < maxOffHeight + lengthOfCopy) {
const [drawX, drawY] = this.displacement([_x, drawLen], [drawLen, _y])
this.drawImage(
_ctx, _offscreenCanvas,
_x, _y, _w, _h,
drawX, drawY, _w, _h
)
drawLen += lengthOfCopy
}
})
}
/**
* 绘制背景区域
*/
protected drawBlocks (): SlotMachine['prizeArea'] {
const { config, ctx, _defaultConfig, _defaultStyle } = this
// 绘制背景区域, 并计算奖品区域
return this.prizeArea = this.blocks.reduce(({x, y, w, h}, block, blockIndex) => {
const [paddingTop, paddingBottom, paddingLeft, paddingRight] = computePadding(block, this.getLength.bind(this))
const r = block.borderRadius ? this.getLength(block.borderRadius) : 0
// 绘制边框
const background = block.background || _defaultStyle.background
if (hasBackground(background)) {
roundRectByArc(ctx, x, y, w, h, r)
ctx.fillStyle = background
ctx.fill()
}
// 绘制图片
block.imgs && block.imgs.forEach((imgInfo, imgIndex) => {
const blockImg = this.ImageCache.get(imgInfo.src)
if (!blockImg) return
// 绘制图片
const [trueWidth, trueHeight] = this.computedWidthAndHeight(blockImg, imgInfo, w, h)
const [xAxis, yAxis] = [this.getOffsetX(trueWidth, w) + this.getLength(imgInfo.left, w), this.getLength(imgInfo.top, h)]
this.drawImage(ctx, blockImg, x + xAxis, y + yAxis, trueWidth, trueHeight)
})
return {
x: x + paddingLeft,
y: y + paddingTop,
w: w - paddingLeft - paddingRight,
h: h - paddingTop - paddingBottom
}
}, { x: 0, y: 0, w: this.boxWidth, h: this.boxHeight })
}
/**
* 绘制老虎机抽奖
*/
protected draw (): void {
const { config, ctx, _defaultConfig, _defaultStyle } = this
// 触发绘制前回调
config.beforeDraw?.call(this, ctx)
// 清空画布
ctx.clearRect(0, 0, this.boxWidth, this.boxHeight)
// 绘制背景
const { x, y, w, h } = this.drawBlocks()!
// 绘制插槽
if (!this._offscreenCanvas) return
const { cellWidth, cellHeight, cellAndSpacing, widthAndSpacing, heightAndSpacing } = this
this.slots.forEach((slot, slotIndex) => {
// 绘制临界点
const _p = cellAndSpacing * slot.order!.length
// 调整奖品垂直居中
const start = this.displacement(-(h - heightAndSpacing) / 2, -(w - widthAndSpacing) / 2)
let scroll = this.scroll[slotIndex] + start
// scroll 会无限累加 1 / -1
if (scroll < 0) {
scroll = scroll % _p + _p
}
if (scroll > _p) {
scroll = scroll % _p
}
const [sx, sy, sw, sh] = this.displacement(
[cellWidth * slotIndex, scroll, cellWidth, h],
[scroll, cellHeight * slotIndex, w, cellHeight]
)
const [dx, dy, dw, dh] = this.displacement(
[x + widthAndSpacing * slotIndex, y, cellWidth, h],
[x, y + heightAndSpacing * slotIndex, w, cellHeight]
)
this.drawImage(ctx, this._offscreenCanvas!, sx, sy, sw, sh, dx, dy, dw, dh)
})
}
/**
* 刻舟求剑
*/
private carveOnGunwaleOfAMovingBoat (): void {
const { _defaultConfig, prizeFlag, cellAndSpacing } = this
// 记录开始停止的时间戳
this.endTime = Date.now()
this.slots.forEach((slot, slotIndex) => {
const order = slot.order!
if (!order.length) return
const speed = slot.speed || _defaultConfig.speed
const direction = slot.direction || _defaultConfig.direction
const orderIndex = order.findIndex(prizeIndex => prizeIndex === prizeFlag![slotIndex])
const _p = cellAndSpacing * order.length
const stopScroll = this.stopScroll[slotIndex] = this.scroll[slotIndex]
let i = 0
while (++i) {
const endScroll = cellAndSpacing * orderIndex + (_p * i * direction) - stopScroll
const currSpeed = quad.easeOut(this.FPS, stopScroll, endScroll, _defaultConfig.decelerationTime) - stopScroll
if (Math.abs(currSpeed) > speed) {
this.endScroll[slotIndex] = endScroll
break
}
}
})
}
/**
* 对外暴露: 开始抽奖方法
*/
public play (): void {
if (this.step !== 0) return
// 记录开始游戏的时间
this.startTime = Date.now()
// 清空中奖索引
this.prizeFlag = void 0
// 开始加速
this.step = 1
// 触发回调
this.config.afterStart?.()
// 开始渲染
this.run()
}
public stop (index: number | number[]): void {
if (this.step === 0 || this.step === 3) return
// 设置中奖索引
if (typeof index === 'number') {
this.prizeFlag = new Array(this.slots.length).fill(index)
} else if (isExpectType(index, 'array')) {
if (index.length === this.slots.length) {
this.prizeFlag = index
} else {
this.stop(-1)
return console.error(`stop([${index}]) 参数长度的不正确`)
}
} else {
this.stop(-1)
return console.error(`stop() 无法识别的参数类型 ${typeof index}`)
}
// 如果包含负数则停止游戏, 反之则继续游戏
if (this.prizeFlag?.includes(-1)) {
this.prizeFlag = []
// 停止游戏
this.step = 0
} else {
// 进入匀速
this.step = 2
}
}
/**
* 让游戏动起来
* @param num 记录帧动画执行多少次
*/
private run (num: number = 0): void {
const { rAF, step, prizeFlag, _defaultConfig, cellAndSpacing, slots } = this
const { accelerationTime, decelerationTime } = _defaultConfig
// 游戏结束
if (this.step === 0 && prizeFlag?.length === slots.length) {
let flag = prizeFlag[0]
for (let i = 0; i < slots.length; i++) {
const slot = slots[i], currFlag = prizeFlag[i]
if (!slot.order?.includes(currFlag) || flag !== currFlag) {
flag = -1
break
}
}
this.endCallback?.(this.prizes.find((prize, index) => index === flag) || void 0)
return
}
// 如果长度为 0 就直接停止游戏
if (prizeFlag !== void 0 && !prizeFlag.length) return
// 计算最终停止的位置
if (this.step === 3 && !this.endScroll.length) this.carveOnGunwaleOfAMovingBoat()
// 计算时间间隔
const startInterval = Date.now() - this.startTime
const endInterval = Date.now() - this.endTime
// 分别计算对应插槽的加速度
slots.forEach((slot, slotIndex) => {
const order = slot.order
if (!order || !order.length) return
const _p = cellAndSpacing * order.length
const speed = Math.abs(slot.speed || _defaultConfig.speed)
const direction = slot.direction || _defaultConfig.direction
let scroll = 0, prevScroll = this.scroll[slotIndex]
if (step === 1 || startInterval < accelerationTime) { // 加速阶段
// 记录帧率
this.FPS = startInterval / num
const currSpeed = quad.easeIn(startInterval, 0, speed, accelerationTime)
// 加速到最大速度后, 即可进入匀速阶段
if (currSpeed === speed) {
this.step = 2
}
scroll = (prevScroll + (currSpeed * direction)) % _p
} else if (step === 2) { // 匀速阶段
// 速度保持不变
scroll = (prevScroll + (speed * direction)) % _p
// 如果有 prizeFlag 有值, 则进入减速阶段
if (prizeFlag?.length === slots.length) {
this.step = 3
// 清空上一轮的位置信息
this.stopScroll = []
this.endScroll = []
}
} else if (step === 3 && endInterval) { // 减速阶段
// 开始缓慢停止
const stopScroll = this.stopScroll[slotIndex]
const endScroll = this.endScroll[slotIndex]
scroll = quad.easeOut(endInterval, stopScroll, endScroll, decelerationTime)
if (endInterval >= decelerationTime) {
this.step = 0
}
}
this.scroll[slotIndex] = scroll
})
this.draw()
rAF(this.run.bind(this, num + 1))
}
// 根据mode置换数值
private displacement<T> (a: T, b: T): T {
return this._defaultConfig.mode === 'horizontal' ? b : a
}
// 根据mode计算宽高
private displacementWidthOrHeight () {
const mode = this._defaultConfig.mode
const slotsLen = this.slots.length
const { colSpacing, rowSpacing } = this._defaultConfig
const { x, y, w, h } = this.prizeArea || this.drawBlocks()!
let cellWidth = 0, cellHeight = 0, widthAndSpacing = 0, heightAndSpacing = 0
if (mode === 'horizontal') {
cellHeight = this.cellHeight = (h - rowSpacing * (slotsLen - 1)) / slotsLen
cellWidth = this.cellWidth = cellHeight
} else {
cellWidth = this.cellWidth = (w - colSpacing * (slotsLen - 1)) / slotsLen
cellHeight = this.cellHeight = cellWidth
}
widthAndSpacing = this.widthAndSpacing = this.cellWidth + colSpacing
heightAndSpacing = this.heightAndSpacing = this.cellHeight + rowSpacing
if (mode === 'horizontal') {
this.cellAndSpacing = widthAndSpacing
} else {
this.cellAndSpacing = heightAndSpacing
}
return {
cellWidth,
cellHeight,
widthAndSpacing,
heightAndSpacing,
}
}
} | the_stack |
import {
BonusTypeEnum,
IEmployeeStatistics,
IEmployeeStatisticsFindInput,
DEFAULT_PROFIT_BASED_BONUS,
DEFAULT_REVENUE_BASED_BONUS,
IMonthAggregatedSplitExpense
} from '@gauzy/contracts';
import { Injectable } from '@nestjs/common';
import { EmployeeService } from '../employee/employee.service';
import { ExpenseService } from '../expense/expense.service';
import { IncomeService } from '../income/income.service';
import { Between, In, LessThanOrEqual, MoreThanOrEqual, IsNull } from 'typeorm';
import { subMonths, startOfMonth, endOfMonth } from 'date-fns';
import { EmployeeRecurringExpenseService } from '../employee-recurring-expense/employee-recurring-expense.service';
import { OrganizationRecurringExpenseService } from '../organization-recurring-expense/organization-recurring-expense.service';
@Injectable()
export class EmployeeStatisticsService {
private _monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
constructor(
private incomeService: IncomeService,
private expenseService: ExpenseService,
private employeeRecurringExpenseService: EmployeeRecurringExpenseService,
private employeeService: EmployeeService,
private organizationRecurringExpenseService: OrganizationRecurringExpenseService
) {}
async getStatisticsByEmployeeId(
employeeId: string,
findInput?: IEmployeeStatisticsFindInput
): Promise<IEmployeeStatistics> {
const mappedEmployeeIncome = (
await this.incomeService.findAllIncomes(
{
where: {
employee: {
id: employeeId
}
}
},
findInput ? findInput.valueDate.toString() : null
)
).items.map((e) => {
const obj = {};
const formattedDate = this._formatDate(e.valueDate);
obj[formattedDate] = +e.amount;
return obj;
});
const mappedEmployeeExpenses = (
await this.expenseService.findAllExpenses(
{
where: {
employee: {
id: employeeId
}
}
},
findInput ? findInput.valueDate.toString() : null
)
).items.map((e) => {
const obj = {};
const formattedDate = this._formatDate(e.valueDate);
obj[formattedDate] = +e.amount;
return obj;
});
const sortedEmployeeExpenses: Object[] = [];
mappedEmployeeExpenses.forEach((obj) => {
// tslint:disable-next-line: forin
for (const key in obj) {
const foundObject = sortedEmployeeExpenses.find((o) =>
o.hasOwnProperty(key)
);
if (foundObject) {
foundObject[key] += obj[key];
} else {
sortedEmployeeExpenses.push(obj);
}
}
});
const sortedEmployeeIncome: Object[] = [];
mappedEmployeeIncome.forEach((obj) => {
// tslint:disable-next-line: forin
for (const key in obj) {
const foundObject = sortedEmployeeIncome.find((o) =>
o.hasOwnProperty(key)
);
if (foundObject) {
foundObject[key] += obj[key];
} else {
sortedEmployeeIncome.push(obj);
}
}
});
let incomeStatistics = [];
let expenseStatistics = [];
this._getLast12months().forEach((month) => {
const incomeStatForTheMonth = sortedEmployeeIncome.find(
(incomeStat) => incomeStat.hasOwnProperty(month)
);
incomeStatForTheMonth
? incomeStatistics.push(incomeStatForTheMonth[month])
: incomeStatistics.push(0);
const expenseStatForTheMonth = sortedEmployeeExpenses.find(
(expenseStat) => expenseStat.hasOwnProperty(month)
);
expenseStatForTheMonth
? expenseStatistics.push(expenseStatForTheMonth[month])
: expenseStatistics.push(0);
});
const {
organization: { bonusType, bonusPercentage }
} = await this.employeeService.findOneByIdString(employeeId, {
relations: ['organization']
});
let profitStatistics = [];
let bonusStatistics = [];
expenseStatistics.forEach((expenseStat, index) => {
const income = incomeStatistics[index];
const profit = income - expenseStat;
const bonus = this.calculateEmployeeBonus(
bonusType,
bonusPercentage,
income,
profit
);
profitStatistics.push(profit);
bonusStatistics.push(bonus);
});
if (findInput && findInput.valueDate) {
expenseStatistics = expenseStatistics.filter(Number);
incomeStatistics = incomeStatistics.filter(Number);
profitStatistics = profitStatistics.filter(Number);
bonusStatistics = bonusStatistics.filter(Number);
}
return {
expenseStatistics,
incomeStatistics,
profitStatistics,
bonusStatistics
};
}
private _getLast12months() {
const start = new Date(Date.now()).getMonth() + 1;
const end = start + 11;
const currentYear = new Date(Date.now()).getFullYear() - 2000;
const monthsNeeded = [];
for (let i = start; i <= end; i++) {
if (i > 11) {
monthsNeeded.push(
this._monthNames[i - 12] + ` '${currentYear}`
);
} else {
monthsNeeded.push(this._monthNames[i] + ` '${currentYear - 1}`);
}
}
return monthsNeeded.reverse();
}
private _formatDate(date: Date) {
return `${this._monthNames[date.getMonth()]} '${
date.getFullYear() - 2000
}`;
}
/**
* Return bonus value based on the bonus type and percentage
* For revenue based bonus, bonus is calculated based on income
* For profit based bonus, bonus is calculated based on profit
*/
calculateEmployeeBonus = (
bonusType: string,
bonusPercentage: number,
income: number,
profit: number
) => {
bonusType = bonusType ? bonusType : BonusTypeEnum.PROFIT_BASED_BONUS;
switch (bonusType) {
case BonusTypeEnum.PROFIT_BASED_BONUS:
return (
(profit * (bonusPercentage || DEFAULT_PROFIT_BASED_BONUS)) /
100
);
case BonusTypeEnum.REVENUE_BASED_BONUS:
return (
(income *
(bonusPercentage || DEFAULT_REVENUE_BASED_BONUS)) /
100
);
default:
return 0;
}
};
/**
* helper function to create a date range to use in SQL between condition
*/
private _beforeDateFilter = (date: Date, lastNMonths: number) => {
return Between(
subMonths(startOfMonth(date), lastNMonths - 1).toISOString(),
endOfMonth(date).toISOString()
);
}
/**
* Gets all income records of one or more employees(using employeeId)
* in last N months(lastNMonths),
* till the specified Date(searchMonth)
* lastNMonths = 1, for last 1 month and 12 for an year
*/
employeeIncomeInNMonths = async (
employeeIds: string[],
searchMonth: Date,
lastNMonths: number,
organizationId: string
) =>
await this.incomeService.findAll({
select: [
'employeeId',
'valueDate',
'amount',
'currency',
'notes',
'isBonus'
],
join : {
alias: 'income',
leftJoinAndSelect: {
client: 'income.client'
}
},
where: {
organizationId,
employee: {
id: In(employeeIds)
},
valueDate: this._beforeDateFilter(searchMonth, lastNMonths)
},
order: {
valueDate: 'DESC'
}
});
/**
* Gets all expense records of one or more employees(using employeeId)
* in last N months(lastNMonths),
* till the specified Date(searchMonth)
* lastNMonths = 1, for last 1 month and 12 for an year
*/
employeeExpenseInNMonths = async (
employeeIds: string[],
searchMonth: Date,
lastNMonths: number,
organizationId: string
) =>
await this.expenseService.findAll({
select: [
'employeeId',
'valueDate',
'amount',
'currency',
'notes',
'vendor',
'category'
],
where: {
organizationId,
employee: {
id: In(employeeIds)
},
splitExpense: false,
valueDate: this._beforeDateFilter(searchMonth, lastNMonths)
},
order: {
valueDate: 'DESC'
},
relations: ['vendor', 'category']
});
/**
* Fetch all recurring expenses of one or more employees using employeeId
*/
employeeRecurringExpenses = async (
employeeIds: string[],
organizationId: string
) =>
await this.employeeRecurringExpenseService.findAll({
select: [
'employeeId',
'currency',
'value',
'categoryName',
'startDate',
'endDate'
],
where: {
employeeId: In(employeeIds),
organizationId
}
});
/**
* Gets all expense records of a employee's organization(employeeId)
* that were marked to be split among its employees,
* in last N months(lastNMonths),till the specified Date(searchMonth)
* lastNMonths = 1, for last 1 month and 12 for an year
*
* @returns {Promise<Map<string, IMonthAggregatedSplitExpense>>} A map with
* the key as 'month-year' for every month in the range & for which at least
* one expense is available
*/
employeeSplitExpenseInNMonths = async (
employeeId: string,
searchMonth: Date,
lastNMonths: number,
organizationId: string
): Promise<Map<string, IMonthAggregatedSplitExpense>> => {
// 1 Get Employee's Organization
const employee = await this.employeeService.findOneByOptions({
where: {
id: employeeId,
organizationId
},
relations: ['organization']
});
// 2 Find split expenses for Employee's Organization in last N months
const { items } = await this.expenseService.findAll({
select: ['valueDate', 'amount', 'currency', 'notes', 'category'],
where: {
organization: { id: employee.organization.id },
splitExpense: true,
valueDate: this._beforeDateFilter(searchMonth, lastNMonths)
},
relations: ['category']
});
const monthlySplitExpenseMap: Map<
string,
IMonthAggregatedSplitExpense
> = new Map();
// 3 Find the number of active employees for each month, and split the expenses among the active employees for each month
for (const expense of items) {
const key = `${expense.valueDate.getMonth()}-${expense.valueDate.getFullYear()}`;
const amount = Number(expense.amount);
if (monthlySplitExpenseMap.has(key)) {
// Update expense statistics values in map if key pre-exists
const stat = monthlySplitExpenseMap.get(key);
const splitAmount = amount / stat.splitAmong;
stat.splitExpense = Number(
(splitAmount + stat.splitExpense).toFixed(2)
);
stat.expense.push(expense);
} else {
// Add a new map entry if the key(month-year) does not already exist
const {
total: splitAmong
} = await this.employeeService.findWorkingEmployees(
employee.organization.id,
expense.valueDate,
false
);
const newStat = {
month: expense.valueDate.getMonth(),
year: expense.valueDate.getFullYear(),
splitExpense: Number((amount / splitAmong).toFixed(2)),
splitAmong,
expense: [expense]
};
monthlySplitExpenseMap.set(key, newStat);
}
}
return monthlySplitExpenseMap;
};
/**
* Fetch all recurring split expenses of the employee's Organization
*/
organizationRecurringSplitExpenses = async (
employeeId: string,
searchMonth: Date,
lastNMonths: number,
organizationId: string
) => {
// 1 Get Employee's Organization
const employee = await this.employeeService.findOneByOptions({
where: {
id: employeeId,
organizationId
},
relations: ['organization']
});
// 2 Fetch all split recurring expenses of the Employee's Organization
const {
items
} = await this.organizationRecurringExpenseService.findAll({
select: [
'currency',
'value',
'categoryName',
'startDate',
'endDate'
],
where: [
{
organizationId: employee.organization.id,
splitExpense: true,
startDate: LessThanOrEqual(endOfMonth(searchMonth)),
endDate: MoreThanOrEqual(
subMonths(startOfMonth(searchMonth), lastNMonths - 1)
)
},
{
organizationId: employee.organization.id,
splitExpense: true,
startDate: LessThanOrEqual(endOfMonth(searchMonth)),
endDate: IsNull()
}
]
});
const monthlySplitExpenseMap: Map<
string,
IMonthAggregatedSplitExpense
> = new Map();
/**
* Add Organization split recurring expense from the
* expense start date
* OR
* past N months to each month's expense, whichever is lesser
* Stop adding recurring expenses at the month where it was stopped
* OR
* till the input date
*/
for (const expense of items) {
// Find start date based on input date and X months.
const inputStartDate = subMonths(
startOfMonth(searchMonth),
lastNMonths - 1
);
/**
* Add Organization split recurring expense from the
* expense start date
* OR
* past N months to each month's expense, whichever is more recent
*/
const requiredStartDate =
expense.startDate > inputStartDate
? expense.startDate
: inputStartDate;
for (
const date = requiredStartDate;
date <= endOfMonth(searchMonth);
date.setMonth(date.getMonth() + 1)
) {
// Stop loading expense if the split recurring expense has ended before input date
if (expense.endDate && date > expense.endDate) break;
const key = `${date.getMonth()}-${date.getFullYear()}`;
const amount = Number(expense.value);
if (monthlySplitExpenseMap.has(key)) {
// Update expense statistics values in map if key pre-exists
const stat = monthlySplitExpenseMap.get(key);
const splitExpense = amount / stat.splitAmong;
stat.splitExpense = Number(
(splitExpense + stat.splitExpense).toFixed(2)
);
stat.recurringExpense.push(expense);
stat.valueDate = date;
} else {
const {
total: splitAmong
} = await this.employeeService.findWorkingEmployees(
employee.organization.id,
date,
false
);
// Add a new map entry if the key(month-year) does not already exist
const newStat: IMonthAggregatedSplitExpense = {
month: date.getMonth(),
year: date.getFullYear(),
splitExpense: Number((amount / splitAmong).toFixed(2)),
splitAmong,
recurringExpense: [expense],
valueDate: date
};
monthlySplitExpenseMap.set(key, newStat);
}
}
}
return monthlySplitExpenseMap;
};
} | the_stack |
import * as http from "http";
import * as https from "https";
import * as url from "url";
import * as qs from "qs";
import * as fs from "fs";
import * as zlib from "zlib";
import * as path from "path";
import * as formidable from "formidable";
import * as Mime from "mime";
import * as uuid from "uuid";
import * as etag from "etag";
import { BrowserFingerprint } from "browser_fingerprint";
import { api, config, utils, Server, Connection } from "../index";
import { ActionsStatus } from "../classes/actionProcessor";
export class WebServer extends Server {
server: http.Server | https.Server;
fingerPrinter: BrowserFingerprint;
sockets: { [id: string]: any };
constructor() {
super();
this.type = "web";
this.sockets = {};
this.attributes = {
canChat: false,
logConnections: false,
logExits: false,
sendWelcomeMessage: false,
verbs: [], // no verbs for connections of this type, as they are to be very short-lived
};
this.connectionCustomMethods = {
setHeader: (connection: Connection, key, value) => {
connection.rawConnection.res.setHeader(key, value);
},
setStatusCode: (connection: Connection, value) => {
connection.rawConnection.responseHttpCode = value;
},
pipe: (connection: Connection, buffer, headers) => {
for (const k in headers) {
//@ts-ignore
connection.setHeader(k, headers[k]);
}
if (typeof buffer === "string") {
buffer = Buffer.from(buffer);
}
connection.rawConnection.res.end(buffer);
},
};
}
async initialize() {
if (["api", "file"].indexOf(this.config.rootEndpointType) < 0) {
throw new Error("rootEndpointType can only be 'api' or 'file'");
}
if (
!this.config.urlPathForFiles &&
this.config.rootEndpointType === "file"
) {
throw new Error(
'rootEndpointType cannot be "file" without a urlPathForFiles'
);
}
this.fingerPrinter = new BrowserFingerprint(this.config.fingerprintOptions);
}
async start() {
let bootAttempts = 0;
if (this.config.secure === false) {
this.server = http.createServer((req, res) => {
this.handleRequest(req, res);
});
} else {
this.server = https.createServer(
this.config.serverOptions,
(req, res) => {
this.handleRequest(req, res);
}
);
}
this.server.on("error", (error) => {
bootAttempts++;
if (bootAttempts < this.config.bootAttempts) {
this.log(`cannot boot web server; trying again [${error}]`, "error");
if (bootAttempts === 1) {
this.cleanSocket(this.config.bindIP, this.config.port);
}
setTimeout(() => {
this.log("attempting to boot again..");
this.server.listen(this.config.port, this.config.bindIP);
}, 1000);
} else {
throw new Error(
`cannot start web server @ ${this.config.bindIP}:${this.config.port} => ${error}`
);
}
});
let socketCounter = 0;
this.server.on("connection", (socket) => {
const id = socketCounter;
this.sockets[id] = socket;
socket.on("close", () => delete this.sockets[id]);
socketCounter++;
});
await new Promise((resolve) => {
this.server.listen(this.config.port, this.config.bindIP, () => {
this.chmodSocket(this.config.bindIP, this.config.port);
resolve(null);
});
});
this.on("connection", async (connection: Connection) => {
const requestMode = await this.determineRequestParams(connection);
if (requestMode === "api") {
this.processAction(connection);
} else if (requestMode === "file") {
this.processFile(connection);
} else if (requestMode === "options") {
this.respondToOptions(connection);
} else if (requestMode === "trace") {
this.respondToTrace(connection);
}
});
this.on("actionComplete", this.completeResponse);
}
async stop() {
if (!this.server) return;
await new Promise((resolve) => {
this.server.close(resolve);
for (const socket of Object.values(this.sockets)) {
socket.destroy();
}
});
}
async sendMessage(connection: Connection, message) {
let stringResponse = "";
if (connection.rawConnection.method !== "HEAD") {
stringResponse = String(message);
}
this.cleanHeaders(connection);
const headers = connection.rawConnection.responseHeaders;
const responseHttpCode = parseInt(
connection.rawConnection.responseHttpCode
);
this.sendWithCompression(
connection,
responseHttpCode,
headers,
stringResponse
);
}
async sendFile(
connection: Connection,
error: Error,
fileStream: any,
mime: string,
length: number,
lastModified: Date
) {
let foundCacheControl = false;
let ifModifiedSince;
connection.rawConnection.responseHeaders.forEach((pair) => {
if (pair[0].toLowerCase() === "cache-control") {
foundCacheControl = true;
}
});
connection.rawConnection.responseHeaders.push(["Content-Type", mime]);
if (fileStream) {
if (!foundCacheControl) {
connection.rawConnection.responseHeaders.push([
"Cache-Control",
"max-age=" +
this.config.flatFileCacheDuration +
", must-revalidate, public",
]);
}
}
if (fileStream && !this.config.enableEtag) {
if (lastModified) {
connection.rawConnection.responseHeaders.push([
"Last-Modified",
new Date(lastModified).toUTCString(),
]);
}
}
this.cleanHeaders(connection);
const headers = connection.rawConnection.responseHeaders;
const reqHeaders = connection.rawConnection.req.headers;
const sendRequestResult = () => {
const responseHttpCode = parseInt(
connection.rawConnection.responseHttpCode,
10
);
if (error) {
this.sendWithCompression(
connection,
responseHttpCode,
headers,
String(error)
);
} else if (responseHttpCode !== 304) {
this.sendWithCompression(
connection,
responseHttpCode,
headers,
null,
fileStream,
length
);
} else {
connection.rawConnection.res.writeHead(
responseHttpCode,
this.transformHeaders(headers)
);
connection.rawConnection.res.end();
connection.destroy();
fileStream.close();
}
};
if (error) {
connection.rawConnection.responseHttpCode = 404;
return sendRequestResult();
}
if (reqHeaders["if-modified-since"]) {
ifModifiedSince = new Date(reqHeaders["if-modified-since"]);
lastModified.setMilliseconds(0);
if (lastModified <= ifModifiedSince) {
connection.rawConnection.responseHttpCode = 304;
}
return sendRequestResult();
}
if (this.config.enableEtag && fileStream && fileStream.path) {
const fileStats: fs.Stats = await new Promise((resolve) => {
fs.stat(fileStream.path, (error, fileStats) => {
if (error || !fileStats) {
this.log(
"Error receving file statistics: " + String(error),
"error"
);
}
return resolve(fileStats);
});
});
if (!fileStats) return sendRequestResult();
const fileEtag = etag(fileStats, { weak: true });
connection.rawConnection.responseHeaders.push(["ETag", fileEtag]);
let noneMatchHeader = reqHeaders["if-none-match"];
const cacheCtrlHeader = reqHeaders["cache-control"];
let noCache = false;
let etagMatches;
// check for no-cache cache request directive
if (cacheCtrlHeader && cacheCtrlHeader.indexOf("no-cache") !== -1) {
noCache = true;
}
// parse if-none-match
if (noneMatchHeader) {
noneMatchHeader = noneMatchHeader.split(/ *, */);
}
// if-none-match
if (noneMatchHeader) {
etagMatches = noneMatchHeader.some((match) => {
return (
match === "*" || match === fileEtag || match === "W/" + fileEtag
);
});
}
if (etagMatches && !noCache) {
connection.rawConnection.responseHttpCode = 304;
}
sendRequestResult();
} else {
sendRequestResult();
}
}
sendWithCompression(
connection: Connection,
responseHttpCode: number,
headers: Array<object>,
stringResponse: string,
fileStream?: any,
fileLength?: number
) {
let acceptEncoding =
connection.rawConnection.req.headers["accept-encoding"];
let compressor;
let stringEncoder;
if (!acceptEncoding) {
acceptEncoding = "";
}
// Note: this is not a conforming accept-encoding parser.
// https://nodejs.org/api/zlib.html#zlib_zlib_createinflate_options
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (this.config.compress === true) {
const gzipMatch = acceptEncoding.match(/\bgzip\b/);
const deflateMatch = acceptEncoding.match(/\bdeflate\b/);
if (
(gzipMatch && !deflateMatch) ||
(gzipMatch && deflateMatch && gzipMatch.index < deflateMatch.index)
) {
headers.push(["Content-Encoding", "gzip"]);
compressor = zlib.createGzip();
stringEncoder = zlib.gzip;
} else if (
(!gzipMatch && deflateMatch) ||
(gzipMatch && deflateMatch && deflateMatch.index < gzipMatch.index)
) {
headers.push(["Content-Encoding", "deflate"]);
compressor = zlib.createDeflate();
stringEncoder = zlib.deflate;
}
}
// the 'finish' event denotes a successful transfer
connection.rawConnection.res.on("finish", () => {
connection.destroy();
});
// the 'close' event denotes a failed transfer, but it is probably the client's fault
connection.rawConnection.res.on("close", () => {
connection.destroy();
});
if (fileStream) {
if (compressor) {
connection.rawConnection.res.writeHead(
responseHttpCode,
this.transformHeaders(headers)
);
fileStream.pipe(compressor).pipe(connection.rawConnection.res);
} else {
if (fileLength) {
headers.push(["Content-Length", fileLength]);
}
connection.rawConnection.res.writeHead(
responseHttpCode,
this.transformHeaders(headers)
);
fileStream.pipe(connection.rawConnection.res);
}
} else {
if (stringEncoder) {
stringEncoder(stringResponse, (error, zippedString) => {
if (error) {
console.error(error);
}
headers.push(["Content-Length", zippedString.length]);
connection.rawConnection.res.writeHead(
responseHttpCode,
this.transformHeaders(headers)
);
connection.rawConnection.res.end(zippedString);
});
} else {
headers.push(["Content-Length", Buffer.byteLength(stringResponse)]);
connection.rawConnection.res.writeHead(
responseHttpCode,
this.transformHeaders(headers)
);
connection.rawConnection.res.end(stringResponse);
}
}
}
handleRequest(req, res) {
const { fingerprint, headersHash } = this.fingerPrinter.fingerprint(req);
const responseHeaders = [];
const cookies = utils.parseCookies(req);
const responseHttpCode = 200;
const method = req.method.toUpperCase();
// waiting until URL() can handle relative paths
// https://github.com/nodejs/node/issues/12682
const parsedURL = url.parse(req.url, true);
let i;
for (i in headersHash) {
responseHeaders.push([i, headersHash[i]]);
}
// https://github.com/actionhero/actionhero/issues/189
responseHeaders.push(["Content-Type", "application/json; charset=utf-8"]);
for (i in this.config.httpHeaders) {
if (this.config.httpHeaders[i]) {
responseHeaders.push([i, this.config.httpHeaders[i]]);
}
}
// check if this request (http://other-host.com) is in allowedRequestHosts ([https://host.com])
if (
this.config.allowedRequestHosts &&
this.config.allowedRequestHosts.length > 0
) {
const requestHost = req.headers["x-forwarded-proto"]
? req.headers["x-forwarded-proto"] + "://" + req.headers.host
: (this.config.secure ? "https://" : "http://") + req.headers.host;
if (!this.config.allowedRequestHosts.includes(requestHost)) {
const newHost = this.config.allowedRequestHosts[0];
res.statusCode = 302;
res.setHeader("Location", newHost + req.url);
return res.end(`You are being redirected to ${newHost + req.url}\r\n`);
}
}
const { ip, port } = utils.parseHeadersForClientAddress(req.headers);
const messageId = uuid.v4();
this.buildConnection({
rawConnection: {
req: req,
res: res,
params: {},
method: method,
cookies: cookies,
responseHeaders: responseHeaders,
responseHttpCode: responseHttpCode,
parsedURL: parsedURL,
},
id: `${fingerprint}-${messageId}`,
messageId: messageId,
fingerprint: fingerprint,
remoteAddress: ip || req.connection.remoteAddress || "0.0.0.0",
remotePort: port || req.connection.remotePort || "0",
});
}
async completeResponse(data) {
if (data.toRender !== true) {
if (data.connection.rawConnection.res.finished) {
data.connection.destroy();
} else {
data.connection.rawConnection.res.on("finish", () =>
data.connection.destroy()
);
data.connection.rawConnection.res.on("close", () =>
data.connection.destroy()
);
}
return;
}
if (
this.config.metadataOptions.serverInformation &&
typeof data.response !== "string"
) {
data.response.serverInformation = this.buildServerInformation(
data.connection.connectedAt
);
}
if (
this.config.metadataOptions.requesterInformation &&
typeof data.response !== "string"
) {
data.response.requesterInformation = this.buildRequesterInformation(
data.connection
);
}
if (data.response.error) {
if (
this.config.returnErrorCodes === true &&
data.connection.rawConnection.responseHttpCode === 200
) {
const customErrorCode = parseInt(data.response.error.code, 10);
const isValidCustomResponseCode =
customErrorCode >= 100 && customErrorCode < 600;
if (isValidCustomResponseCode) {
data.connection.rawConnection.responseHttpCode = customErrorCode;
} else if (data.actionStatus === ActionsStatus.UnknownAction) {
data.connection.rawConnection.responseHttpCode = 404;
} else if (data.actionStatus === ActionsStatus.MissingParams) {
data.connection.rawConnection.responseHttpCode = 422;
} else {
data.connection.rawConnection.responseHttpCode =
this.config.defaultErrorStatusCode ?? 500;
}
}
}
if (
!data.response.error &&
data.action &&
data.params.apiVersion &&
api.actions.actions[data.params.action][data.params.apiVersion]
.matchExtensionMimeType === true &&
data.connection.extension
) {
const mime = Mime.getType(data.connection.extension);
if (mime) {
data.connection.rawConnection.responseHeaders.push([
"Content-Type",
mime,
]);
}
}
if (data.response.error) {
data.response.error = await config.errors.serializers.servers.web(
data.response.error
);
}
let stringResponse = "";
if (this.extractHeader(data.connection, "Content-Type").match(/json/)) {
stringResponse = JSON.stringify(data.response, null, this.config.padding);
if (data.params.callback) {
data.connection.rawConnection.responseHeaders.push([
"Content-Type",
"application/javascript",
]);
stringResponse =
this.callbackHtmlEscape(data.connection.params.callback) +
"(" +
stringResponse +
");";
}
} else {
stringResponse = data.response;
}
this.sendMessage(data.connection, stringResponse);
}
extractHeader(connection: Connection, match: string) {
let i = connection.rawConnection.responseHeaders.length - 1;
while (i >= 0) {
if (
connection.rawConnection.responseHeaders[i][0].toLowerCase() ===
match.toLowerCase()
) {
return connection.rawConnection.responseHeaders[i][1];
}
i--;
}
return null;
}
respondToOptions(connection: Connection) {
if (
!this.config.httpHeaders["Access-Control-Allow-Methods"] &&
!this.extractHeader(connection, "Access-Control-Allow-Methods")
) {
const methods = "HEAD, GET, POST, PUT, DELETE, OPTIONS, TRACE";
connection.rawConnection.responseHeaders.push([
"Access-Control-Allow-Methods",
methods,
]);
}
if (
!this.config.httpHeaders["Access-Control-Allow-Origin"] &&
!this.extractHeader(connection, "Access-Control-Allow-Origin")
) {
const origin = "*";
connection.rawConnection.responseHeaders.push([
"Access-Control-Allow-Origin",
origin,
]);
}
this.sendMessage(connection, "");
}
respondToTrace(connection: Connection) {
const data = this.buildRequesterInformation(connection);
const stringResponse = JSON.stringify(data, null, this.config.padding);
this.sendMessage(connection, stringResponse);
}
async determineRequestParams(connection: Connection) {
// determine file or api request
let requestMode = this.config.rootEndpointType;
const pathname = connection.rawConnection.parsedURL.pathname;
const pathParts = pathname.split("/");
let i;
while (pathParts[0] === "") {
pathParts.shift();
}
if (pathParts[pathParts.length - 1] === "") {
pathParts.pop();
}
let urlPathForActionsParts = [];
if (this.config.urlPathForActions) {
urlPathForActionsParts = this.config.urlPathForActions.split("/");
while (urlPathForActionsParts[0] === "") {
urlPathForActionsParts.shift();
}
}
let urlPathForFilesParts = [];
if (this.config.urlPathForFiles) {
urlPathForFilesParts = this.config.urlPathForFiles.split("/");
while (urlPathForFilesParts[0] === "") {
urlPathForFilesParts.shift();
}
}
if (
pathParts[0] &&
utils.arrayStartingMatch(urlPathForActionsParts, pathParts)
) {
requestMode = "api";
for (i = 0; i < urlPathForActionsParts.length; i++) {
pathParts.shift();
}
} else if (
pathParts[0] &&
utils.arrayStartingMatch(urlPathForFilesParts, pathParts)
) {
requestMode = "file";
for (i = 0; i < urlPathForFilesParts.length; i++) {
pathParts.shift();
}
}
const extensionParts =
connection.rawConnection.parsedURL.pathname.split(".");
if (extensionParts.length > 1) {
connection.extension = extensionParts[extensionParts.length - 1];
}
// OPTIONS
if (connection.rawConnection.method === "OPTIONS") {
requestMode = "options";
return requestMode;
}
// API
if (requestMode === "api") {
if (connection.rawConnection.method === "TRACE") {
requestMode = "trace";
}
let search = "";
if (connection.rawConnection.parsedURL.search) {
search = connection.rawConnection.parsedURL.search.slice(1);
}
this.fillParamsFromWebRequest(
connection,
qs.parse(search, this.config.queryParseOptions)
);
connection.rawConnection.params.query =
connection.rawConnection.parsedURL.query;
if (
connection.rawConnection.method !== "GET" &&
connection.rawConnection.method !== "HEAD" &&
(connection.rawConnection.req.headers["content-type"] ||
connection.rawConnection.req.headers["Content-Type"])
) {
connection.rawConnection.form = new formidable.IncomingForm();
for (i in this.config.formOptions) {
connection.rawConnection.form[i] = this.config.formOptions[i];
}
let rawBody = Promise.resolve(Buffer.alloc(0));
if (this.config.saveRawBody) {
rawBody = new Promise((resolve, reject) => {
let fullBody = Buffer.alloc(0);
connection.rawConnection.req
.on("data", (chunk) => {
fullBody = Buffer.concat([fullBody, chunk]);
})
.on("end", () => {
resolve(fullBody);
});
});
}
const { fields, files } = await new Promise((resolve) => {
connection.rawConnection.form.parse(
connection.rawConnection.req,
(error, fields, files) => {
if (error) {
this.log("error processing form: " + String(error), "error");
connection.error = new Error(
"There was an error processing this form."
);
}
resolve({ fields, files });
}
);
});
connection.rawConnection.params.body = fields;
connection.rawConnection.params.rawBody = await rawBody;
connection.rawConnection.params.files = files;
this.fillParamsFromWebRequest(connection, files);
this.fillParamsFromWebRequest(connection, fields);
connection.params.action = null;
api.routes.processRoute(connection, pathParts);
return requestMode;
} else {
connection.params.action = null;
api.routes.processRoute(connection, pathParts);
return requestMode;
}
}
// FILE
if (requestMode === "file") {
api.routes.processRoute(connection, pathParts);
if (!connection.params.file) {
connection.params.file = pathParts.join(path.sep);
}
if (
connection.params.file === "" ||
connection.params.file[connection.params.file.length - 1] === "/"
) {
connection.params.file =
connection.params.file + config.general.directoryFileType;
}
try {
connection.params.file = decodeURIComponent(connection.params.file);
} catch (e) {
connection.error = new Error("There was an error decoding URI: " + e);
}
return requestMode;
}
}
fillParamsFromWebRequest(connection, varsHash) {
// helper for JSON posts
const collapsedVarsHash = utils.collapseObjectToArray(varsHash);
if (collapsedVarsHash !== false) {
varsHash = { payload: collapsedVarsHash }; // post was an array, lets call it "payload"
}
for (const v in varsHash) {
connection.params[v] = varsHash[v];
}
}
transformHeaders(headersArray) {
return headersArray.reduce((headers, currentHeader) => {
const currentHeaderKey = currentHeader[0].toLowerCase();
// we have a set-cookie, let's see what we have to do
if (currentHeaderKey === "set-cookie") {
if (headers[currentHeaderKey]) {
headers[currentHeaderKey].push(currentHeader[1]);
} else {
headers[currentHeaderKey] = [currentHeader[1]];
}
} else {
headers[currentHeaderKey] = currentHeader[1];
}
return headers;
}, {});
}
buildServerInformation(connectedAt: number) {
const stopTime = new Date().getTime();
return {
serverName: config.general.serverName,
apiVersion: config.general.apiVersion,
requestDuration: stopTime - connectedAt,
currentTime: stopTime,
};
}
buildRequesterInformation(connection) {
const requesterInformation = {
id: connection.id,
fingerprint: connection.fingerprint,
messageId: connection.messageId,
remoteIP: connection.remoteIP,
receivedParams: {} as { [key: string]: any },
};
for (const p in connection.params) {
if (
config.general.disableParamScrubbing === true ||
api.params.postVariables.indexOf(p) >= 0
) {
requesterInformation.receivedParams[p] = connection.params[p];
}
}
return requesterInformation;
}
cleanHeaders(connection) {
const originalHeaders = connection.rawConnection.responseHeaders.reverse();
const foundHeaders = [];
const cleanedHeaders = [];
for (const i in originalHeaders) {
const key = originalHeaders[i][0];
const value = originalHeaders[i][1];
if (
foundHeaders.indexOf(key.toLowerCase()) >= 0 &&
key.toLowerCase().indexOf("set-cookie") < 0
) {
// ignore, it's a duplicate
} else if (
connection.rawConnection.method === "HEAD" &&
key === "Transfer-Encoding"
) {
// ignore, we can't send this header for HEAD requests
} else {
foundHeaders.push(key.toLowerCase());
cleanedHeaders.push([key, value]);
}
}
connection.rawConnection.responseHeaders = cleanedHeaders;
}
cleanSocket(bindIP, port) {
if (!bindIP && typeof port === "string" && port.indexOf("/") >= 0) {
fs.unlink(port, (error) => {
if (error) {
this.log(`cannot remove stale socket @ ${port}: ${error}`, "error");
} else {
this.log(`removed stale unix socket @ ${port}`);
}
});
}
}
chmodSocket(bindIP, port) {
if (!bindIP && typeof port === "string" && port.indexOf("/") >= 0) {
fs.chmodSync(port, "0777");
}
}
callbackHtmlEscape(str) {
return str
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\)/g, "")
.replace(/\(/g, "");
}
} | the_stack |
import type { NonNullObject } from '@sapphire/utilities';
import type { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export interface Scalars {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** ISO 3166-1 alpha-2 country code */
CountryCode: string;
/** 8 digit long date integer (YYYYMMDD). Unknown dates represented by 0. E.g. 2016: 20160000, May 1976: 19760500 */
FuzzyDateInt: number;
Json: Record<PropertyKey, unknown>;
}
/** Notification for when a activity is liked */
export interface ActivityLikeNotification {
readonly __typename?: 'ActivityLikeNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who liked to the activity */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity which was liked */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly activity?: Maybe<ActivityUnion>;
/** The user who liked the activity */
readonly user?: Maybe<User>;
}
/** Notification for when authenticated user is @ mentioned in activity or reply */
export interface ActivityMentionNotification {
readonly __typename?: 'ActivityMentionNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who mentioned the authenticated user */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity where mentioned */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly activity?: Maybe<ActivityUnion>;
/** The user who mentioned the authenticated user */
readonly user?: Maybe<User>;
}
/** Notification for when a user is send an activity message */
export interface ActivityMessageNotification {
readonly __typename?: 'ActivityMessageNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The if of the user who send the message */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity message */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The message activity */
readonly message?: Maybe<MessageActivity>;
/** The user who sent the message */
readonly user?: Maybe<User>;
}
/** Replay to an activity item */
export interface ActivityReply {
readonly __typename?: 'ActivityReply';
/** The id of the reply */
readonly id: Scalars['Int'];
/** The id of the replies creator */
readonly userId?: Maybe<Scalars['Int']>;
/** The id of the parent activity */
readonly activityId?: Maybe<Scalars['Int']>;
/** The reply text */
readonly text?: Maybe<Scalars['String']>;
/** The amount of likes the reply has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the reply */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** The time the reply was created at */
readonly createdAt: Scalars['Int'];
/** The user who created reply */
readonly user?: Maybe<User>;
/** The users who liked the reply */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** Replay to an activity item */
export interface ActivityReplyTextArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** Notification for when a activity reply is liked */
export interface ActivityReplyLikeNotification {
readonly __typename?: 'ActivityReplyLikeNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who liked to the activity reply */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity where the reply which was liked */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly activity?: Maybe<ActivityUnion>;
/** The user who liked the activity reply */
readonly user?: Maybe<User>;
}
/** Notification for when a user replies to the authenticated users activity */
export interface ActivityReplyNotification {
readonly __typename?: 'ActivityReplyNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who replied to the activity */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity which was replied too */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly activity?: Maybe<ActivityUnion>;
/** The user who replied to the activity */
readonly user?: Maybe<User>;
}
/** Notification for when a user replies to activity the authenticated user has replied to */
export interface ActivityReplySubscribedNotification {
readonly __typename?: 'ActivityReplySubscribedNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who replied to the activity */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity which was replied too */
readonly activityId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly activity?: Maybe<ActivityUnion>;
/** The user who replied to the activity */
readonly user?: Maybe<User>;
}
/** Activity sort enums */
export const enum ActivitySort {
Id = 'ID',
IdDesc = 'ID_DESC'
}
/** Activity type enum. */
export const enum ActivityType {
/** A text activity */
Text = 'TEXT',
/** A anime list update activity */
AnimeList = 'ANIME_LIST',
/** A manga list update activity */
MangaList = 'MANGA_LIST',
/** A text message activity sent to another user */
Message = 'MESSAGE',
/** Anime & Manga list update, only used in query arguments */
MediaList = 'MEDIA_LIST'
}
/** Activity union type */
export type ActivityUnion = TextActivity | ListActivity | MessageActivity;
/** Notification for when an episode of anime airs */
export interface AiringNotification {
readonly __typename?: 'AiringNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the aired anime */
readonly animeId: Scalars['Int'];
/** The episode number that just aired */
readonly episode: Scalars['Int'];
/** The notification context text */
readonly contexts?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The associated media of the airing schedule */
readonly media?: Maybe<Media>;
}
/** Score & Watcher stats for airing anime by episode and mid-week */
export interface AiringProgression {
readonly __typename?: 'AiringProgression';
/** The episode the stats were recorded at. .5 is the mid point between 2 episodes airing dates. */
readonly episode?: Maybe<Scalars['Float']>;
/** The average score for the media */
readonly score?: Maybe<Scalars['Float']>;
/** The amount of users watching the anime */
readonly watching?: Maybe<Scalars['Int']>;
}
/** Media Airing Schedule. NOTE: We only aim to guarantee that FUTURE airing data is present and accurate. */
export interface AiringSchedule {
readonly __typename?: 'AiringSchedule';
/** The id of the airing schedule item */
readonly id: Scalars['Int'];
/** The time the episode airs at */
readonly airingAt: Scalars['Int'];
/** Seconds until episode starts airing */
readonly timeUntilAiring: Scalars['Int'];
/** The airing episode number */
readonly episode: Scalars['Int'];
/** The associate media id of the airing episode */
readonly mediaId: Scalars['Int'];
/** The associate media of the airing episode */
readonly media?: Maybe<Media>;
}
export interface AiringScheduleConnection {
readonly __typename?: 'AiringScheduleConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<AiringScheduleEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<AiringSchedule>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** AiringSchedule connection edge */
export interface AiringScheduleEdge {
readonly __typename?: 'AiringScheduleEdge';
readonly node?: Maybe<AiringSchedule>;
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
}
export interface AiringScheduleInput {
readonly airingAt?: Maybe<Scalars['Int']>;
readonly episode?: Maybe<Scalars['Int']>;
readonly timeUntilAiring?: Maybe<Scalars['Int']>;
}
/** Airing schedule sort enums */
export const enum AiringSort {
Id = 'ID',
IdDesc = 'ID_DESC',
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Time = 'TIME',
TimeDesc = 'TIME_DESC',
Episode = 'EPISODE',
EpisodeDesc = 'EPISODE_DESC'
}
export interface AniChartHighlightInput {
readonly mediaId?: Maybe<Scalars['Int']>;
readonly highlight?: Maybe<Scalars['String']>;
}
export interface AniChartUser {
readonly __typename?: 'AniChartUser';
readonly user?: Maybe<User>;
readonly settings?: Maybe<Scalars['Json']>;
readonly highlights?: Maybe<Scalars['Json']>;
}
/** A character that features in an anime or manga */
export interface Character {
readonly __typename?: 'Character';
/** The id of the character */
readonly id: Scalars['Int'];
/** The names of the character */
readonly name?: Maybe<CharacterName>;
/** Character images */
readonly image?: Maybe<CharacterImage>;
/** A general description of the character */
readonly description?: Maybe<Scalars['String']>;
/** The character's gender. Usually Male, Female, or Non-binary but can be any string. */
readonly gender?: Maybe<Scalars['String']>;
/** The character's birth date */
readonly dateOfBirth?: Maybe<FuzzyDate>;
/** The character's age. Note this is a string, not an int, it may contain further text and additional ages. */
readonly age?: Maybe<Scalars['String']>;
/** The characters blood type */
readonly bloodType?: Maybe<Scalars['String']>;
/** If the character is marked as favourite by the currently authenticated user */
readonly isFavourite: Scalars['Boolean'];
/** If the character is blocked from being added to favourites */
readonly isFavouriteBlocked: Scalars['Boolean'];
/** The url for the character page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** Media that includes the character */
readonly media?: Maybe<MediaConnection>;
/** @deprecated No data available */
readonly updatedAt?: Maybe<Scalars['Int']>;
/** The amount of user's who have favourited the character */
readonly favourites?: Maybe<Scalars['Int']>;
/** Notes for site moderators */
readonly modNotes?: Maybe<Scalars['String']>;
}
/** A character that features in an anime or manga */
export interface CharacterDescriptionArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** A character that features in an anime or manga */
export interface CharacterMediaArgs {
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
type?: Maybe<MediaType>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface CharacterConnection {
readonly __typename?: 'CharacterConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<CharacterEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Character>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Character connection edge */
export interface CharacterEdge {
readonly __typename?: 'CharacterEdge';
readonly node?: Maybe<Character>;
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
/** The characters role in the media */
readonly role?: Maybe<CharacterRole>;
/** Media specific character name */
readonly name?: Maybe<Scalars['String']>;
/** The voice actors of the character */
readonly voiceActors?: Maybe<ReadonlyArray<Maybe<Staff>>>;
/** The voice actors of the character with role date */
readonly voiceActorRoles?: Maybe<ReadonlyArray<Maybe<StaffRoleType>>>;
/** The media the character is in */
readonly media?: Maybe<ReadonlyArray<Maybe<Media>>>;
/** The order the character should be displayed from the users favourites */
readonly favouriteOrder?: Maybe<Scalars['Int']>;
}
/** Character connection edge */
export interface CharacterEdgeVoiceActorsArgs {
language?: Maybe<StaffLanguage>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
/** Character connection edge */
export interface CharacterEdgeVoiceActorRolesArgs {
language?: Maybe<StaffLanguage>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
export interface CharacterImage {
readonly __typename?: 'CharacterImage';
/** The character's image of media at its largest size */
readonly large?: Maybe<Scalars['String']>;
/** The character's image of media at medium size */
readonly medium?: Maybe<Scalars['String']>;
}
/** The names of the character */
export interface CharacterName {
readonly __typename?: 'CharacterName';
/** The character's given name */
readonly first?: Maybe<Scalars['String']>;
/** The character's middle name */
readonly middle?: Maybe<Scalars['String']>;
/** The character's surname */
readonly last?: Maybe<Scalars['String']>;
/** The character's first and last name */
readonly full?: Maybe<Scalars['String']>;
/** The character's full name in their native language */
readonly native?: Maybe<Scalars['String']>;
/** Other names the character might be referred to as */
readonly alternative?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** Other names the character might be referred to as but are spoilers */
readonly alternativeSpoiler?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The currently authenticated users preferred name language. Default romaji for non-authenticated */
readonly userPreferred?: Maybe<Scalars['String']>;
}
/** The names of the character */
export interface CharacterNameInput {
/** The character's given name */
readonly first?: Maybe<Scalars['String']>;
/** The character's middle name */
readonly middle?: Maybe<Scalars['String']>;
/** The character's surname */
readonly last?: Maybe<Scalars['String']>;
/** The character's full name in their native language */
readonly native?: Maybe<Scalars['String']>;
/** Other names the character might be referred by */
readonly alternative?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** Other names the character might be referred to as but are spoilers */
readonly alternativeSpoiler?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
}
/** The role the character plays in the media */
export const enum CharacterRole {
/** A primary character role in the media */
Main = 'MAIN',
/** A supporting character role in the media */
Supporting = 'SUPPORTING',
/** A background character in the media */
Background = 'BACKGROUND'
}
/** Character sort enums */
export const enum CharacterSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Role = 'ROLE',
RoleDesc = 'ROLE_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
/** Order manually decided by moderators */
Relevance = 'RELEVANCE'
}
/** A submission for a character that features in an anime or manga */
export interface CharacterSubmission {
readonly __typename?: 'CharacterSubmission';
/** The id of the submission */
readonly id: Scalars['Int'];
/** Character that the submission is referencing */
readonly character?: Maybe<Character>;
/** The character submission changes */
readonly submission?: Maybe<Character>;
/** Submitter for the submission */
readonly submitter?: Maybe<User>;
/** Status of the submission */
readonly status?: Maybe<SubmissionStatus>;
/** Inner details of submission status */
readonly notes?: Maybe<Scalars['String']>;
readonly source?: Maybe<Scalars['String']>;
readonly createdAt?: Maybe<Scalars['Int']>;
}
export interface CharacterSubmissionConnection {
readonly __typename?: 'CharacterSubmissionConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<CharacterSubmissionEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<CharacterSubmission>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** CharacterSubmission connection edge */
export interface CharacterSubmissionEdge {
readonly __typename?: 'CharacterSubmissionEdge';
readonly node?: Maybe<CharacterSubmission>;
/** The characters role in the media */
readonly role?: Maybe<CharacterRole>;
/** The voice actors of the character */
readonly voiceActors?: Maybe<ReadonlyArray<Maybe<Staff>>>;
/** The submitted voice actors of the character */
readonly submittedVoiceActors?: Maybe<ReadonlyArray<Maybe<StaffSubmission>>>;
}
/** Deleted data type */
export interface Deleted {
readonly __typename?: 'Deleted';
/** If an item has been successfully deleted */
readonly deleted?: Maybe<Scalars['Boolean']>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface Favourites {
readonly __typename?: 'Favourites';
/** Favourite anime */
readonly anime?: Maybe<MediaConnection>;
/** Favourite manga */
readonly manga?: Maybe<MediaConnection>;
/** Favourite characters */
readonly characters?: Maybe<CharacterConnection>;
/** Favourite staff */
readonly staff?: Maybe<StaffConnection>;
/** Favourite studios */
readonly studios?: Maybe<StudioConnection>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface FavouritesAnimeArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface FavouritesMangaArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface FavouritesCharactersArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface FavouritesStaffArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** User's favourite anime, manga, characters, staff & studios */
export interface FavouritesStudiosArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Notification for when the authenticated user is followed by another user */
export interface FollowingNotification {
readonly __typename?: 'FollowingNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who followed the authenticated user */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The liked activity */
readonly user?: Maybe<User>;
}
/** User's format statistics */
export interface FormatStats {
readonly __typename?: 'FormatStats';
readonly format?: Maybe<MediaFormat>;
readonly amount?: Maybe<Scalars['Int']>;
}
/** Date object that allows for incomplete date values (fuzzy) */
export interface FuzzyDate {
readonly __typename?: 'FuzzyDate';
/** Numeric Year (2017) */
readonly year?: Maybe<Scalars['Int']>;
/** Numeric Month (3) */
readonly month?: Maybe<Scalars['Int']>;
/** Numeric Day (24) */
readonly day?: Maybe<Scalars['Int']>;
}
/** Date object that allows for incomplete date values (fuzzy) */
export interface FuzzyDateInput {
/** Numeric Year (2017) */
readonly year?: Maybe<Scalars['Int']>;
/** Numeric Month (3) */
readonly month?: Maybe<Scalars['Int']>;
/** Numeric Day (24) */
readonly day?: Maybe<Scalars['Int']>;
}
/** User's genre statistics */
export interface GenreStats {
readonly __typename?: 'GenreStats';
readonly genre?: Maybe<Scalars['String']>;
readonly amount?: Maybe<Scalars['Int']>;
readonly meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the genre has been watched by the user */
readonly timeWatched?: Maybe<Scalars['Int']>;
}
/** Page of data (Used for internal use only) */
export interface InternalPage {
readonly __typename?: 'InternalPage';
readonly mediaSubmissions?: Maybe<ReadonlyArray<Maybe<MediaSubmission>>>;
readonly characterSubmissions?: Maybe<ReadonlyArray<Maybe<CharacterSubmission>>>;
readonly staffSubmissions?: Maybe<ReadonlyArray<Maybe<StaffSubmission>>>;
readonly revisionHistory?: Maybe<ReadonlyArray<Maybe<RevisionHistory>>>;
readonly reports?: Maybe<ReadonlyArray<Maybe<Report>>>;
readonly modActions?: Maybe<ReadonlyArray<Maybe<ModAction>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
readonly users?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly media?: Maybe<ReadonlyArray<Maybe<Media>>>;
readonly characters?: Maybe<ReadonlyArray<Maybe<Character>>>;
readonly staff?: Maybe<ReadonlyArray<Maybe<Staff>>>;
readonly studios?: Maybe<ReadonlyArray<Maybe<Studio>>>;
readonly mediaList?: Maybe<ReadonlyArray<Maybe<MediaList>>>;
readonly airingSchedules?: Maybe<ReadonlyArray<Maybe<AiringSchedule>>>;
readonly mediaTrends?: Maybe<ReadonlyArray<Maybe<MediaTrend>>>;
readonly notifications?: Maybe<ReadonlyArray<Maybe<NotificationUnion>>>;
readonly followers?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly following?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly activities?: Maybe<ReadonlyArray<Maybe<ActivityUnion>>>;
readonly activityReplies?: Maybe<ReadonlyArray<Maybe<ActivityReply>>>;
readonly threads?: Maybe<ReadonlyArray<Maybe<Thread>>>;
readonly threadComments?: Maybe<ReadonlyArray<Maybe<ThreadComment>>>;
readonly reviews?: Maybe<ReadonlyArray<Maybe<Review>>>;
readonly recommendations?: Maybe<ReadonlyArray<Maybe<Recommendation>>>;
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageMediaSubmissionsArgs {
mediaId?: Maybe<Scalars['Int']>;
submissionId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
type?: Maybe<MediaType>;
sort?: Maybe<ReadonlyArray<Maybe<SubmissionSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageCharacterSubmissionsArgs {
characterId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
sort?: Maybe<ReadonlyArray<Maybe<SubmissionSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageStaffSubmissionsArgs {
staffId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
status?: Maybe<SubmissionStatus>;
sort?: Maybe<ReadonlyArray<Maybe<SubmissionSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageRevisionHistoryArgs {
userId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
characterId?: Maybe<Scalars['Int']>;
staffId?: Maybe<Scalars['Int']>;
studioId?: Maybe<Scalars['Int']>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageReportsArgs {
reporterId?: Maybe<Scalars['Int']>;
reportedId?: Maybe<Scalars['Int']>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageModActionsArgs {
userId?: Maybe<Scalars['Int']>;
modId?: Maybe<Scalars['Int']>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageUsersArgs {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageMediaArgs {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<ReadonlyArray<Maybe<MediaSource>>>;
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageCharactersArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<CharacterSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageStaffArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageStudiosArgs {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StudioSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageMediaListArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaListSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageAiringSchedulesArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<AiringSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageMediaTrendsArgs {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaTrendSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageNotificationsArgs {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<ReadonlyArray<Maybe<NotificationType>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageFollowersArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageFollowingArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageActivitiesArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
type_not_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ActivitySort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageActivityRepliesArgs {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageThreadsArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageThreadCommentsArgs {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadCommentSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageReviewsArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<ReadonlyArray<Maybe<ReviewSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageRecommendationsArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<RecommendationSort>>>;
}
/** Page of data (Used for internal use only) */
export interface InternalPageLikesArgs {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
}
/** Types that can be liked */
export const enum LikeableType {
Thread = 'THREAD',
ThreadComment = 'THREAD_COMMENT',
Activity = 'ACTIVITY',
ActivityReply = 'ACTIVITY_REPLY'
}
/** Likeable union type */
export type LikeableUnion = ListActivity | TextActivity | MessageActivity | ActivityReply | Thread | ThreadComment;
/** User list activity (anime & manga updates) */
export interface ListActivity {
readonly __typename?: 'ListActivity';
/** The id of the activity */
readonly id: Scalars['Int'];
/** The user id of the activity's creator */
readonly userId?: Maybe<Scalars['Int']>;
/** The type of activity */
readonly type?: Maybe<ActivityType>;
/** The number of activity replies */
readonly replyCount: Scalars['Int'];
/** The list item's textual status */
readonly status?: Maybe<Scalars['String']>;
/** The list progress made */
readonly progress?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
readonly isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
readonly isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** The url for the activity page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The time the activity was created at */
readonly createdAt: Scalars['Int'];
/** The owner of the activity */
readonly user?: Maybe<User>;
/** The associated media to the activity update */
readonly media?: Maybe<Media>;
/** The written replies to the activity */
readonly replies?: Maybe<ReadonlyArray<Maybe<ActivityReply>>>;
/** The users who liked the activity */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** User's list score statistics */
export interface ListScoreStats {
readonly __typename?: 'ListScoreStats';
readonly meanScore?: Maybe<Scalars['Int']>;
readonly standardDeviation?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface Media {
readonly __typename?: 'Media';
/** The id of the media */
readonly id: Scalars['Int'];
/** The mal id of the media */
readonly idMal?: Maybe<Scalars['Int']>;
/** The official titles of the media in various languages */
readonly title?: Maybe<MediaTitle>;
/** The type of the media; anime or manga */
readonly type?: Maybe<MediaType>;
/** The format the media was released in */
readonly format?: Maybe<MediaFormat>;
/** The current releasing status of the media */
readonly status?: Maybe<MediaStatus>;
/** Short description of the media's story and characters */
readonly description?: Maybe<Scalars['String']>;
/** The first official release date of the media */
readonly startDate?: Maybe<FuzzyDate>;
/** The last official release date of the media */
readonly endDate?: Maybe<FuzzyDate>;
/** The season the media was initially released in */
readonly season?: Maybe<MediaSeason>;
/** The season year the media was initially released in */
readonly seasonYear?: Maybe<Scalars['Int']>;
/**
* The year & season the media was initially released in
* @deprecated
*/
readonly seasonInt?: Maybe<Scalars['Int']>;
/** The amount of episodes the anime has when complete */
readonly episodes?: Maybe<Scalars['Int']>;
/** The general length of each anime episode in minutes */
readonly duration?: Maybe<Scalars['Int']>;
/** The amount of chapters the manga has when complete */
readonly chapters?: Maybe<Scalars['Int']>;
/** The amount of volumes the manga has when complete */
readonly volumes?: Maybe<Scalars['Int']>;
/** Where the media was created. (ISO 3166-1 alpha-2) */
readonly countryOfOrigin?: Maybe<Scalars['CountryCode']>;
/** If the media is officially licensed or a self-published doujin release */
readonly isLicensed?: Maybe<Scalars['Boolean']>;
/** Source type the media was adapted from. */
readonly source?: Maybe<MediaSource>;
/** Official Twitter hashtags for the media */
readonly hashtag?: Maybe<Scalars['String']>;
/** Media trailer or advertisement */
readonly trailer?: Maybe<MediaTrailer>;
/** When the media's data was last updated */
readonly updatedAt?: Maybe<Scalars['Int']>;
/** The cover images of the media */
readonly coverImage?: Maybe<MediaCoverImage>;
/** The banner image of the media */
readonly bannerImage?: Maybe<Scalars['String']>;
/** The genres of the media */
readonly genres?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** Alternative titles of the media */
readonly synonyms?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** A weighted average score of all the user's scores of the media */
readonly averageScore?: Maybe<Scalars['Int']>;
/** Mean score of all the user's scores of the media */
readonly meanScore?: Maybe<Scalars['Int']>;
/** The number of users with the media on their list */
readonly popularity?: Maybe<Scalars['Int']>;
/** Locked media may not be added to lists our favorited. This may be due to the entry pending for deletion or other reasons. */
readonly isLocked?: Maybe<Scalars['Boolean']>;
/** The amount of related activity in the past hour */
readonly trending?: Maybe<Scalars['Int']>;
/** The amount of user's who have favourited the media */
readonly favourites?: Maybe<Scalars['Int']>;
/** List of tags that describes elements and themes of the media */
readonly tags?: Maybe<ReadonlyArray<Maybe<MediaTag>>>;
/** Other media in the same or connecting franchise */
readonly relations?: Maybe<MediaConnection>;
/** The characters in the media */
readonly characters?: Maybe<CharacterConnection>;
/** The staff who produced the media */
readonly staff?: Maybe<StaffConnection>;
/** The companies who produced the media */
readonly studios?: Maybe<StudioConnection>;
/** If the media is marked as favourite by the current authenticated user */
readonly isFavourite: Scalars['Boolean'];
/** If the media is intended only for 18+ adult audiences */
readonly isAdult?: Maybe<Scalars['Boolean']>;
/** The media's next episode airing schedule */
readonly nextAiringEpisode?: Maybe<AiringSchedule>;
/** The media's entire airing schedule */
readonly airingSchedule?: Maybe<AiringScheduleConnection>;
/** The media's daily trend stats */
readonly trends?: Maybe<MediaTrendConnection>;
/** External links to another site related to the media */
readonly externalLinks?: Maybe<ReadonlyArray<Maybe<MediaExternalLink>>>;
/** Data and links to legal streaming episodes on external sites */
readonly streamingEpisodes?: Maybe<ReadonlyArray<Maybe<MediaStreamingEpisode>>>;
/** The ranking of the media in a particular time span and format compared to other media */
readonly rankings?: Maybe<ReadonlyArray<Maybe<MediaRank>>>;
/** The authenticated user's media list entry for the media */
readonly mediaListEntry?: Maybe<MediaList>;
/** User reviews of the media */
readonly reviews?: Maybe<ReviewConnection>;
/** User recommendations for similar media */
readonly recommendations?: Maybe<RecommendationConnection>;
readonly stats?: Maybe<MediaStats>;
/** The url for the media page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** If the media should have forum thread automatically created for it on airing episode release */
readonly autoCreateForumThread?: Maybe<Scalars['Boolean']>;
/** If the media is blocked from being recommended to/from */
readonly isRecommendationBlocked?: Maybe<Scalars['Boolean']>;
/** Notes for site moderators */
readonly modNotes?: Maybe<Scalars['String']>;
}
/** Anime or Manga */
export interface MediaStatusArgs {
version?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaDescriptionArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** Anime or Manga */
export interface MediaSourceArgs {
version?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaCharactersArgs {
sort?: Maybe<ReadonlyArray<Maybe<CharacterSort>>>;
role?: Maybe<CharacterRole>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaStaffArgs {
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaStudiosArgs {
sort?: Maybe<ReadonlyArray<Maybe<StudioSort>>>;
isMain?: Maybe<Scalars['Boolean']>;
}
/** Anime or Manga */
export interface MediaAiringScheduleArgs {
notYetAired?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaTrendsArgs {
sort?: Maybe<ReadonlyArray<Maybe<MediaTrendSort>>>;
releasing?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaReviewsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ReviewSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Anime or Manga */
export interface MediaRecommendationsArgs {
sort?: Maybe<ReadonlyArray<Maybe<RecommendationSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Internal - Media characters separated */
export interface MediaCharacter {
readonly __typename?: 'MediaCharacter';
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
/** The characters role in the media */
readonly role?: Maybe<CharacterRole>;
readonly roleNotes?: Maybe<Scalars['String']>;
readonly dubGroup?: Maybe<Scalars['String']>;
/** Media specific character name */
readonly characterName?: Maybe<Scalars['String']>;
/** The characters in the media voiced by the parent actor */
readonly character?: Maybe<Character>;
/** The voice actor of the character */
readonly voiceActor?: Maybe<Staff>;
}
export interface MediaConnection {
readonly __typename?: 'MediaConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<MediaEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Media>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
export interface MediaCoverImage {
readonly __typename?: 'MediaCoverImage';
/** The cover image url of the media at its largest size. If this size isn't available, large will be provided instead. */
readonly extraLarge?: Maybe<Scalars['String']>;
/** The cover image url of the media at a large size */
readonly large?: Maybe<Scalars['String']>;
/** The cover image url of the media at medium size */
readonly medium?: Maybe<Scalars['String']>;
/** Average #hex color of cover image */
readonly color?: Maybe<Scalars['String']>;
}
/** Media connection edge */
export interface MediaEdge {
readonly __typename?: 'MediaEdge';
readonly node?: Maybe<Media>;
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
/** The type of relation to the parent model */
readonly relationType?: Maybe<MediaRelation>;
/** If the studio is the main animation studio of the media (For Studio->MediaConnection field only) */
readonly isMainStudio: Scalars['Boolean'];
/** The characters in the media voiced by the parent actor */
readonly characters?: Maybe<ReadonlyArray<Maybe<Character>>>;
/** The characters role in the media */
readonly characterRole?: Maybe<CharacterRole>;
/** Media specific character name */
readonly characterName?: Maybe<Scalars['String']>;
/** Notes regarding the VA's role for the character */
readonly roleNotes?: Maybe<Scalars['String']>;
/** Used for grouping roles where multiple dubs exist for the same language. Either dubbing company name or language variant. */
readonly dubGroup?: Maybe<Scalars['String']>;
/** The role of the staff member in the production of the media */
readonly staffRole?: Maybe<Scalars['String']>;
/** The voice actors of the character */
readonly voiceActors?: Maybe<ReadonlyArray<Maybe<Staff>>>;
/** The voice actors of the character with role date */
readonly voiceActorRoles?: Maybe<ReadonlyArray<Maybe<StaffRoleType>>>;
/** The order the media should be displayed from the users favourites */
readonly favouriteOrder?: Maybe<Scalars['Int']>;
}
/** Media connection edge */
export interface MediaEdgeRelationTypeArgs {
version?: Maybe<Scalars['Int']>;
}
/** Media connection edge */
export interface MediaEdgeVoiceActorsArgs {
language?: Maybe<StaffLanguage>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
/** Media connection edge */
export interface MediaEdgeVoiceActorRolesArgs {
language?: Maybe<StaffLanguage>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
/** An external link to another site related to the media */
export interface MediaExternalLink {
readonly __typename?: 'MediaExternalLink';
/** The id of the external link */
readonly id: Scalars['Int'];
/** The url of the external link */
readonly url: Scalars['String'];
/** The site location of the external link */
readonly site: Scalars['String'];
}
/** An external link to another site related to the media */
export interface MediaExternalLinkInput {
/** The id of the external link */
readonly id: Scalars['Int'];
/** The url of the external link */
readonly url: Scalars['String'];
/** The site location of the external link */
readonly site: Scalars['String'];
}
/** The format the media was released in */
export const enum MediaFormat {
/** Anime broadcast on television */
Tv = 'TV',
/** Anime which are under 15 minutes in length and broadcast on television */
TvShort = 'TV_SHORT',
/** Anime movies with a theatrical release */
Movie = 'MOVIE',
/** Special episodes that have been included in DVD/Blu-ray releases, picture dramas, pilots, etc */
Special = 'SPECIAL',
/** (Original Video Animation) Anime that have been released directly on DVD/Blu-ray without originally going through a theatrical release or television broadcast */
Ova = 'OVA',
/** (Original Net Animation) Anime that have been originally released online or are only available through streaming services. */
Ona = 'ONA',
/** Short anime released as a music video */
Music = 'MUSIC',
/** Professionally published manga with more than one chapter */
Manga = 'MANGA',
/** Written books released as a series of light novels */
Novel = 'NOVEL',
/** Manga with just one chapter */
OneShot = 'ONE_SHOT'
}
/** List of anime or manga */
export interface MediaList {
readonly __typename?: 'MediaList';
/** The id of the list entry */
readonly id: Scalars['Int'];
/** The id of the user owner of the list entry */
readonly userId: Scalars['Int'];
/** The id of the media */
readonly mediaId: Scalars['Int'];
/** The watching/reading status */
readonly status?: Maybe<MediaListStatus>;
/** The score of the entry */
readonly score?: Maybe<Scalars['Float']>;
/** The amount of episodes/chapters consumed by the user */
readonly progress?: Maybe<Scalars['Int']>;
/** The amount of volumes read by the user */
readonly progressVolumes?: Maybe<Scalars['Int']>;
/** The amount of times the user has rewatched/read the media */
readonly repeat?: Maybe<Scalars['Int']>;
/** Priority of planning */
readonly priority?: Maybe<Scalars['Int']>;
/** If the entry should only be visible to authenticated user */
readonly private?: Maybe<Scalars['Boolean']>;
/** Text notes */
readonly notes?: Maybe<Scalars['String']>;
/** If the entry shown be hidden from non-custom lists */
readonly hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
/** Map of booleans for which custom lists the entry are in */
readonly customLists?: Maybe<Scalars['Json']>;
/** Map of advanced scores with name keys */
readonly advancedScores?: Maybe<Scalars['Json']>;
/** When the entry was started by the user */
readonly startedAt?: Maybe<FuzzyDate>;
/** When the entry was completed by the user */
readonly completedAt?: Maybe<FuzzyDate>;
/** When the entry data was last updated */
readonly updatedAt?: Maybe<Scalars['Int']>;
/** When the entry data was created */
readonly createdAt?: Maybe<Scalars['Int']>;
readonly media?: Maybe<Media>;
readonly user?: Maybe<User>;
}
/** List of anime or manga */
export interface MediaListScoreArgs {
format?: Maybe<ScoreFormat>;
}
/** List of anime or manga */
export interface MediaListCustomListsArgs {
asArray?: Maybe<Scalars['Boolean']>;
}
/** List of anime or manga */
export interface MediaListCollection {
readonly __typename?: 'MediaListCollection';
/** Grouped media list entries */
readonly lists?: Maybe<ReadonlyArray<Maybe<MediaListGroup>>>;
/** The owner of the list */
readonly user?: Maybe<User>;
/** If there is another chunk */
readonly hasNextChunk?: Maybe<Scalars['Boolean']>;
/**
* A map of media list entry arrays grouped by status
* @deprecated Not GraphQL spec compliant, use lists field instead.
*/
readonly statusLists?: Maybe<ReadonlyArray<Maybe<ReadonlyArray<Maybe<MediaList>>>>>;
/**
* A map of media list entry arrays grouped by custom lists
* @deprecated Not GraphQL spec compliant, use lists field instead.
*/
readonly customLists?: Maybe<ReadonlyArray<Maybe<ReadonlyArray<Maybe<MediaList>>>>>;
}
/** List of anime or manga */
export interface MediaListCollectionStatusListsArgs {
asArray?: Maybe<Scalars['Boolean']>;
}
/** List of anime or manga */
export interface MediaListCollectionCustomListsArgs {
asArray?: Maybe<Scalars['Boolean']>;
}
/** List group of anime or manga entries */
export interface MediaListGroup {
readonly __typename?: 'MediaListGroup';
/** Media list entries */
readonly entries?: Maybe<ReadonlyArray<Maybe<MediaList>>>;
readonly name?: Maybe<Scalars['String']>;
readonly isCustomList?: Maybe<Scalars['Boolean']>;
readonly isSplitCompletedList?: Maybe<Scalars['Boolean']>;
readonly status?: Maybe<MediaListStatus>;
}
/** A user's list options */
export interface MediaListOptions {
readonly __typename?: 'MediaListOptions';
/** The score format the user is using for media lists */
readonly scoreFormat?: Maybe<ScoreFormat>;
/** The default order list rows should be displayed in */
readonly rowOrder?: Maybe<Scalars['String']>;
/** @deprecated No longer used */
readonly useLegacyLists?: Maybe<Scalars['Boolean']>;
/** The user's anime list options */
readonly animeList?: Maybe<MediaListTypeOptions>;
/** The user's manga list options */
readonly mangaList?: Maybe<MediaListTypeOptions>;
/**
* The list theme options for both lists
* @deprecated No longer used
*/
readonly sharedTheme?: Maybe<Scalars['Json']>;
/**
* If the shared theme should be used instead of the individual list themes
* @deprecated No longer used
*/
readonly sharedThemeEnabled?: Maybe<Scalars['Boolean']>;
}
/** A user's list options for anime or manga lists */
export interface MediaListOptionsInput {
/** The order each list should be displayed in */
readonly sectionOrder?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** If the completed sections of the list should be separated by format */
readonly splitCompletedSectionByFormat?: Maybe<Scalars['Boolean']>;
/** The names of the user's custom lists */
readonly customLists?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The names of the user's advanced scoring sections */
readonly advancedScoring?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** If advanced scoring is enabled */
readonly advancedScoringEnabled?: Maybe<Scalars['Boolean']>;
/** list theme */
readonly theme?: Maybe<Scalars['String']>;
}
/** Media list sort enums */
export const enum MediaListSort {
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Status = 'STATUS',
StatusDesc = 'STATUS_DESC',
Progress = 'PROGRESS',
ProgressDesc = 'PROGRESS_DESC',
ProgressVolumes = 'PROGRESS_VOLUMES',
ProgressVolumesDesc = 'PROGRESS_VOLUMES_DESC',
Repeat = 'REPEAT',
RepeatDesc = 'REPEAT_DESC',
Priority = 'PRIORITY',
PriorityDesc = 'PRIORITY_DESC',
StartedOn = 'STARTED_ON',
StartedOnDesc = 'STARTED_ON_DESC',
FinishedOn = 'FINISHED_ON',
FinishedOnDesc = 'FINISHED_ON_DESC',
AddedTime = 'ADDED_TIME',
AddedTimeDesc = 'ADDED_TIME_DESC',
UpdatedTime = 'UPDATED_TIME',
UpdatedTimeDesc = 'UPDATED_TIME_DESC',
MediaTitleRomaji = 'MEDIA_TITLE_ROMAJI',
MediaTitleRomajiDesc = 'MEDIA_TITLE_ROMAJI_DESC',
MediaTitleEnglish = 'MEDIA_TITLE_ENGLISH',
MediaTitleEnglishDesc = 'MEDIA_TITLE_ENGLISH_DESC',
MediaTitleNative = 'MEDIA_TITLE_NATIVE',
MediaTitleNativeDesc = 'MEDIA_TITLE_NATIVE_DESC',
MediaPopularity = 'MEDIA_POPULARITY',
MediaPopularityDesc = 'MEDIA_POPULARITY_DESC'
}
/** Media list watching/reading status enum. */
export const enum MediaListStatus {
/** Currently watching/reading */
Current = 'CURRENT',
/** Planning to watch/read */
Planning = 'PLANNING',
/** Finished watching/reading */
Completed = 'COMPLETED',
/** Stopped watching/reading before completing */
Dropped = 'DROPPED',
/** Paused watching/reading */
Paused = 'PAUSED',
/** Re-watching/reading */
Repeating = 'REPEATING'
}
/** A user's list options for anime or manga lists */
export interface MediaListTypeOptions {
readonly __typename?: 'MediaListTypeOptions';
/** The order each list should be displayed in */
readonly sectionOrder?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** If the completed sections of the list should be separated by format */
readonly splitCompletedSectionByFormat?: Maybe<Scalars['Boolean']>;
/**
* The list theme options
* @deprecated This field has not yet been fully implemented and may change without warning
*/
readonly theme?: Maybe<Scalars['Json']>;
/** The names of the user's custom lists */
readonly customLists?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The names of the user's advanced scoring sections */
readonly advancedScoring?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** If advanced scoring is enabled */
readonly advancedScoringEnabled?: Maybe<Scalars['Boolean']>;
}
/** The ranking of a media in a particular time span and format compared to other media */
export interface MediaRank {
readonly __typename?: 'MediaRank';
/** The id of the rank */
readonly id: Scalars['Int'];
/** The numerical rank of the media */
readonly rank: Scalars['Int'];
/** The type of ranking */
readonly type: MediaRankType;
/** The format the media is ranked within */
readonly format: MediaFormat;
/** The year the media is ranked within */
readonly year?: Maybe<Scalars['Int']>;
/** The season the media is ranked within */
readonly season?: Maybe<MediaSeason>;
/** If the ranking is based on all time instead of a season/year */
readonly allTime?: Maybe<Scalars['Boolean']>;
/** String that gives context to the ranking type and time span */
readonly context: Scalars['String'];
}
/** The type of ranking */
export const enum MediaRankType {
/** Ranking is based on the media's ratings/score */
Rated = 'RATED',
/** Ranking is based on the media's popularity */
Popular = 'POPULAR'
}
/** Type of relation media has to its parent. */
export const enum MediaRelation {
/** An adaption of this media into a different format */
Adaptation = 'ADAPTATION',
/** Released before the relation */
Prequel = 'PREQUEL',
/** Released after the relation */
Sequel = 'SEQUEL',
/** The media a side story is from */
Parent = 'PARENT',
/** A side story of the parent media */
SideStory = 'SIDE_STORY',
/** Shares at least 1 character */
Character = 'CHARACTER',
/** A shortened and summarized version */
Summary = 'SUMMARY',
/** An alternative version of the same media */
Alternative = 'ALTERNATIVE',
/** An alternative version of the media with a different primary focus */
SpinOff = 'SPIN_OFF',
/** Other */
Other = 'OTHER',
/** Version 2 only. The source material the media was adapted from */
Source = 'SOURCE',
/** Version 2 only. */
Compilation = 'COMPILATION',
/** Version 2 only. */
Contains = 'CONTAINS'
}
export const enum MediaSeason {
/** Months December to February */
Winter = 'WINTER',
/** Months March to May */
Spring = 'SPRING',
/** Months June to August */
Summer = 'SUMMER',
/** Months September to November */
Fall = 'FALL'
}
/** Media sort enums */
export const enum MediaSort {
Id = 'ID',
IdDesc = 'ID_DESC',
TitleRomaji = 'TITLE_ROMAJI',
TitleRomajiDesc = 'TITLE_ROMAJI_DESC',
TitleEnglish = 'TITLE_ENGLISH',
TitleEnglishDesc = 'TITLE_ENGLISH_DESC',
TitleNative = 'TITLE_NATIVE',
TitleNativeDesc = 'TITLE_NATIVE_DESC',
Type = 'TYPE',
TypeDesc = 'TYPE_DESC',
Format = 'FORMAT',
FormatDesc = 'FORMAT_DESC',
StartDate = 'START_DATE',
StartDateDesc = 'START_DATE_DESC',
EndDate = 'END_DATE',
EndDateDesc = 'END_DATE_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Popularity = 'POPULARITY',
PopularityDesc = 'POPULARITY_DESC',
Trending = 'TRENDING',
TrendingDesc = 'TRENDING_DESC',
Episodes = 'EPISODES',
EpisodesDesc = 'EPISODES_DESC',
Duration = 'DURATION',
DurationDesc = 'DURATION_DESC',
Status = 'STATUS',
StatusDesc = 'STATUS_DESC',
Chapters = 'CHAPTERS',
ChaptersDesc = 'CHAPTERS_DESC',
Volumes = 'VOLUMES',
VolumesDesc = 'VOLUMES_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC'
}
/** Source type the media was adapted from */
export const enum MediaSource {
/** An original production not based of another work */
Original = 'ORIGINAL',
/** Asian comic book */
Manga = 'MANGA',
/** Written work published in volumes */
LightNovel = 'LIGHT_NOVEL',
/** Video game driven primary by text and narrative */
VisualNovel = 'VISUAL_NOVEL',
/** Video game */
VideoGame = 'VIDEO_GAME',
/** Other */
Other = 'OTHER',
/** Version 2 only. Written works not published in volumes */
Novel = 'NOVEL',
/** Version 2 only. Self-published works */
Doujinshi = 'DOUJINSHI',
/** Version 2 only. Japanese Anime */
Anime = 'ANIME'
}
/** A media's statistics */
export interface MediaStats {
readonly __typename?: 'MediaStats';
readonly scoreDistribution?: Maybe<ReadonlyArray<Maybe<ScoreDistribution>>>;
readonly statusDistribution?: Maybe<ReadonlyArray<Maybe<StatusDistribution>>>;
/** @deprecated Replaced by MediaTrends */
readonly airingProgression?: Maybe<ReadonlyArray<Maybe<AiringProgression>>>;
}
/** The current releasing status of the media */
export const enum MediaStatus {
/** Has completed and is no longer being released */
Finished = 'FINISHED',
/** Currently releasing */
Releasing = 'RELEASING',
/** To be released at a later date */
NotYetReleased = 'NOT_YET_RELEASED',
/** Ended before the work could be finished */
Cancelled = 'CANCELLED',
/** Version 2 only. Is currently paused from releasing and will resume at a later date */
Hiatus = 'HIATUS'
}
/** Data and links to legal streaming episodes on external sites */
export interface MediaStreamingEpisode {
readonly __typename?: 'MediaStreamingEpisode';
/** Title of the episode */
readonly title?: Maybe<Scalars['String']>;
/** Url of episode image thumbnail */
readonly thumbnail?: Maybe<Scalars['String']>;
/** The url of the episode */
readonly url?: Maybe<Scalars['String']>;
/** The site location of the streaming episodes */
readonly site?: Maybe<Scalars['String']>;
}
/** Media submission */
export interface MediaSubmission {
readonly __typename?: 'MediaSubmission';
/** The id of the submission */
readonly id: Scalars['Int'];
/** User submitter of the submission */
readonly submitter?: Maybe<User>;
/** Status of the submission */
readonly status?: Maybe<SubmissionStatus>;
readonly submitterStats?: Maybe<Scalars['Json']>;
readonly notes?: Maybe<Scalars['String']>;
readonly source?: Maybe<Scalars['String']>;
readonly changes?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
readonly media?: Maybe<Media>;
readonly submission?: Maybe<Media>;
readonly characters?: Maybe<ReadonlyArray<Maybe<MediaSubmissionComparison>>>;
readonly staff?: Maybe<ReadonlyArray<Maybe<MediaSubmissionComparison>>>;
readonly studios?: Maybe<ReadonlyArray<Maybe<MediaSubmissionComparison>>>;
readonly relations?: Maybe<ReadonlyArray<Maybe<MediaEdge>>>;
readonly externalLinks?: Maybe<ReadonlyArray<Maybe<MediaExternalLink>>>;
readonly createdAt?: Maybe<Scalars['Int']>;
}
/** Media submission with comparison to current data */
export interface MediaSubmissionComparison {
readonly __typename?: 'MediaSubmissionComparison';
readonly submission?: Maybe<MediaSubmissionEdge>;
readonly character?: Maybe<MediaCharacter>;
readonly staff?: Maybe<StaffEdge>;
readonly studio?: Maybe<StudioEdge>;
}
export interface MediaSubmissionEdge {
readonly __typename?: 'MediaSubmissionEdge';
/** The id of the direct submission */
readonly id?: Maybe<Scalars['Int']>;
readonly characterRole?: Maybe<CharacterRole>;
readonly staffRole?: Maybe<Scalars['String']>;
readonly roleNotes?: Maybe<Scalars['String']>;
readonly dubGroup?: Maybe<Scalars['String']>;
readonly characterName?: Maybe<Scalars['String']>;
readonly isMain?: Maybe<Scalars['Boolean']>;
readonly character?: Maybe<Character>;
readonly characterSubmission?: Maybe<Character>;
readonly voiceActor?: Maybe<Staff>;
readonly voiceActorSubmission?: Maybe<Staff>;
readonly staff?: Maybe<Staff>;
readonly staffSubmission?: Maybe<Staff>;
readonly studio?: Maybe<Studio>;
readonly media?: Maybe<Media>;
}
/** A tag that describes a theme or element of the media */
export interface MediaTag {
readonly __typename?: 'MediaTag';
/** The id of the tag */
readonly id: Scalars['Int'];
/** The name of the tag */
readonly name: Scalars['String'];
/** A general description of the tag */
readonly description?: Maybe<Scalars['String']>;
/** The categories of tags this tag belongs to */
readonly category?: Maybe<Scalars['String']>;
/** The relevance ranking of the tag out of the 100 for this media */
readonly rank?: Maybe<Scalars['Int']>;
/** If the tag could be a spoiler for any media */
readonly isGeneralSpoiler?: Maybe<Scalars['Boolean']>;
/** If the tag is a spoiler for this media */
readonly isMediaSpoiler?: Maybe<Scalars['Boolean']>;
/** If the tag is only for adult 18+ media */
readonly isAdult?: Maybe<Scalars['Boolean']>;
}
/** The official titles of the media in various languages */
export interface MediaTitle {
readonly __typename?: 'MediaTitle';
/** The romanization of the native language title */
readonly romaji?: Maybe<Scalars['String']>;
/** The official english title */
readonly english?: Maybe<Scalars['String']>;
/** Official title in it's native language */
readonly native?: Maybe<Scalars['String']>;
/** The currently authenticated users preferred title language. Default romaji for non-authenticated */
readonly userPreferred?: Maybe<Scalars['String']>;
}
/** The official titles of the media in various languages */
export interface MediaTitleRomajiArgs {
stylised?: Maybe<Scalars['Boolean']>;
}
/** The official titles of the media in various languages */
export interface MediaTitleEnglishArgs {
stylised?: Maybe<Scalars['Boolean']>;
}
/** The official titles of the media in various languages */
export interface MediaTitleNativeArgs {
stylised?: Maybe<Scalars['Boolean']>;
}
/** The official titles of the media in various languages */
export interface MediaTitleInput {
/** The romanization of the native language title */
readonly romaji?: Maybe<Scalars['String']>;
/** The official english title */
readonly english?: Maybe<Scalars['String']>;
/** Official title in it's native language */
readonly native?: Maybe<Scalars['String']>;
}
/** Media trailer or advertisement */
export interface MediaTrailer {
readonly __typename?: 'MediaTrailer';
/** The trailer video id */
readonly id?: Maybe<Scalars['String']>;
/** The site the video is hosted by (Currently either youtube or dailymotion) */
readonly site?: Maybe<Scalars['String']>;
/** The url for the thumbnail image of the video */
readonly thumbnail?: Maybe<Scalars['String']>;
}
/** Daily media statistics */
export interface MediaTrend {
readonly __typename?: 'MediaTrend';
/** The id of the tag */
readonly mediaId: Scalars['Int'];
/** The day the data was recorded (timestamp) */
readonly date: Scalars['Int'];
/** The amount of media activity on the day */
readonly trending: Scalars['Int'];
/** A weighted average score of all the user's scores of the media */
readonly averageScore?: Maybe<Scalars['Int']>;
/** The number of users with the media on their list */
readonly popularity?: Maybe<Scalars['Int']>;
/** The number of users with watching/reading the media */
readonly inProgress?: Maybe<Scalars['Int']>;
/** If the media was being released at this time */
readonly releasing: Scalars['Boolean'];
/** The episode number of the anime released on this day */
readonly episode?: Maybe<Scalars['Int']>;
/** The related media */
readonly media?: Maybe<Media>;
}
export interface MediaTrendConnection {
readonly __typename?: 'MediaTrendConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<MediaTrendEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<MediaTrend>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Media trend connection edge */
export interface MediaTrendEdge {
readonly __typename?: 'MediaTrendEdge';
readonly node?: Maybe<MediaTrend>;
}
/** Media trend sort enums */
export const enum MediaTrendSort {
Id = 'ID',
IdDesc = 'ID_DESC',
MediaId = 'MEDIA_ID',
MediaIdDesc = 'MEDIA_ID_DESC',
Date = 'DATE',
DateDesc = 'DATE_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Popularity = 'POPULARITY',
PopularityDesc = 'POPULARITY_DESC',
Trending = 'TRENDING',
TrendingDesc = 'TRENDING_DESC',
Episode = 'EPISODE',
EpisodeDesc = 'EPISODE_DESC'
}
/** Media type enum, anime or manga. */
export const enum MediaType {
/** Japanese Anime */
Anime = 'ANIME',
/** Asian comic */
Manga = 'MANGA'
}
/** User message activity */
export interface MessageActivity {
readonly __typename?: 'MessageActivity';
/** The id of the activity */
readonly id: Scalars['Int'];
/** The user id of the activity's recipient */
readonly recipientId?: Maybe<Scalars['Int']>;
/** The user id of the activity's sender */
readonly messengerId?: Maybe<Scalars['Int']>;
/** The type of the activity */
readonly type?: Maybe<ActivityType>;
/** The number of activity replies */
readonly replyCount: Scalars['Int'];
/** The message text (Markdown) */
readonly message?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
readonly isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
readonly isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** If the message is private and only viewable to the sender and recipients */
readonly isPrivate?: Maybe<Scalars['Boolean']>;
/** The url for the activity page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The time the activity was created at */
readonly createdAt: Scalars['Int'];
/** The user who the activity message was sent to */
readonly recipient?: Maybe<User>;
/** The user who sent the activity message */
readonly messenger?: Maybe<User>;
/** The written replies to the activity */
readonly replies?: Maybe<ReadonlyArray<Maybe<ActivityReply>>>;
/** The users who liked the activity */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** User message activity */
export interface MessageActivityMessageArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
export interface ModAction {
readonly __typename?: 'ModAction';
/** The id of the action */
readonly id: Scalars['Int'];
readonly user?: Maybe<User>;
readonly mod?: Maybe<User>;
readonly type?: Maybe<ModActionType>;
readonly objectId?: Maybe<Scalars['Int']>;
readonly objectType?: Maybe<Scalars['String']>;
readonly data?: Maybe<Scalars['String']>;
readonly createdAt: Scalars['Int'];
}
export const enum ModActionType {
Note = 'NOTE',
Ban = 'BAN',
Delete = 'DELETE',
Edit = 'EDIT',
Expire = 'EXPIRE',
Report = 'REPORT',
Reset = 'RESET',
Anon = 'ANON'
}
/** Mod role enums */
export const enum ModRole {
/** An AniList administrator */
Admin = 'ADMIN',
/** A head developer of AniList */
LeadDeveloper = 'LEAD_DEVELOPER',
/** An AniList developer */
Developer = 'DEVELOPER',
/** A lead community moderator */
LeadCommunity = 'LEAD_COMMUNITY',
/** A community moderator */
Community = 'COMMUNITY',
/** A discord community moderator */
DiscordCommunity = 'DISCORD_COMMUNITY',
/** A lead anime data moderator */
LeadAnimeData = 'LEAD_ANIME_DATA',
/** An anime data moderator */
AnimeData = 'ANIME_DATA',
/** A lead manga data moderator */
LeadMangaData = 'LEAD_MANGA_DATA',
/** A manga data moderator */
MangaData = 'MANGA_DATA',
/** A lead social media moderator */
LeadSocialMedia = 'LEAD_SOCIAL_MEDIA',
/** A social media moderator */
SocialMedia = 'SOCIAL_MEDIA',
/** A retired moderator */
Retired = 'RETIRED'
}
export interface Mutation {
readonly __typename?: 'Mutation';
readonly UpdateUser?: Maybe<User>;
/** Create or update a media list entry */
readonly SaveMediaListEntry?: Maybe<MediaList>;
/** Update multiple media list entries to the same values */
readonly UpdateMediaListEntries?: Maybe<ReadonlyArray<Maybe<MediaList>>>;
/** Delete a media list entry */
readonly DeleteMediaListEntry?: Maybe<Deleted>;
/** Delete a custom list and remove the list entries from it */
readonly DeleteCustomList?: Maybe<Deleted>;
/** Create or update text activity for the currently authenticated user */
readonly SaveTextActivity?: Maybe<TextActivity>;
/** Create or update message activity for the currently authenticated user */
readonly SaveMessageActivity?: Maybe<MessageActivity>;
/** Update list activity (Mod Only) */
readonly SaveListActivity?: Maybe<ListActivity>;
/** Delete an activity item of the authenticated users */
readonly DeleteActivity?: Maybe<Deleted>;
/** Toggle the subscription of an activity item */
readonly ToggleActivitySubscription?: Maybe<ActivityUnion>;
/** Create or update an activity reply */
readonly SaveActivityReply?: Maybe<ActivityReply>;
/** Delete an activity reply of the authenticated users */
readonly DeleteActivityReply?: Maybe<Deleted>;
/**
* Add or remove a like from a likeable type.
* Returns all the users who liked the same model
*/
readonly ToggleLike?: Maybe<ReadonlyArray<Maybe<User>>>;
/** Add or remove a like from a likeable type. */
readonly ToggleLikeV2?: Maybe<LikeableUnion>;
/** Toggle the un/following of a user */
readonly ToggleFollow?: Maybe<User>;
/** Favourite or unfavourite an anime, manga, character, staff member, or studio */
readonly ToggleFavourite?: Maybe<Favourites>;
/** Update the order favourites are displayed in */
readonly UpdateFavouriteOrder?: Maybe<Favourites>;
/** Create or update a review */
readonly SaveReview?: Maybe<Review>;
/** Delete a review */
readonly DeleteReview?: Maybe<Deleted>;
/** Rate a review */
readonly RateReview?: Maybe<Review>;
/** Recommendation a media */
readonly SaveRecommendation?: Maybe<Recommendation>;
/** Create or update a forum thread */
readonly SaveThread?: Maybe<Thread>;
/** Delete a thread */
readonly DeleteThread?: Maybe<Deleted>;
/** Toggle the subscription of a forum thread */
readonly ToggleThreadSubscription?: Maybe<Thread>;
/** Create or update a thread comment */
readonly SaveThreadComment?: Maybe<ThreadComment>;
/** Delete a thread comment */
readonly DeleteThreadComment?: Maybe<Deleted>;
readonly UpdateAniChartSettings?: Maybe<Scalars['Json']>;
readonly UpdateAniChartHighlights?: Maybe<Scalars['Json']>;
}
export interface MutationUpdateUserArgs {
about?: Maybe<Scalars['String']>;
titleLanguage?: Maybe<UserTitleLanguage>;
displayAdultContent?: Maybe<Scalars['Boolean']>;
airingNotifications?: Maybe<Scalars['Boolean']>;
scoreFormat?: Maybe<ScoreFormat>;
rowOrder?: Maybe<Scalars['String']>;
profileColor?: Maybe<Scalars['String']>;
donatorBadge?: Maybe<Scalars['String']>;
notificationOptions?: Maybe<ReadonlyArray<Maybe<NotificationOptionInput>>>;
timezone?: Maybe<Scalars['String']>;
activityMergeTime?: Maybe<Scalars['Int']>;
animeListOptions?: Maybe<MediaListOptionsInput>;
mangaListOptions?: Maybe<MediaListOptionsInput>;
staffNameLanguage?: Maybe<UserStaffNameLanguage>;
}
export interface MutationSaveMediaListEntryArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
status?: Maybe<MediaListStatus>;
score?: Maybe<Scalars['Float']>;
scoreRaw?: Maybe<Scalars['Int']>;
progress?: Maybe<Scalars['Int']>;
progressVolumes?: Maybe<Scalars['Int']>;
repeat?: Maybe<Scalars['Int']>;
priority?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
customLists?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
advancedScores?: Maybe<ReadonlyArray<Maybe<Scalars['Float']>>>;
startedAt?: Maybe<FuzzyDateInput>;
completedAt?: Maybe<FuzzyDateInput>;
}
export interface MutationUpdateMediaListEntriesArgs {
status?: Maybe<MediaListStatus>;
score?: Maybe<Scalars['Float']>;
scoreRaw?: Maybe<Scalars['Int']>;
progress?: Maybe<Scalars['Int']>;
progressVolumes?: Maybe<Scalars['Int']>;
repeat?: Maybe<Scalars['Int']>;
priority?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
hiddenFromStatusLists?: Maybe<Scalars['Boolean']>;
advancedScores?: Maybe<ReadonlyArray<Maybe<Scalars['Float']>>>;
startedAt?: Maybe<FuzzyDateInput>;
completedAt?: Maybe<FuzzyDateInput>;
ids?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
}
export interface MutationDeleteMediaListEntryArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationDeleteCustomListArgs {
customList?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
}
export interface MutationSaveTextActivityArgs {
id?: Maybe<Scalars['Int']>;
text?: Maybe<Scalars['String']>;
locked?: Maybe<Scalars['Boolean']>;
}
export interface MutationSaveMessageActivityArgs {
id?: Maybe<Scalars['Int']>;
message?: Maybe<Scalars['String']>;
recipientId?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
locked?: Maybe<Scalars['Boolean']>;
asMod?: Maybe<Scalars['Boolean']>;
}
export interface MutationSaveListActivityArgs {
id?: Maybe<Scalars['Int']>;
locked?: Maybe<Scalars['Boolean']>;
}
export interface MutationDeleteActivityArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationToggleActivitySubscriptionArgs {
activityId?: Maybe<Scalars['Int']>;
subscribe?: Maybe<Scalars['Boolean']>;
}
export interface MutationSaveActivityReplyArgs {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
text?: Maybe<Scalars['String']>;
asMod?: Maybe<Scalars['Boolean']>;
}
export interface MutationDeleteActivityReplyArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationToggleLikeArgs {
id?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
}
export interface MutationToggleLikeV2Args {
id?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
}
export interface MutationToggleFollowArgs {
userId?: Maybe<Scalars['Int']>;
}
export interface MutationToggleFavouriteArgs {
animeId?: Maybe<Scalars['Int']>;
mangaId?: Maybe<Scalars['Int']>;
characterId?: Maybe<Scalars['Int']>;
staffId?: Maybe<Scalars['Int']>;
studioId?: Maybe<Scalars['Int']>;
}
export interface MutationUpdateFavouriteOrderArgs {
animeIds?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mangaIds?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
characterIds?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
staffIds?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
studioIds?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
animeOrder?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mangaOrder?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
characterOrder?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
staffOrder?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
studioOrder?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
}
export interface MutationSaveReviewArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
body?: Maybe<Scalars['String']>;
summary?: Maybe<Scalars['String']>;
score?: Maybe<Scalars['Int']>;
private?: Maybe<Scalars['Boolean']>;
}
export interface MutationDeleteReviewArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationRateReviewArgs {
reviewId?: Maybe<Scalars['Int']>;
rating?: Maybe<ReviewRating>;
}
export interface MutationSaveRecommendationArgs {
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
rating?: Maybe<RecommendationRating>;
}
export interface MutationSaveThreadArgs {
id?: Maybe<Scalars['Int']>;
title?: Maybe<Scalars['String']>;
body?: Maybe<Scalars['String']>;
categories?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaCategories?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sticky?: Maybe<Scalars['Boolean']>;
locked?: Maybe<Scalars['Boolean']>;
}
export interface MutationDeleteThreadArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationToggleThreadSubscriptionArgs {
threadId?: Maybe<Scalars['Int']>;
subscribe?: Maybe<Scalars['Boolean']>;
}
export interface MutationSaveThreadCommentArgs {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
parentCommentId?: Maybe<Scalars['Int']>;
comment?: Maybe<Scalars['String']>;
}
export interface MutationDeleteThreadCommentArgs {
id?: Maybe<Scalars['Int']>;
}
export interface MutationUpdateAniChartSettingsArgs {
titleLanguage?: Maybe<Scalars['String']>;
outgoingLinkProvider?: Maybe<Scalars['String']>;
theme?: Maybe<Scalars['String']>;
sort?: Maybe<Scalars['String']>;
}
export interface MutationUpdateAniChartHighlightsArgs {
highlights?: Maybe<ReadonlyArray<Maybe<AniChartHighlightInput>>>;
}
/** Notification option */
export interface NotificationOption {
readonly __typename?: 'NotificationOption';
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** Whether this type of notification is enabled */
readonly enabled?: Maybe<Scalars['Boolean']>;
}
/** Notification option input */
export interface NotificationOptionInput {
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** Whether this type of notification is enabled */
readonly enabled?: Maybe<Scalars['Boolean']>;
}
/** Notification type enum */
export const enum NotificationType {
/** A user has sent you message */
ActivityMessage = 'ACTIVITY_MESSAGE',
/** A user has replied to your activity */
ActivityReply = 'ACTIVITY_REPLY',
/** A user has followed you */
Following = 'FOLLOWING',
/** A user has mentioned you in their activity */
ActivityMention = 'ACTIVITY_MENTION',
/** A user has mentioned you in a forum comment */
ThreadCommentMention = 'THREAD_COMMENT_MENTION',
/** A user has commented in one of your subscribed forum threads */
ThreadSubscribed = 'THREAD_SUBSCRIBED',
/** A user has replied to your forum comment */
ThreadCommentReply = 'THREAD_COMMENT_REPLY',
/** An anime you are currently watching has aired */
Airing = 'AIRING',
/** A user has liked your activity */
ActivityLike = 'ACTIVITY_LIKE',
/** A user has liked your activity reply */
ActivityReplyLike = 'ACTIVITY_REPLY_LIKE',
/** A user has liked your forum thread */
ThreadLike = 'THREAD_LIKE',
/** A user has liked your forum comment */
ThreadCommentLike = 'THREAD_COMMENT_LIKE',
/** A user has replied to activity you have also replied to */
ActivityReplySubscribed = 'ACTIVITY_REPLY_SUBSCRIBED',
/** A new anime or manga has been added to the site where its related media is on the user's list */
RelatedMediaAddition = 'RELATED_MEDIA_ADDITION'
}
/** Notification union type */
export type NotificationUnion =
| AiringNotification
| FollowingNotification
| ActivityMessageNotification
| ActivityMentionNotification
| ActivityReplyNotification
| ActivityReplySubscribedNotification
| ActivityLikeNotification
| ActivityReplyLikeNotification
| ThreadCommentMentionNotification
| ThreadCommentReplyNotification
| ThreadCommentSubscribedNotification
| ThreadCommentLikeNotification
| ThreadLikeNotification
| RelatedMediaAdditionNotification;
/** Page of data */
export interface Page {
readonly __typename?: 'Page';
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
readonly users?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly media?: Maybe<ReadonlyArray<Maybe<Media>>>;
readonly characters?: Maybe<ReadonlyArray<Maybe<Character>>>;
readonly staff?: Maybe<ReadonlyArray<Maybe<Staff>>>;
readonly studios?: Maybe<ReadonlyArray<Maybe<Studio>>>;
readonly mediaList?: Maybe<ReadonlyArray<Maybe<MediaList>>>;
readonly airingSchedules?: Maybe<ReadonlyArray<Maybe<AiringSchedule>>>;
readonly mediaTrends?: Maybe<ReadonlyArray<Maybe<MediaTrend>>>;
readonly notifications?: Maybe<ReadonlyArray<Maybe<NotificationUnion>>>;
readonly followers?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly following?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly activities?: Maybe<ReadonlyArray<Maybe<ActivityUnion>>>;
readonly activityReplies?: Maybe<ReadonlyArray<Maybe<ActivityReply>>>;
readonly threads?: Maybe<ReadonlyArray<Maybe<Thread>>>;
readonly threadComments?: Maybe<ReadonlyArray<Maybe<ThreadComment>>>;
readonly reviews?: Maybe<ReadonlyArray<Maybe<Review>>>;
readonly recommendations?: Maybe<ReadonlyArray<Maybe<Recommendation>>>;
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** Page of data */
export interface PageUsersArgs {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data */
export interface PageMediaArgs {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<ReadonlyArray<Maybe<MediaSource>>>;
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
}
/** Page of data */
export interface PageCharactersArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<CharacterSort>>>;
}
/** Page of data */
export interface PageStaffArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
/** Page of data */
export interface PageStudiosArgs {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StudioSort>>>;
}
/** Page of data */
export interface PageMediaListArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaListSort>>>;
}
/** Page of data */
export interface PageAiringSchedulesArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<AiringSort>>>;
}
/** Page of data */
export interface PageMediaTrendsArgs {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaTrendSort>>>;
}
/** Page of data */
export interface PageNotificationsArgs {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<ReadonlyArray<Maybe<NotificationType>>>;
}
/** Page of data */
export interface PageFollowersArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data */
export interface PageFollowingArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
/** Page of data */
export interface PageActivitiesArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
type_not_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ActivitySort>>>;
}
/** Page of data */
export interface PageActivityRepliesArgs {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
}
/** Page of data */
export interface PageThreadsArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadSort>>>;
}
/** Page of data */
export interface PageThreadCommentsArgs {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadCommentSort>>>;
}
/** Page of data */
export interface PageReviewsArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<ReadonlyArray<Maybe<ReviewSort>>>;
}
/** Page of data */
export interface PageRecommendationsArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<RecommendationSort>>>;
}
/** Page of data */
export interface PageLikesArgs {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
}
export interface PageInfo {
readonly __typename?: 'PageInfo';
/** The total number of items */
readonly total?: Maybe<Scalars['Int']>;
/** The count on a page */
readonly perPage?: Maybe<Scalars['Int']>;
/** The current page */
readonly currentPage?: Maybe<Scalars['Int']>;
/** The last page */
readonly lastPage?: Maybe<Scalars['Int']>;
/** If there is another page */
readonly hasNextPage?: Maybe<Scalars['Boolean']>;
}
/** Provides the parsed markdown as html */
export interface ParsedMarkdown {
readonly __typename?: 'ParsedMarkdown';
/** The parsed markdown as html */
readonly html?: Maybe<Scalars['String']>;
}
export interface Query {
readonly __typename?: 'Query';
readonly Page?: Maybe<Page>;
/** Media query */
readonly Media?: Maybe<Media>;
/** Media Trend query */
readonly MediaTrend?: Maybe<MediaTrend>;
/** Airing schedule query */
readonly AiringSchedule?: Maybe<AiringSchedule>;
/** Character query */
readonly Character?: Maybe<Character>;
/** Staff query */
readonly Staff?: Maybe<Staff>;
/** Media list query */
readonly MediaList?: Maybe<MediaList>;
/** Media list collection query, provides list pre-grouped by status & custom lists. User ID and Media Type arguments required. */
readonly MediaListCollection?: Maybe<MediaListCollection>;
/** Collection of all the possible media genres */
readonly GenreCollection?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** Collection of all the possible media tags */
readonly MediaTagCollection?: Maybe<ReadonlyArray<Maybe<MediaTag>>>;
/** User query */
readonly User?: Maybe<User>;
/** Get the currently authenticated user */
readonly Viewer?: Maybe<User>;
/** Notification query */
readonly Notification?: Maybe<NotificationUnion>;
/** Studio query */
readonly Studio?: Maybe<Studio>;
/** Review query */
readonly Review?: Maybe<Review>;
/** Activity query */
readonly Activity?: Maybe<ActivityUnion>;
/** Activity reply query */
readonly ActivityReply?: Maybe<ActivityReply>;
/** Follow query */
readonly Following?: Maybe<User>;
/** Follow query */
readonly Follower?: Maybe<User>;
/** Thread query */
readonly Thread?: Maybe<Thread>;
/** Comment query */
readonly ThreadComment?: Maybe<ReadonlyArray<Maybe<ThreadComment>>>;
/** Recommendation query */
readonly Recommendation?: Maybe<Recommendation>;
/** Like query */
readonly Like?: Maybe<User>;
/** Provide AniList markdown to be converted to html (Requires auth) */
readonly Markdown?: Maybe<ParsedMarkdown>;
readonly AniChartUser?: Maybe<AniChartUser>;
/** Site statistics query */
readonly SiteStatistics?: Maybe<SiteStatistics>;
/** Get the user who added a tag to a media */
readonly MediaTagUser?: Maybe<User>;
}
export interface QueryPageArgs {
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface QueryMediaArgs {
id?: Maybe<Scalars['Int']>;
idMal?: Maybe<Scalars['Int']>;
startDate?: Maybe<Scalars['FuzzyDateInt']>;
endDate?: Maybe<Scalars['FuzzyDateInt']>;
season?: Maybe<MediaSeason>;
seasonYear?: Maybe<Scalars['Int']>;
type?: Maybe<MediaType>;
format?: Maybe<MediaFormat>;
status?: Maybe<MediaStatus>;
episodes?: Maybe<Scalars['Int']>;
duration?: Maybe<Scalars['Int']>;
chapters?: Maybe<Scalars['Int']>;
volumes?: Maybe<Scalars['Int']>;
isAdult?: Maybe<Scalars['Boolean']>;
genre?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
minimumTagRank?: Maybe<Scalars['Int']>;
tagCategory?: Maybe<Scalars['String']>;
onList?: Maybe<Scalars['Boolean']>;
licensedBy?: Maybe<Scalars['String']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
source?: Maybe<MediaSource>;
countryOfOrigin?: Maybe<Scalars['CountryCode']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not?: Maybe<Scalars['Int']>;
idMal_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
idMal_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
startDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
startDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startDate_like?: Maybe<Scalars['String']>;
endDate_greater?: Maybe<Scalars['FuzzyDateInt']>;
endDate_lesser?: Maybe<Scalars['FuzzyDateInt']>;
endDate_like?: Maybe<Scalars['String']>;
format_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
format_not?: Maybe<MediaFormat>;
format_not_in?: Maybe<ReadonlyArray<Maybe<MediaFormat>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
status_not?: Maybe<MediaStatus>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaStatus>>>;
episodes_greater?: Maybe<Scalars['Int']>;
episodes_lesser?: Maybe<Scalars['Int']>;
duration_greater?: Maybe<Scalars['Int']>;
duration_lesser?: Maybe<Scalars['Int']>;
chapters_greater?: Maybe<Scalars['Int']>;
chapters_lesser?: Maybe<Scalars['Int']>;
volumes_greater?: Maybe<Scalars['Int']>;
volumes_lesser?: Maybe<Scalars['Int']>;
genre_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
genre_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tag_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
tagCategory_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
licensedBy_in?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
averageScore_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
source_in?: Maybe<ReadonlyArray<Maybe<MediaSource>>>;
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
}
export interface QueryMediaTrendArgs {
mediaId?: Maybe<Scalars['Int']>;
date?: Maybe<Scalars['Int']>;
trending?: Maybe<Scalars['Int']>;
averageScore?: Maybe<Scalars['Int']>;
popularity?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
releasing?: Maybe<Scalars['Boolean']>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
date_greater?: Maybe<Scalars['Int']>;
date_lesser?: Maybe<Scalars['Int']>;
trending_greater?: Maybe<Scalars['Int']>;
trending_lesser?: Maybe<Scalars['Int']>;
trending_not?: Maybe<Scalars['Int']>;
averageScore_greater?: Maybe<Scalars['Int']>;
averageScore_lesser?: Maybe<Scalars['Int']>;
averageScore_not?: Maybe<Scalars['Int']>;
popularity_greater?: Maybe<Scalars['Int']>;
popularity_lesser?: Maybe<Scalars['Int']>;
popularity_not?: Maybe<Scalars['Int']>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
episode_not?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaTrendSort>>>;
}
export interface QueryAiringScheduleArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
episode?: Maybe<Scalars['Int']>;
airingAt?: Maybe<Scalars['Int']>;
notYetAired?: Maybe<Scalars['Boolean']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not?: Maybe<Scalars['Int']>;
episode_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
episode_greater?: Maybe<Scalars['Int']>;
episode_lesser?: Maybe<Scalars['Int']>;
airingAt_greater?: Maybe<Scalars['Int']>;
airingAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<AiringSort>>>;
}
export interface QueryCharacterArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<CharacterSort>>>;
}
export interface QueryStaffArgs {
id?: Maybe<Scalars['Int']>;
isBirthday?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StaffSort>>>;
}
export interface QueryMediaListArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
mediaId?: Maybe<Scalars['Int']>;
isFollowing?: Maybe<Scalars['Boolean']>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
compareWithAuthList?: Maybe<Scalars['Boolean']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaListSort>>>;
}
export interface QueryMediaListCollectionArgs {
userId?: Maybe<Scalars['Int']>;
userName?: Maybe<Scalars['String']>;
type?: Maybe<MediaType>;
status?: Maybe<MediaListStatus>;
notes?: Maybe<Scalars['String']>;
startedAt?: Maybe<Scalars['FuzzyDateInt']>;
completedAt?: Maybe<Scalars['FuzzyDateInt']>;
forceSingleCompletedList?: Maybe<Scalars['Boolean']>;
chunk?: Maybe<Scalars['Int']>;
perChunk?: Maybe<Scalars['Int']>;
status_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not_in?: Maybe<ReadonlyArray<Maybe<MediaListStatus>>>;
status_not?: Maybe<MediaListStatus>;
notes_like?: Maybe<Scalars['String']>;
startedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
startedAt_like?: Maybe<Scalars['String']>;
completedAt_greater?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_lesser?: Maybe<Scalars['FuzzyDateInt']>;
completedAt_like?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<MediaListSort>>>;
}
export interface QueryMediaTagCollectionArgs {
status?: Maybe<Scalars['Int']>;
}
export interface QueryUserArgs {
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
isModerator?: Maybe<Scalars['Boolean']>;
search?: Maybe<Scalars['String']>;
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
export interface QueryNotificationArgs {
type?: Maybe<NotificationType>;
resetNotificationCount?: Maybe<Scalars['Boolean']>;
type_in?: Maybe<ReadonlyArray<Maybe<NotificationType>>>;
}
export interface QueryStudioArgs {
id?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<StudioSort>>>;
}
export interface QueryReviewArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
mediaType?: Maybe<MediaType>;
sort?: Maybe<ReadonlyArray<Maybe<ReviewSort>>>;
}
export interface QueryActivityArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
messengerId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
type?: Maybe<ActivityType>;
isFollowing?: Maybe<Scalars['Boolean']>;
hasReplies?: Maybe<Scalars['Boolean']>;
hasRepliesOrTypeText?: Maybe<Scalars['Boolean']>;
createdAt?: Maybe<Scalars['Int']>;
id_not?: Maybe<Scalars['Int']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
id_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not?: Maybe<Scalars['Int']>;
userId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
userId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not?: Maybe<Scalars['Int']>;
messengerId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
messengerId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not?: Maybe<Scalars['Int']>;
mediaId_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
mediaId_not_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
type_not?: Maybe<ActivityType>;
type_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
type_not_in?: Maybe<ReadonlyArray<Maybe<ActivityType>>>;
createdAt_greater?: Maybe<Scalars['Int']>;
createdAt_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ActivitySort>>>;
}
export interface QueryActivityReplyArgs {
id?: Maybe<Scalars['Int']>;
activityId?: Maybe<Scalars['Int']>;
}
export interface QueryFollowingArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
export interface QueryFollowerArgs {
userId: Scalars['Int'];
sort?: Maybe<ReadonlyArray<Maybe<UserSort>>>;
}
export interface QueryThreadArgs {
id?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
replyUserId?: Maybe<Scalars['Int']>;
subscribed?: Maybe<Scalars['Boolean']>;
categoryId?: Maybe<Scalars['Int']>;
mediaCategoryId?: Maybe<Scalars['Int']>;
search?: Maybe<Scalars['String']>;
id_in?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadSort>>>;
}
export interface QueryThreadCommentArgs {
id?: Maybe<Scalars['Int']>;
threadId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<ThreadCommentSort>>>;
}
export interface QueryRecommendationArgs {
id?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
mediaRecommendationId?: Maybe<Scalars['Int']>;
userId?: Maybe<Scalars['Int']>;
rating?: Maybe<Scalars['Int']>;
onList?: Maybe<Scalars['Boolean']>;
rating_greater?: Maybe<Scalars['Int']>;
rating_lesser?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<RecommendationSort>>>;
}
export interface QueryLikeArgs {
likeableId?: Maybe<Scalars['Int']>;
type?: Maybe<LikeableType>;
}
export interface QueryMarkdownArgs {
markdown: Scalars['String'];
}
export interface QueryMediaTagUserArgs {
tagId?: Maybe<Scalars['Int']>;
mediaId?: Maybe<Scalars['Int']>;
}
/** Media recommendation */
export interface Recommendation {
readonly __typename?: 'Recommendation';
/** The id of the recommendation */
readonly id: Scalars['Int'];
/** Users rating of the recommendation */
readonly rating?: Maybe<Scalars['Int']>;
/** The rating of the recommendation by currently authenticated user */
readonly userRating?: Maybe<RecommendationRating>;
/** The media the recommendation is from */
readonly media?: Maybe<Media>;
/** The recommended media */
readonly mediaRecommendation?: Maybe<Media>;
/** The user that first created the recommendation */
readonly user?: Maybe<User>;
}
export interface RecommendationConnection {
readonly __typename?: 'RecommendationConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<RecommendationEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Recommendation>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Recommendation connection edge */
export interface RecommendationEdge {
readonly __typename?: 'RecommendationEdge';
readonly node?: Maybe<Recommendation>;
}
/** Recommendation rating enums */
export const enum RecommendationRating {
NoRating = 'NO_RATING',
RateUp = 'RATE_UP',
RateDown = 'RATE_DOWN'
}
/** Recommendation sort enums */
export const enum RecommendationSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Rating = 'RATING',
RatingDesc = 'RATING_DESC'
}
/** Notification for when new media is added to the site */
export interface RelatedMediaAdditionNotification {
readonly __typename?: 'RelatedMediaAdditionNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the new media */
readonly mediaId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The associated media of the airing schedule */
readonly media?: Maybe<Media>;
}
export interface Report {
readonly __typename?: 'Report';
readonly id: Scalars['Int'];
readonly reporter?: Maybe<User>;
readonly reported?: Maybe<User>;
readonly reason?: Maybe<Scalars['String']>;
/** When the entry data was created */
readonly createdAt?: Maybe<Scalars['Int']>;
readonly cleared?: Maybe<Scalars['Boolean']>;
}
/** A Review that features in an anime or manga */
export interface Review {
readonly __typename?: 'Review';
/** The id of the review */
readonly id: Scalars['Int'];
/** The id of the review's creator */
readonly userId: Scalars['Int'];
/** The id of the review's media */
readonly mediaId: Scalars['Int'];
/** For which type of media the review is for */
readonly mediaType?: Maybe<MediaType>;
/** A short summary of the review */
readonly summary?: Maybe<Scalars['String']>;
/** The main review body text */
readonly body?: Maybe<Scalars['String']>;
/** The total user rating of the review */
readonly rating?: Maybe<Scalars['Int']>;
/** The amount of user ratings of the review */
readonly ratingAmount?: Maybe<Scalars['Int']>;
/** The rating of the review by currently authenticated user */
readonly userRating?: Maybe<ReviewRating>;
/** The review score of the media */
readonly score?: Maybe<Scalars['Int']>;
/** If the review is not yet publicly published and is only viewable by creator */
readonly private?: Maybe<Scalars['Boolean']>;
/** The url for the review page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The time of the thread creation */
readonly createdAt: Scalars['Int'];
/** The time of the thread last update */
readonly updatedAt: Scalars['Int'];
/** The creator of the review */
readonly user?: Maybe<User>;
/** The media the review is of */
readonly media?: Maybe<Media>;
}
/** A Review that features in an anime or manga */
export interface ReviewBodyArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
export interface ReviewConnection {
readonly __typename?: 'ReviewConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<ReviewEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Review>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Review connection edge */
export interface ReviewEdge {
readonly __typename?: 'ReviewEdge';
readonly node?: Maybe<Review>;
}
/** Review rating enums */
export const enum ReviewRating {
NoVote = 'NO_VOTE',
UpVote = 'UP_VOTE',
DownVote = 'DOWN_VOTE'
}
/** Review sort enums */
export const enum ReviewSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Score = 'SCORE',
ScoreDesc = 'SCORE_DESC',
Rating = 'RATING',
RatingDesc = 'RATING_DESC',
CreatedAt = 'CREATED_AT',
CreatedAtDesc = 'CREATED_AT_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC'
}
/** Feed of mod edit activity */
export interface RevisionHistory {
readonly __typename?: 'RevisionHistory';
/** The id of the media */
readonly id: Scalars['Int'];
/** The action taken on the objects */
readonly action?: Maybe<RevisionHistoryAction>;
/** A JSON object of the fields that changed */
readonly changes?: Maybe<Scalars['Json']>;
/** The user who made the edit to the object */
readonly user?: Maybe<User>;
/** The media the mod feed entry references */
readonly media?: Maybe<Media>;
/** The character the mod feed entry references */
readonly character?: Maybe<Character>;
/** The staff member the mod feed entry references */
readonly staff?: Maybe<Staff>;
/** The studio the mod feed entry references */
readonly studio?: Maybe<Studio>;
/** When the mod feed entry was created */
readonly createdAt?: Maybe<Scalars['Int']>;
}
/** Revision history actions */
export const enum RevisionHistoryAction {
Create = 'CREATE',
Edit = 'EDIT'
}
/** A user's list score distribution. */
export interface ScoreDistribution {
readonly __typename?: 'ScoreDistribution';
readonly score?: Maybe<Scalars['Int']>;
/** The amount of list entries with this score */
readonly amount?: Maybe<Scalars['Int']>;
}
/** Media list scoring type */
export const enum ScoreFormat {
/** An integer from 0-100 */
Point_100 = 'POINT_100',
/** A float from 0-10 with 1 decimal place */
Point_10Decimal = 'POINT_10_DECIMAL',
/** An integer from 0-10 */
Point_10 = 'POINT_10',
/** An integer from 0-5. Should be represented in Stars */
Point_5 = 'POINT_5',
/** An integer from 0-3. Should be represented in Smileys. 0 => No Score, 1 => :(, 2 => :|, 3 => :) */
Point_3 = 'POINT_3'
}
export interface SiteStatistics {
readonly __typename?: 'SiteStatistics';
readonly users?: Maybe<SiteTrendConnection>;
readonly anime?: Maybe<SiteTrendConnection>;
readonly manga?: Maybe<SiteTrendConnection>;
readonly characters?: Maybe<SiteTrendConnection>;
readonly staff?: Maybe<SiteTrendConnection>;
readonly studios?: Maybe<SiteTrendConnection>;
readonly reviews?: Maybe<SiteTrendConnection>;
}
export interface SiteStatisticsUsersArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsAnimeArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsMangaArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsCharactersArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsStaffArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsStudiosArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface SiteStatisticsReviewsArgs {
sort?: Maybe<ReadonlyArray<Maybe<SiteTrendSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Daily site statistics */
export interface SiteTrend {
readonly __typename?: 'SiteTrend';
/** The day the data was recorded (timestamp) */
readonly date: Scalars['Int'];
readonly count: Scalars['Int'];
/** The change from yesterday */
readonly change: Scalars['Int'];
}
export interface SiteTrendConnection {
readonly __typename?: 'SiteTrendConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<SiteTrendEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<SiteTrend>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Site trend connection edge */
export interface SiteTrendEdge {
readonly __typename?: 'SiteTrendEdge';
readonly node?: Maybe<SiteTrend>;
}
/** Site trend sort enums */
export const enum SiteTrendSort {
Date = 'DATE',
DateDesc = 'DATE_DESC',
Count = 'COUNT',
CountDesc = 'COUNT_DESC',
Change = 'CHANGE',
ChangeDesc = 'CHANGE_DESC'
}
/** Voice actors or production staff */
export interface Staff {
readonly __typename?: 'Staff';
/** The id of the staff member */
readonly id: Scalars['Int'];
/** The names of the staff member */
readonly name?: Maybe<StaffName>;
/**
* The primary language the staff member dub's in
* @deprecated Replaced with languageV2
*/
readonly language?: Maybe<StaffLanguage>;
/** The primary language of the staff member. Current values: Japanese, English, Korean, Italian, Spanish, Portuguese, French, German, Hebrew, Hungarian, Chinese, Arabic, Filipino, Catalan */
readonly languageV2?: Maybe<Scalars['String']>;
/** The staff images */
readonly image?: Maybe<StaffImage>;
/** A general description of the staff member */
readonly description?: Maybe<Scalars['String']>;
/** The person's primary occupations */
readonly primaryOccupations?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The staff's gender. Usually Male, Female, or Non-binary but can be any string. */
readonly gender?: Maybe<Scalars['String']>;
readonly dateOfBirth?: Maybe<FuzzyDate>;
readonly dateOfDeath?: Maybe<FuzzyDate>;
/** The person's age in years */
readonly age?: Maybe<Scalars['Int']>;
/** [startYear, endYear] (If the 2nd value is not present staff is still active) */
readonly yearsActive?: Maybe<ReadonlyArray<Maybe<Scalars['Int']>>>;
/** The persons birthplace or hometown */
readonly homeTown?: Maybe<Scalars['String']>;
/** The persons blood type */
readonly bloodType?: Maybe<Scalars['String']>;
/** If the staff member is marked as favourite by the currently authenticated user */
readonly isFavourite: Scalars['Boolean'];
/** If the staff member is blocked from being added to favourites */
readonly isFavouriteBlocked: Scalars['Boolean'];
/** The url for the staff page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** Media where the staff member has a production role */
readonly staffMedia?: Maybe<MediaConnection>;
/** Characters voiced by the actor */
readonly characters?: Maybe<CharacterConnection>;
/** Media the actor voiced characters in. (Same data as characters with media as node instead of characters) */
readonly characterMedia?: Maybe<MediaConnection>;
/** @deprecated No data available */
readonly updatedAt?: Maybe<Scalars['Int']>;
/** Staff member that the submission is referencing */
readonly staff?: Maybe<Staff>;
/** Submitter for the submission */
readonly submitter?: Maybe<User>;
/** Status of the submission */
readonly submissionStatus?: Maybe<Scalars['Int']>;
/** Inner details of submission status */
readonly submissionNotes?: Maybe<Scalars['String']>;
/** The amount of user's who have favourited the staff member */
readonly favourites?: Maybe<Scalars['Int']>;
/** Notes for site moderators */
readonly modNotes?: Maybe<Scalars['String']>;
}
/** Voice actors or production staff */
export interface StaffDescriptionArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** Voice actors or production staff */
export interface StaffStaffMediaArgs {
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
type?: Maybe<MediaType>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Voice actors or production staff */
export interface StaffCharactersArgs {
sort?: Maybe<ReadonlyArray<Maybe<CharacterSort>>>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
/** Voice actors or production staff */
export interface StaffCharacterMediaArgs {
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface StaffConnection {
readonly __typename?: 'StaffConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<StaffEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Staff>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Staff connection edge */
export interface StaffEdge {
readonly __typename?: 'StaffEdge';
readonly node?: Maybe<Staff>;
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
/** The role of the staff member in the production of the media */
readonly role?: Maybe<Scalars['String']>;
/** The order the staff should be displayed from the users favourites */
readonly favouriteOrder?: Maybe<Scalars['Int']>;
}
export interface StaffImage {
readonly __typename?: 'StaffImage';
/** The person's image of media at its largest size */
readonly large?: Maybe<Scalars['String']>;
/** The person's image of media at medium size */
readonly medium?: Maybe<Scalars['String']>;
}
/** The primary language of the voice actor */
export const enum StaffLanguage {
/** Japanese */
Japanese = 'JAPANESE',
/** English */
English = 'ENGLISH',
/** Korean */
Korean = 'KOREAN',
/** Italian */
Italian = 'ITALIAN',
/** Spanish */
Spanish = 'SPANISH',
/** Portuguese */
Portuguese = 'PORTUGUESE',
/** French */
French = 'FRENCH',
/** German */
German = 'GERMAN',
/** Hebrew */
Hebrew = 'HEBREW',
/** Hungarian */
Hungarian = 'HUNGARIAN'
}
/** The names of the staff member */
export interface StaffName {
readonly __typename?: 'StaffName';
/** The person's given name */
readonly first?: Maybe<Scalars['String']>;
/** The person's middle name */
readonly middle?: Maybe<Scalars['String']>;
/** The person's surname */
readonly last?: Maybe<Scalars['String']>;
/** The person's first and last name */
readonly full?: Maybe<Scalars['String']>;
/** The person's full name in their native language */
readonly native?: Maybe<Scalars['String']>;
/** Other names the staff member might be referred to as (pen names) */
readonly alternative?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
/** The currently authenticated users preferred name language. Default romaji for non-authenticated */
readonly userPreferred?: Maybe<Scalars['String']>;
}
/** The names of the staff member */
export interface StaffNameInput {
/** The person's given name */
readonly first?: Maybe<Scalars['String']>;
/** The person's middle name */
readonly middle?: Maybe<Scalars['String']>;
/** The person's surname */
readonly last?: Maybe<Scalars['String']>;
/** The person's full name in their native language */
readonly native?: Maybe<Scalars['String']>;
/** Other names the character might be referred by */
readonly alternative?: Maybe<ReadonlyArray<Maybe<Scalars['String']>>>;
}
/** Voice actor role for a character */
export interface StaffRoleType {
readonly __typename?: 'StaffRoleType';
/** The voice actors of the character */
readonly voiceActor?: Maybe<Staff>;
/** Notes regarding the VA's role for the character */
readonly roleNotes?: Maybe<Scalars['String']>;
/** Used for grouping roles where multiple dubs exist for the same language. Either dubbing company name or language variant. */
readonly dubGroup?: Maybe<Scalars['String']>;
}
/** Staff sort enums */
export const enum StaffSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Role = 'ROLE',
RoleDesc = 'ROLE_DESC',
Language = 'LANGUAGE',
LanguageDesc = 'LANGUAGE_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC',
/** Order manually decided by moderators */
Relevance = 'RELEVANCE'
}
/** User's staff statistics */
export interface StaffStats {
readonly __typename?: 'StaffStats';
readonly staff?: Maybe<Staff>;
readonly amount?: Maybe<Scalars['Int']>;
readonly meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the staff member has been watched by the user */
readonly timeWatched?: Maybe<Scalars['Int']>;
}
/** A submission for a staff that features in an anime or manga */
export interface StaffSubmission {
readonly __typename?: 'StaffSubmission';
/** The id of the submission */
readonly id: Scalars['Int'];
/** Staff that the submission is referencing */
readonly staff?: Maybe<Staff>;
/** The staff submission changes */
readonly submission?: Maybe<Staff>;
/** Submitter for the submission */
readonly submitter?: Maybe<User>;
/** Status of the submission */
readonly status?: Maybe<SubmissionStatus>;
/** Inner details of submission status */
readonly notes?: Maybe<Scalars['String']>;
readonly source?: Maybe<Scalars['String']>;
readonly createdAt?: Maybe<Scalars['Int']>;
}
/** The distribution of the watching/reading status of media or a user's list */
export interface StatusDistribution {
readonly __typename?: 'StatusDistribution';
/** The day the activity took place (Unix timestamp) */
readonly status?: Maybe<MediaListStatus>;
/** The amount of entries with this status */
readonly amount?: Maybe<Scalars['Int']>;
}
/** Animation or production company */
export interface Studio {
readonly __typename?: 'Studio';
/** The id of the studio */
readonly id: Scalars['Int'];
/** The name of the studio */
readonly name: Scalars['String'];
/** If the studio is an animation studio or a different kind of company */
readonly isAnimationStudio: Scalars['Boolean'];
/** The media the studio has worked on */
readonly media?: Maybe<MediaConnection>;
/** The url for the studio page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** If the studio is marked as favourite by the currently authenticated user */
readonly isFavourite: Scalars['Boolean'];
/** The amount of user's who have favourited the studio */
readonly favourites?: Maybe<Scalars['Int']>;
}
/** Animation or production company */
export interface StudioMediaArgs {
sort?: Maybe<ReadonlyArray<Maybe<MediaSort>>>;
isMain?: Maybe<Scalars['Boolean']>;
onList?: Maybe<Scalars['Boolean']>;
page?: Maybe<Scalars['Int']>;
perPage?: Maybe<Scalars['Int']>;
}
export interface StudioConnection {
readonly __typename?: 'StudioConnection';
readonly edges?: Maybe<ReadonlyArray<Maybe<StudioEdge>>>;
readonly nodes?: Maybe<ReadonlyArray<Maybe<Studio>>>;
/** The pagination information */
readonly pageInfo?: Maybe<PageInfo>;
}
/** Studio connection edge */
export interface StudioEdge {
readonly __typename?: 'StudioEdge';
readonly node?: Maybe<Studio>;
/** The id of the connection */
readonly id?: Maybe<Scalars['Int']>;
/** If the studio is the main animation studio of the anime */
readonly isMain: Scalars['Boolean'];
/** The order the character should be displayed from the users favourites */
readonly favouriteOrder?: Maybe<Scalars['Int']>;
}
/** Studio sort enums */
export const enum StudioSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Name = 'NAME',
NameDesc = 'NAME_DESC',
SearchMatch = 'SEARCH_MATCH',
Favourites = 'FAVOURITES',
FavouritesDesc = 'FAVOURITES_DESC'
}
/** User's studio statistics */
export interface StudioStats {
readonly __typename?: 'StudioStats';
readonly studio?: Maybe<Studio>;
readonly amount?: Maybe<Scalars['Int']>;
readonly meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the studio's works have been watched by the user */
readonly timeWatched?: Maybe<Scalars['Int']>;
}
/** Submission sort enums */
export const enum SubmissionSort {
Id = 'ID',
IdDesc = 'ID_DESC'
}
/** Submission status */
export const enum SubmissionStatus {
Pending = 'PENDING',
Rejected = 'REJECTED',
PartiallyAccepted = 'PARTIALLY_ACCEPTED',
Accepted = 'ACCEPTED'
}
/** User's tag statistics */
export interface TagStats {
readonly __typename?: 'TagStats';
readonly tag?: Maybe<MediaTag>;
readonly amount?: Maybe<Scalars['Int']>;
readonly meanScore?: Maybe<Scalars['Int']>;
/** The amount of time in minutes the tag has been watched by the user */
readonly timeWatched?: Maybe<Scalars['Int']>;
}
/** User text activity */
export interface TextActivity {
readonly __typename?: 'TextActivity';
/** The id of the activity */
readonly id: Scalars['Int'];
/** The user id of the activity's creator */
readonly userId?: Maybe<Scalars['Int']>;
/** The type of activity */
readonly type?: Maybe<ActivityType>;
/** The number of activity replies */
readonly replyCount: Scalars['Int'];
/** The status text (Markdown) */
readonly text?: Maybe<Scalars['String']>;
/** The url for the activity page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** If the activity is locked and can receive replies */
readonly isLocked?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the activity */
readonly isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the activity has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the activity */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** The time the activity was created at */
readonly createdAt: Scalars['Int'];
/** The user who created the activity */
readonly user?: Maybe<User>;
/** The written replies to the activity */
readonly replies?: Maybe<ReadonlyArray<Maybe<ActivityReply>>>;
/** The users who liked the activity */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
}
/** User text activity */
export interface TextActivityTextArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** Forum Thread */
export interface Thread {
readonly __typename?: 'Thread';
/** The id of the thread */
readonly id: Scalars['Int'];
/** The title of the thread */
readonly title?: Maybe<Scalars['String']>;
/** The text body of the thread (Markdown) */
readonly body?: Maybe<Scalars['String']>;
/** The id of the thread owner user */
readonly userId: Scalars['Int'];
/** The id of the user who most recently commented on the thread */
readonly replyUserId?: Maybe<Scalars['Int']>;
/** The id of the most recent comment on the thread */
readonly replyCommentId?: Maybe<Scalars['Int']>;
/** The number of comments on the thread */
readonly replyCount?: Maybe<Scalars['Int']>;
/** The number of times users have viewed the thread */
readonly viewCount?: Maybe<Scalars['Int']>;
/** If the thread is locked and can receive comments */
readonly isLocked?: Maybe<Scalars['Boolean']>;
/** If the thread is stickied and should be displayed at the top of the page */
readonly isSticky?: Maybe<Scalars['Boolean']>;
/** If the currently authenticated user is subscribed to the thread */
readonly isSubscribed?: Maybe<Scalars['Boolean']>;
/** The amount of likes the thread has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the thread */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** The time of the last reply */
readonly repliedAt?: Maybe<Scalars['Int']>;
/** The time of the thread creation */
readonly createdAt: Scalars['Int'];
/** The time of the thread last update */
readonly updatedAt: Scalars['Int'];
/** The owner of the thread */
readonly user?: Maybe<User>;
/** The user to last reply to the thread */
readonly replyUser?: Maybe<User>;
/** The users who liked the thread */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
/** The url for the thread page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The categories of the thread */
readonly categories?: Maybe<ReadonlyArray<Maybe<ThreadCategory>>>;
/** The media categories of the thread */
readonly mediaCategories?: Maybe<ReadonlyArray<Maybe<Media>>>;
}
/** Forum Thread */
export interface ThreadBodyArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** A forum thread category */
export interface ThreadCategory {
readonly __typename?: 'ThreadCategory';
/** The id of the category */
readonly id: Scalars['Int'];
/** The name of the category */
readonly name: Scalars['String'];
}
/** Forum Thread Comment */
export interface ThreadComment {
readonly __typename?: 'ThreadComment';
/** The id of the comment */
readonly id: Scalars['Int'];
/** The user id of the comment's owner */
readonly userId?: Maybe<Scalars['Int']>;
/** The id of thread the comment belongs to */
readonly threadId?: Maybe<Scalars['Int']>;
/** The text content of the comment (Markdown) */
readonly comment?: Maybe<Scalars['String']>;
/** The amount of likes the comment has */
readonly likeCount: Scalars['Int'];
/** If the currently authenticated user liked the comment */
readonly isLiked?: Maybe<Scalars['Boolean']>;
/** The url for the comment page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The time of the comments creation */
readonly createdAt: Scalars['Int'];
/** The time of the comments last update */
readonly updatedAt: Scalars['Int'];
/** The thread the comment belongs to */
readonly thread?: Maybe<Thread>;
/** The user who created the comment */
readonly user?: Maybe<User>;
/** The users who liked the comment */
readonly likes?: Maybe<ReadonlyArray<Maybe<User>>>;
/** The comment's child reply comments */
readonly childComments?: Maybe<Scalars['Json']>;
}
/** Forum Thread Comment */
export interface ThreadCommentCommentArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** Notification for when a thread comment is liked */
export interface ThreadCommentLikeNotification {
readonly __typename?: 'ThreadCommentLikeNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who liked to the activity */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the activity which was liked */
readonly commentId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
readonly thread?: Maybe<Thread>;
/** The thread comment that was liked */
readonly comment?: Maybe<ThreadComment>;
/** The user who liked the activity */
readonly user?: Maybe<User>;
}
/** Notification for when authenticated user is @ mentioned in a forum thread comment */
export interface ThreadCommentMentionNotification {
readonly __typename?: 'ThreadCommentMentionNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who mentioned the authenticated user */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the comment where mentioned */
readonly commentId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
readonly thread?: Maybe<Thread>;
/** The thread comment that included the @ mention */
readonly comment?: Maybe<ThreadComment>;
/** The user who mentioned the authenticated user */
readonly user?: Maybe<User>;
}
/** Notification for when a user replies to your forum thread comment */
export interface ThreadCommentReplyNotification {
readonly __typename?: 'ThreadCommentReplyNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who create the comment reply */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the reply comment */
readonly commentId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
readonly thread?: Maybe<Thread>;
/** The reply thread comment */
readonly comment?: Maybe<ThreadComment>;
/** The user who replied to the activity */
readonly user?: Maybe<User>;
}
/** Thread comments sort enums */
export const enum ThreadCommentSort {
Id = 'ID',
IdDesc = 'ID_DESC'
}
/** Notification for when a user replies to a subscribed forum thread */
export interface ThreadCommentSubscribedNotification {
readonly __typename?: 'ThreadCommentSubscribedNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who commented on the thread */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the new comment in the subscribed thread */
readonly commentId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
readonly thread?: Maybe<Thread>;
/** The reply thread comment */
readonly comment?: Maybe<ThreadComment>;
/** The user who replied to the subscribed thread */
readonly user?: Maybe<User>;
}
/** Notification for when a thread is liked */
export interface ThreadLikeNotification {
readonly __typename?: 'ThreadLikeNotification';
/** The id of the Notification */
readonly id: Scalars['Int'];
/** The id of the user who liked to the activity */
readonly userId: Scalars['Int'];
/** The type of notification */
readonly type?: Maybe<NotificationType>;
/** The id of the thread which was liked */
readonly threadId: Scalars['Int'];
/** The notification context text */
readonly context?: Maybe<Scalars['String']>;
/** The time the notification was created at */
readonly createdAt?: Maybe<Scalars['Int']>;
/** The thread that the relevant comment belongs to */
readonly thread?: Maybe<Thread>;
/** The liked thread comment */
readonly comment?: Maybe<ThreadComment>;
/** The user who liked the activity */
readonly user?: Maybe<User>;
}
/** Thread sort enums */
export const enum ThreadSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Title = 'TITLE',
TitleDesc = 'TITLE_DESC',
CreatedAt = 'CREATED_AT',
CreatedAtDesc = 'CREATED_AT_DESC',
UpdatedAt = 'UPDATED_AT',
UpdatedAtDesc = 'UPDATED_AT_DESC',
RepliedAt = 'REPLIED_AT',
RepliedAtDesc = 'REPLIED_AT_DESC',
ReplyCount = 'REPLY_COUNT',
ReplyCountDesc = 'REPLY_COUNT_DESC',
ViewCount = 'VIEW_COUNT',
ViewCountDesc = 'VIEW_COUNT_DESC',
IsSticky = 'IS_STICKY',
SearchMatch = 'SEARCH_MATCH'
}
/** A user */
export interface User {
readonly __typename?: 'User';
/** The id of the user */
readonly id: Scalars['Int'];
/** The name of the user */
readonly name: Scalars['String'];
/** The bio written by user (Markdown) */
readonly about?: Maybe<Scalars['String']>;
/** The user's avatar images */
readonly avatar?: Maybe<UserAvatar>;
/** The user's banner images */
readonly bannerImage?: Maybe<Scalars['String']>;
/** If the authenticated user if following this user */
readonly isFollowing?: Maybe<Scalars['Boolean']>;
/** If this user if following the authenticated user */
readonly isFollower?: Maybe<Scalars['Boolean']>;
/** If the user is blocked by the authenticated user */
readonly isBlocked?: Maybe<Scalars['Boolean']>;
readonly bans?: Maybe<Scalars['Json']>;
/** The user's general options */
readonly options?: Maybe<UserOptions>;
/** The user's media list options */
readonly mediaListOptions?: Maybe<MediaListOptions>;
/** The users favourites */
readonly favourites?: Maybe<Favourites>;
/** The users anime & manga list statistics */
readonly statistics?: Maybe<UserStatisticTypes>;
/** The number of unread notifications the user has */
readonly unreadNotificationCount?: Maybe<Scalars['Int']>;
/** The url for the user page on the AniList website */
readonly siteUrl?: Maybe<Scalars['String']>;
/** The donation tier of the user */
readonly donatorTier?: Maybe<Scalars['Int']>;
/** Custom donation badge text */
readonly donatorBadge?: Maybe<Scalars['String']>;
/** The user's moderator roles if they are a site moderator */
readonly moderatorRoles?: Maybe<ReadonlyArray<Maybe<ModRole>>>;
/** When the user's account was created. (Does not exist for accounts created before 2020) */
readonly createdAt?: Maybe<Scalars['Int']>;
/** When the user's data was last updated */
readonly updatedAt?: Maybe<Scalars['Int']>;
/**
* The user's statistics
* @deprecated Deprecated. Replaced with statistics field.
*/
readonly stats?: Maybe<UserStats>;
/**
* If the user is a moderator or data moderator
* @deprecated Deprecated. Replaced with moderatorRoles field.
*/
readonly moderatorStatus?: Maybe<Scalars['String']>;
/** The user's previously used names. */
readonly previousNames?: Maybe<ReadonlyArray<Maybe<UserPreviousName>>>;
}
/** A user */
export interface UserAboutArgs {
asHtml?: Maybe<Scalars['Boolean']>;
}
/** A user */
export interface UserFavouritesArgs {
page?: Maybe<Scalars['Int']>;
}
/** A user's activity history stats. */
export interface UserActivityHistory {
readonly __typename?: 'UserActivityHistory';
/** The day the activity took place (Unix timestamp) */
readonly date?: Maybe<Scalars['Int']>;
/** The amount of activity on the day */
readonly amount?: Maybe<Scalars['Int']>;
/** The level of activity represented on a 1-10 scale */
readonly level?: Maybe<Scalars['Int']>;
}
/** A user's avatars */
export interface UserAvatar {
readonly __typename?: 'UserAvatar';
/** The avatar of user at its largest size */
readonly large?: Maybe<Scalars['String']>;
/** The avatar of user at medium size */
readonly medium?: Maybe<Scalars['String']>;
}
export interface UserCountryStatistic {
readonly __typename?: 'UserCountryStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly country?: Maybe<Scalars['CountryCode']>;
}
export interface UserFormatStatistic {
readonly __typename?: 'UserFormatStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly format?: Maybe<MediaFormat>;
}
export interface UserGenreStatistic {
readonly __typename?: 'UserGenreStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly genre?: Maybe<Scalars['String']>;
}
export interface UserLengthStatistic {
readonly __typename?: 'UserLengthStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly length?: Maybe<Scalars['String']>;
}
/** User data for moderators */
export interface UserModData {
readonly __typename?: 'UserModData';
readonly alts?: Maybe<ReadonlyArray<Maybe<User>>>;
readonly bans?: Maybe<Scalars['Json']>;
readonly ip?: Maybe<Scalars['Json']>;
readonly counts?: Maybe<Scalars['Json']>;
readonly privacy?: Maybe<Scalars['Int']>;
readonly email?: Maybe<Scalars['String']>;
}
/** A user's general options */
export interface UserOptions {
readonly __typename?: 'UserOptions';
/** The language the user wants to see media titles in */
readonly titleLanguage?: Maybe<UserTitleLanguage>;
/** Whether the user has enabled viewing of 18+ content */
readonly displayAdultContent?: Maybe<Scalars['Boolean']>;
/** Whether the user receives notifications when a show they are watching aires */
readonly airingNotifications?: Maybe<Scalars['Boolean']>;
/** Profile highlight color (blue, purple, pink, orange, red, green, gray) */
readonly profileColor?: Maybe<Scalars['String']>;
/** Notification options */
readonly notificationOptions?: Maybe<ReadonlyArray<Maybe<NotificationOption>>>;
/** The user's timezone offset (Auth user only) */
readonly timezone?: Maybe<Scalars['String']>;
/** Minutes between activity for them to be merged together. 0 is Never, Above 2 weeks (20160 mins) is Always. */
readonly activityMergeTime?: Maybe<Scalars['Int']>;
/** The language the user wants to see staff and character names in */
readonly staffNameLanguage?: Maybe<UserStaffNameLanguage>;
}
/** A user's previous name */
export interface UserPreviousName {
readonly __typename?: 'UserPreviousName';
/** A previous name of the user. */
readonly name?: Maybe<Scalars['String']>;
/** When the user first changed from this name. */
readonly createdAt?: Maybe<Scalars['Int']>;
/** When the user most recently changed from this name. */
readonly updatedAt?: Maybe<Scalars['Int']>;
}
export interface UserReleaseYearStatistic {
readonly __typename?: 'UserReleaseYearStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly releaseYear?: Maybe<Scalars['Int']>;
}
export interface UserScoreStatistic {
readonly __typename?: 'UserScoreStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly score?: Maybe<Scalars['Int']>;
}
/** User sort enums */
export const enum UserSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Username = 'USERNAME',
UsernameDesc = 'USERNAME_DESC',
WatchedTime = 'WATCHED_TIME',
WatchedTimeDesc = 'WATCHED_TIME_DESC',
ChaptersRead = 'CHAPTERS_READ',
ChaptersReadDesc = 'CHAPTERS_READ_DESC',
SearchMatch = 'SEARCH_MATCH'
}
/** The language the user wants to see staff and character names in */
export const enum UserStaffNameLanguage {
/** The romanization of the staff or character's native name, with western name ordering */
RomajiWestern = 'ROMAJI_WESTERN',
/** The romanization of the staff or character's native name */
Romaji = 'ROMAJI',
/** The staff or character's name in their native language */
Native = 'NATIVE'
}
export interface UserStaffStatistic {
readonly __typename?: 'UserStaffStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly staff?: Maybe<Staff>;
}
export interface UserStartYearStatistic {
readonly __typename?: 'UserStartYearStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly startYear?: Maybe<Scalars['Int']>;
}
export interface UserStatisticTypes {
readonly __typename?: 'UserStatisticTypes';
readonly anime?: Maybe<UserStatistics>;
readonly manga?: Maybe<UserStatistics>;
}
export interface UserStatistics {
readonly __typename?: 'UserStatistics';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly standardDeviation: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly episodesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly volumesRead: Scalars['Int'];
readonly formats?: Maybe<ReadonlyArray<Maybe<UserFormatStatistic>>>;
readonly statuses?: Maybe<ReadonlyArray<Maybe<UserStatusStatistic>>>;
readonly scores?: Maybe<ReadonlyArray<Maybe<UserScoreStatistic>>>;
readonly lengths?: Maybe<ReadonlyArray<Maybe<UserLengthStatistic>>>;
readonly releaseYears?: Maybe<ReadonlyArray<Maybe<UserReleaseYearStatistic>>>;
readonly startYears?: Maybe<ReadonlyArray<Maybe<UserStartYearStatistic>>>;
readonly genres?: Maybe<ReadonlyArray<Maybe<UserGenreStatistic>>>;
readonly tags?: Maybe<ReadonlyArray<Maybe<UserTagStatistic>>>;
readonly countries?: Maybe<ReadonlyArray<Maybe<UserCountryStatistic>>>;
readonly voiceActors?: Maybe<ReadonlyArray<Maybe<UserVoiceActorStatistic>>>;
readonly staff?: Maybe<ReadonlyArray<Maybe<UserStaffStatistic>>>;
readonly studios?: Maybe<ReadonlyArray<Maybe<UserStudioStatistic>>>;
}
export interface UserStatisticsFormatsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsStatusesArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsScoresArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsLengthsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsReleaseYearsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsStartYearsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsGenresArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsTagsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsCountriesArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsVoiceActorsArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsStaffArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
export interface UserStatisticsStudiosArgs {
limit?: Maybe<Scalars['Int']>;
sort?: Maybe<ReadonlyArray<Maybe<UserStatisticsSort>>>;
}
/** User statistics sort enum */
export const enum UserStatisticsSort {
Id = 'ID',
IdDesc = 'ID_DESC',
Count = 'COUNT',
CountDesc = 'COUNT_DESC',
Progress = 'PROGRESS',
ProgressDesc = 'PROGRESS_DESC',
MeanScore = 'MEAN_SCORE',
MeanScoreDesc = 'MEAN_SCORE_DESC'
}
/** A user's statistics */
export interface UserStats {
readonly __typename?: 'UserStats';
/** The amount of anime the user has watched in minutes */
readonly watchedTime?: Maybe<Scalars['Int']>;
/** The amount of manga chapters the user has read */
readonly chaptersRead?: Maybe<Scalars['Int']>;
readonly activityHistory?: Maybe<ReadonlyArray<Maybe<UserActivityHistory>>>;
readonly animeStatusDistribution?: Maybe<ReadonlyArray<Maybe<StatusDistribution>>>;
readonly mangaStatusDistribution?: Maybe<ReadonlyArray<Maybe<StatusDistribution>>>;
readonly animeScoreDistribution?: Maybe<ReadonlyArray<Maybe<ScoreDistribution>>>;
readonly mangaScoreDistribution?: Maybe<ReadonlyArray<Maybe<ScoreDistribution>>>;
readonly animeListScores?: Maybe<ListScoreStats>;
readonly mangaListScores?: Maybe<ListScoreStats>;
readonly favouredGenresOverview?: Maybe<ReadonlyArray<Maybe<GenreStats>>>;
readonly favouredGenres?: Maybe<ReadonlyArray<Maybe<GenreStats>>>;
readonly favouredTags?: Maybe<ReadonlyArray<Maybe<TagStats>>>;
readonly favouredActors?: Maybe<ReadonlyArray<Maybe<StaffStats>>>;
readonly favouredStaff?: Maybe<ReadonlyArray<Maybe<StaffStats>>>;
readonly favouredStudios?: Maybe<ReadonlyArray<Maybe<StudioStats>>>;
readonly favouredYears?: Maybe<ReadonlyArray<Maybe<YearStats>>>;
readonly favouredFormats?: Maybe<ReadonlyArray<Maybe<FormatStats>>>;
}
export interface UserStatusStatistic {
readonly __typename?: 'UserStatusStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly status?: Maybe<MediaListStatus>;
}
export interface UserStudioStatistic {
readonly __typename?: 'UserStudioStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly studio?: Maybe<Studio>;
}
export interface UserTagStatistic {
readonly __typename?: 'UserTagStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly tag?: Maybe<MediaTag>;
}
/** The language the user wants to see media titles in */
export const enum UserTitleLanguage {
/** The romanization of the native language title */
Romaji = 'ROMAJI',
/** The official english title */
English = 'ENGLISH',
/** Official title in it's native language */
Native = 'NATIVE',
/** The romanization of the native language title, stylised by media creator */
RomajiStylised = 'ROMAJI_STYLISED',
/** The official english title, stylised by media creator */
EnglishStylised = 'ENGLISH_STYLISED',
/** Official title in it's native language, stylised by media creator */
NativeStylised = 'NATIVE_STYLISED'
}
export interface UserVoiceActorStatistic {
readonly __typename?: 'UserVoiceActorStatistic';
readonly count: Scalars['Int'];
readonly meanScore: Scalars['Float'];
readonly minutesWatched: Scalars['Int'];
readonly chaptersRead: Scalars['Int'];
readonly mediaIds: ReadonlyArray<Maybe<Scalars['Int']>>;
readonly voiceActor?: Maybe<Staff>;
readonly characterIds: ReadonlyArray<Maybe<Scalars['Int']>>;
}
/** User's year statistics */
export interface YearStats {
readonly __typename?: 'YearStats';
readonly year?: Maybe<Scalars['Int']>;
readonly amount?: Maybe<Scalars['Int']>;
readonly meanScore?: Maybe<Scalars['Int']>;
}
export type ResolverTypeWrapper<T> = Promise<T> | T;
export interface ResolverWithResolve<TResult, TParent, TContext, TArgs> {
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
}
export interface LegacyStitchingResolver<TResult, TParent, TContext, TArgs> {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
}
export interface NewStitchingResolver<TResult, TParent, TContext, TArgs> {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
}
export type StitchingResolver<TResult, TParent, TContext, TArgs> =
| LegacyStitchingResolver<TResult, TParent, TContext, TArgs>
| NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = NonNullObject, TContext = NonNullObject, TArgs = NonNullObject> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| ResolverWithResolve<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<TResult, TKey extends string, TParent = NonNullObject, TContext = NonNullObject, TArgs = NonNullObject> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = NonNullObject, TContext = NonNullObject> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = NonNullObject, TContext = NonNullObject> = (
obj: T,
context: TContext,
info: GraphQLResolveInfo
) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<TResult = NonNullObject, TParent = NonNullObject, TContext = NonNullObject, TArgs = NonNullObject> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export interface ResolversTypes {
ActivityLikeNotification: ResolverTypeWrapper<Omit<ActivityLikeNotification, 'activity'> & { activity?: Maybe<ResolversTypes['ActivityUnion']> }>;
Int: ResolverTypeWrapper<Scalars['Int']>;
String: ResolverTypeWrapper<Scalars['String']>;
ActivityMentionNotification: ResolverTypeWrapper<
Omit<ActivityMentionNotification, 'activity'> & { activity?: Maybe<ResolversTypes['ActivityUnion']> }
>;
ActivityMessageNotification: ResolverTypeWrapper<ActivityMessageNotification>;
ActivityReply: ResolverTypeWrapper<ActivityReply>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
ActivityReplyLikeNotification: ResolverTypeWrapper<
Omit<ActivityReplyLikeNotification, 'activity'> & { activity?: Maybe<ResolversTypes['ActivityUnion']> }
>;
ActivityReplyNotification: ResolverTypeWrapper<
Omit<ActivityReplyNotification, 'activity'> & { activity?: Maybe<ResolversTypes['ActivityUnion']> }
>;
ActivityReplySubscribedNotification: ResolverTypeWrapper<
Omit<ActivityReplySubscribedNotification, 'activity'> & { activity?: Maybe<ResolversTypes['ActivityUnion']> }
>;
ActivitySort: ActivitySort;
ActivityType: ActivityType;
ActivityUnion: ResolversTypes['TextActivity'] | ResolversTypes['ListActivity'] | ResolversTypes['MessageActivity'];
AiringNotification: ResolverTypeWrapper<AiringNotification>;
AiringProgression: ResolverTypeWrapper<AiringProgression>;
Float: ResolverTypeWrapper<Scalars['Float']>;
AiringSchedule: ResolverTypeWrapper<AiringSchedule>;
AiringScheduleConnection: ResolverTypeWrapper<AiringScheduleConnection>;
AiringScheduleEdge: ResolverTypeWrapper<AiringScheduleEdge>;
AiringScheduleInput: AiringScheduleInput;
AiringSort: AiringSort;
AniChartHighlightInput: AniChartHighlightInput;
AniChartUser: ResolverTypeWrapper<AniChartUser>;
Character: ResolverTypeWrapper<Character>;
CharacterConnection: ResolverTypeWrapper<CharacterConnection>;
CharacterEdge: ResolverTypeWrapper<CharacterEdge>;
CharacterImage: ResolverTypeWrapper<CharacterImage>;
CharacterName: ResolverTypeWrapper<CharacterName>;
CharacterNameInput: CharacterNameInput;
CharacterRole: CharacterRole;
CharacterSort: CharacterSort;
CharacterSubmission: ResolverTypeWrapper<CharacterSubmission>;
CharacterSubmissionConnection: ResolverTypeWrapper<CharacterSubmissionConnection>;
CharacterSubmissionEdge: ResolverTypeWrapper<CharacterSubmissionEdge>;
CountryCode: ResolverTypeWrapper<Scalars['CountryCode']>;
Deleted: ResolverTypeWrapper<Deleted>;
Favourites: ResolverTypeWrapper<Favourites>;
FollowingNotification: ResolverTypeWrapper<FollowingNotification>;
FormatStats: ResolverTypeWrapper<FormatStats>;
FuzzyDate: ResolverTypeWrapper<FuzzyDate>;
FuzzyDateInput: FuzzyDateInput;
FuzzyDateInt: ResolverTypeWrapper<Scalars['FuzzyDateInt']>;
GenreStats: ResolverTypeWrapper<GenreStats>;
InternalPage: ResolverTypeWrapper<
Omit<InternalPage, 'notifications' | 'activities'> & {
notifications?: Maybe<ReadonlyArray<Maybe<ResolversTypes['NotificationUnion']>>>;
activities?: Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityUnion']>>>;
}
>;
Json: ResolverTypeWrapper<Scalars['Json']>;
LikeableType: LikeableType;
LikeableUnion:
| ResolversTypes['ListActivity']
| ResolversTypes['TextActivity']
| ResolversTypes['MessageActivity']
| ResolversTypes['ActivityReply']
| ResolversTypes['Thread']
| ResolversTypes['ThreadComment'];
ListActivity: ResolverTypeWrapper<ListActivity>;
ListScoreStats: ResolverTypeWrapper<ListScoreStats>;
Media: ResolverTypeWrapper<Media>;
MediaCharacter: ResolverTypeWrapper<MediaCharacter>;
MediaConnection: ResolverTypeWrapper<MediaConnection>;
MediaCoverImage: ResolverTypeWrapper<MediaCoverImage>;
MediaEdge: ResolverTypeWrapper<MediaEdge>;
MediaExternalLink: ResolverTypeWrapper<MediaExternalLink>;
MediaExternalLinkInput: MediaExternalLinkInput;
MediaFormat: MediaFormat;
MediaList: ResolverTypeWrapper<MediaList>;
MediaListCollection: ResolverTypeWrapper<MediaListCollection>;
MediaListGroup: ResolverTypeWrapper<MediaListGroup>;
MediaListOptions: ResolverTypeWrapper<MediaListOptions>;
MediaListOptionsInput: MediaListOptionsInput;
MediaListSort: MediaListSort;
MediaListStatus: MediaListStatus;
MediaListTypeOptions: ResolverTypeWrapper<MediaListTypeOptions>;
MediaRank: ResolverTypeWrapper<MediaRank>;
MediaRankType: MediaRankType;
MediaRelation: MediaRelation;
MediaSeason: MediaSeason;
MediaSort: MediaSort;
MediaSource: MediaSource;
MediaStats: ResolverTypeWrapper<MediaStats>;
MediaStatus: MediaStatus;
MediaStreamingEpisode: ResolverTypeWrapper<MediaStreamingEpisode>;
MediaSubmission: ResolverTypeWrapper<MediaSubmission>;
MediaSubmissionComparison: ResolverTypeWrapper<MediaSubmissionComparison>;
MediaSubmissionEdge: ResolverTypeWrapper<MediaSubmissionEdge>;
MediaTag: ResolverTypeWrapper<MediaTag>;
MediaTitle: ResolverTypeWrapper<MediaTitle>;
MediaTitleInput: MediaTitleInput;
MediaTrailer: ResolverTypeWrapper<MediaTrailer>;
MediaTrend: ResolverTypeWrapper<MediaTrend>;
MediaTrendConnection: ResolverTypeWrapper<MediaTrendConnection>;
MediaTrendEdge: ResolverTypeWrapper<MediaTrendEdge>;
MediaTrendSort: MediaTrendSort;
MediaType: MediaType;
MessageActivity: ResolverTypeWrapper<MessageActivity>;
ModAction: ResolverTypeWrapper<ModAction>;
ModActionType: ModActionType;
ModRole: ModRole;
Mutation: ResolverTypeWrapper<NonNullObject>;
NotificationOption: ResolverTypeWrapper<NotificationOption>;
NotificationOptionInput: NotificationOptionInput;
NotificationType: NotificationType;
NotificationUnion:
| ResolversTypes['AiringNotification']
| ResolversTypes['FollowingNotification']
| ResolversTypes['ActivityMessageNotification']
| ResolversTypes['ActivityMentionNotification']
| ResolversTypes['ActivityReplyNotification']
| ResolversTypes['ActivityReplySubscribedNotification']
| ResolversTypes['ActivityLikeNotification']
| ResolversTypes['ActivityReplyLikeNotification']
| ResolversTypes['ThreadCommentMentionNotification']
| ResolversTypes['ThreadCommentReplyNotification']
| ResolversTypes['ThreadCommentSubscribedNotification']
| ResolversTypes['ThreadCommentLikeNotification']
| ResolversTypes['ThreadLikeNotification']
| ResolversTypes['RelatedMediaAdditionNotification'];
Page: ResolverTypeWrapper<
Omit<Page, 'notifications' | 'activities'> & {
notifications?: Maybe<ReadonlyArray<Maybe<ResolversTypes['NotificationUnion']>>>;
activities?: Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityUnion']>>>;
}
>;
PageInfo: ResolverTypeWrapper<PageInfo>;
ParsedMarkdown: ResolverTypeWrapper<ParsedMarkdown>;
Query: ResolverTypeWrapper<NonNullObject>;
Recommendation: ResolverTypeWrapper<Recommendation>;
RecommendationConnection: ResolverTypeWrapper<RecommendationConnection>;
RecommendationEdge: ResolverTypeWrapper<RecommendationEdge>;
RecommendationRating: RecommendationRating;
RecommendationSort: RecommendationSort;
RelatedMediaAdditionNotification: ResolverTypeWrapper<RelatedMediaAdditionNotification>;
Report: ResolverTypeWrapper<Report>;
Review: ResolverTypeWrapper<Review>;
ReviewConnection: ResolverTypeWrapper<ReviewConnection>;
ReviewEdge: ResolverTypeWrapper<ReviewEdge>;
ReviewRating: ReviewRating;
ReviewSort: ReviewSort;
RevisionHistory: ResolverTypeWrapper<RevisionHistory>;
RevisionHistoryAction: RevisionHistoryAction;
ScoreDistribution: ResolverTypeWrapper<ScoreDistribution>;
ScoreFormat: ScoreFormat;
SiteStatistics: ResolverTypeWrapper<SiteStatistics>;
SiteTrend: ResolverTypeWrapper<SiteTrend>;
SiteTrendConnection: ResolverTypeWrapper<SiteTrendConnection>;
SiteTrendEdge: ResolverTypeWrapper<SiteTrendEdge>;
SiteTrendSort: SiteTrendSort;
Staff: ResolverTypeWrapper<Staff>;
StaffConnection: ResolverTypeWrapper<StaffConnection>;
StaffEdge: ResolverTypeWrapper<StaffEdge>;
StaffImage: ResolverTypeWrapper<StaffImage>;
StaffLanguage: StaffLanguage;
StaffName: ResolverTypeWrapper<StaffName>;
StaffNameInput: StaffNameInput;
StaffRoleType: ResolverTypeWrapper<StaffRoleType>;
StaffSort: StaffSort;
StaffStats: ResolverTypeWrapper<StaffStats>;
StaffSubmission: ResolverTypeWrapper<StaffSubmission>;
StatusDistribution: ResolverTypeWrapper<StatusDistribution>;
Studio: ResolverTypeWrapper<Studio>;
StudioConnection: ResolverTypeWrapper<StudioConnection>;
StudioEdge: ResolverTypeWrapper<StudioEdge>;
StudioSort: StudioSort;
StudioStats: ResolverTypeWrapper<StudioStats>;
SubmissionSort: SubmissionSort;
SubmissionStatus: SubmissionStatus;
TagStats: ResolverTypeWrapper<TagStats>;
TextActivity: ResolverTypeWrapper<TextActivity>;
Thread: ResolverTypeWrapper<Thread>;
ThreadCategory: ResolverTypeWrapper<ThreadCategory>;
ThreadComment: ResolverTypeWrapper<ThreadComment>;
ThreadCommentLikeNotification: ResolverTypeWrapper<ThreadCommentLikeNotification>;
ThreadCommentMentionNotification: ResolverTypeWrapper<ThreadCommentMentionNotification>;
ThreadCommentReplyNotification: ResolverTypeWrapper<ThreadCommentReplyNotification>;
ThreadCommentSort: ThreadCommentSort;
ThreadCommentSubscribedNotification: ResolverTypeWrapper<ThreadCommentSubscribedNotification>;
ThreadLikeNotification: ResolverTypeWrapper<ThreadLikeNotification>;
ThreadSort: ThreadSort;
User: ResolverTypeWrapper<User>;
UserActivityHistory: ResolverTypeWrapper<UserActivityHistory>;
UserAvatar: ResolverTypeWrapper<UserAvatar>;
UserCountryStatistic: ResolverTypeWrapper<UserCountryStatistic>;
UserFormatStatistic: ResolverTypeWrapper<UserFormatStatistic>;
UserGenreStatistic: ResolverTypeWrapper<UserGenreStatistic>;
UserLengthStatistic: ResolverTypeWrapper<UserLengthStatistic>;
UserModData: ResolverTypeWrapper<UserModData>;
UserOptions: ResolverTypeWrapper<UserOptions>;
UserPreviousName: ResolverTypeWrapper<UserPreviousName>;
UserReleaseYearStatistic: ResolverTypeWrapper<UserReleaseYearStatistic>;
UserScoreStatistic: ResolverTypeWrapper<UserScoreStatistic>;
UserSort: UserSort;
UserStaffNameLanguage: UserStaffNameLanguage;
UserStaffStatistic: ResolverTypeWrapper<UserStaffStatistic>;
UserStartYearStatistic: ResolverTypeWrapper<UserStartYearStatistic>;
UserStatisticTypes: ResolverTypeWrapper<UserStatisticTypes>;
UserStatistics: ResolverTypeWrapper<UserStatistics>;
UserStatisticsSort: UserStatisticsSort;
UserStats: ResolverTypeWrapper<UserStats>;
UserStatusStatistic: ResolverTypeWrapper<UserStatusStatistic>;
UserStudioStatistic: ResolverTypeWrapper<UserStudioStatistic>;
UserTagStatistic: ResolverTypeWrapper<UserTagStatistic>;
UserTitleLanguage: UserTitleLanguage;
UserVoiceActorStatistic: ResolverTypeWrapper<UserVoiceActorStatistic>;
YearStats: ResolverTypeWrapper<YearStats>;
}
/** Mapping between all available schema types and the resolvers parents */
export interface ResolversParentTypes {
ActivityLikeNotification: Omit<ActivityLikeNotification, 'activity'> & { activity?: Maybe<ResolversParentTypes['ActivityUnion']> };
Int: Scalars['Int'];
String: Scalars['String'];
ActivityMentionNotification: Omit<ActivityMentionNotification, 'activity'> & { activity?: Maybe<ResolversParentTypes['ActivityUnion']> };
ActivityMessageNotification: ActivityMessageNotification;
ActivityReply: ActivityReply;
Boolean: Scalars['Boolean'];
ActivityReplyLikeNotification: Omit<ActivityReplyLikeNotification, 'activity'> & { activity?: Maybe<ResolversParentTypes['ActivityUnion']> };
ActivityReplyNotification: Omit<ActivityReplyNotification, 'activity'> & { activity?: Maybe<ResolversParentTypes['ActivityUnion']> };
ActivityReplySubscribedNotification: Omit<ActivityReplySubscribedNotification, 'activity'> & {
activity?: Maybe<ResolversParentTypes['ActivityUnion']>;
};
ActivityUnion: ResolversParentTypes['TextActivity'] | ResolversParentTypes['ListActivity'] | ResolversParentTypes['MessageActivity'];
AiringNotification: AiringNotification;
AiringProgression: AiringProgression;
Float: Scalars['Float'];
AiringSchedule: AiringSchedule;
AiringScheduleConnection: AiringScheduleConnection;
AiringScheduleEdge: AiringScheduleEdge;
AiringScheduleInput: AiringScheduleInput;
AniChartHighlightInput: AniChartHighlightInput;
AniChartUser: AniChartUser;
Character: Character;
CharacterConnection: CharacterConnection;
CharacterEdge: CharacterEdge;
CharacterImage: CharacterImage;
CharacterName: CharacterName;
CharacterNameInput: CharacterNameInput;
CharacterSubmission: CharacterSubmission;
CharacterSubmissionConnection: CharacterSubmissionConnection;
CharacterSubmissionEdge: CharacterSubmissionEdge;
CountryCode: Scalars['CountryCode'];
Deleted: Deleted;
Favourites: Favourites;
FollowingNotification: FollowingNotification;
FormatStats: FormatStats;
FuzzyDate: FuzzyDate;
FuzzyDateInput: FuzzyDateInput;
FuzzyDateInt: Scalars['FuzzyDateInt'];
GenreStats: GenreStats;
InternalPage: Omit<InternalPage, 'notifications' | 'activities'> & {
notifications?: Maybe<ReadonlyArray<Maybe<ResolversParentTypes['NotificationUnion']>>>;
activities?: Maybe<ReadonlyArray<Maybe<ResolversParentTypes['ActivityUnion']>>>;
};
Json: Scalars['Json'];
LikeableUnion:
| ResolversParentTypes['ListActivity']
| ResolversParentTypes['TextActivity']
| ResolversParentTypes['MessageActivity']
| ResolversParentTypes['ActivityReply']
| ResolversParentTypes['Thread']
| ResolversParentTypes['ThreadComment'];
ListActivity: ListActivity;
ListScoreStats: ListScoreStats;
Media: Media;
MediaCharacter: MediaCharacter;
MediaConnection: MediaConnection;
MediaCoverImage: MediaCoverImage;
MediaEdge: MediaEdge;
MediaExternalLink: MediaExternalLink;
MediaExternalLinkInput: MediaExternalLinkInput;
MediaList: MediaList;
MediaListCollection: MediaListCollection;
MediaListGroup: MediaListGroup;
MediaListOptions: MediaListOptions;
MediaListOptionsInput: MediaListOptionsInput;
MediaListTypeOptions: MediaListTypeOptions;
MediaRank: MediaRank;
MediaStats: MediaStats;
MediaStreamingEpisode: MediaStreamingEpisode;
MediaSubmission: MediaSubmission;
MediaSubmissionComparison: MediaSubmissionComparison;
MediaSubmissionEdge: MediaSubmissionEdge;
MediaTag: MediaTag;
MediaTitle: MediaTitle;
MediaTitleInput: MediaTitleInput;
MediaTrailer: MediaTrailer;
MediaTrend: MediaTrend;
MediaTrendConnection: MediaTrendConnection;
MediaTrendEdge: MediaTrendEdge;
MessageActivity: MessageActivity;
ModAction: ModAction;
Mutation: NonNullObject;
NotificationOption: NotificationOption;
NotificationOptionInput: NotificationOptionInput;
NotificationUnion:
| ResolversParentTypes['AiringNotification']
| ResolversParentTypes['FollowingNotification']
| ResolversParentTypes['ActivityMessageNotification']
| ResolversParentTypes['ActivityMentionNotification']
| ResolversParentTypes['ActivityReplyNotification']
| ResolversParentTypes['ActivityReplySubscribedNotification']
| ResolversParentTypes['ActivityLikeNotification']
| ResolversParentTypes['ActivityReplyLikeNotification']
| ResolversParentTypes['ThreadCommentMentionNotification']
| ResolversParentTypes['ThreadCommentReplyNotification']
| ResolversParentTypes['ThreadCommentSubscribedNotification']
| ResolversParentTypes['ThreadCommentLikeNotification']
| ResolversParentTypes['ThreadLikeNotification']
| ResolversParentTypes['RelatedMediaAdditionNotification'];
Page: Omit<Page, 'notifications' | 'activities'> & {
notifications?: Maybe<ReadonlyArray<Maybe<ResolversParentTypes['NotificationUnion']>>>;
activities?: Maybe<ReadonlyArray<Maybe<ResolversParentTypes['ActivityUnion']>>>;
};
PageInfo: PageInfo;
ParsedMarkdown: ParsedMarkdown;
Query: NonNullObject;
Recommendation: Recommendation;
RecommendationConnection: RecommendationConnection;
RecommendationEdge: RecommendationEdge;
RelatedMediaAdditionNotification: RelatedMediaAdditionNotification;
Report: Report;
Review: Review;
ReviewConnection: ReviewConnection;
ReviewEdge: ReviewEdge;
RevisionHistory: RevisionHistory;
ScoreDistribution: ScoreDistribution;
SiteStatistics: SiteStatistics;
SiteTrend: SiteTrend;
SiteTrendConnection: SiteTrendConnection;
SiteTrendEdge: SiteTrendEdge;
Staff: Staff;
StaffConnection: StaffConnection;
StaffEdge: StaffEdge;
StaffImage: StaffImage;
StaffName: StaffName;
StaffNameInput: StaffNameInput;
StaffRoleType: StaffRoleType;
StaffStats: StaffStats;
StaffSubmission: StaffSubmission;
StatusDistribution: StatusDistribution;
Studio: Studio;
StudioConnection: StudioConnection;
StudioEdge: StudioEdge;
StudioStats: StudioStats;
TagStats: TagStats;
TextActivity: TextActivity;
Thread: Thread;
ThreadCategory: ThreadCategory;
ThreadComment: ThreadComment;
ThreadCommentLikeNotification: ThreadCommentLikeNotification;
ThreadCommentMentionNotification: ThreadCommentMentionNotification;
ThreadCommentReplyNotification: ThreadCommentReplyNotification;
ThreadCommentSubscribedNotification: ThreadCommentSubscribedNotification;
ThreadLikeNotification: ThreadLikeNotification;
User: User;
UserActivityHistory: UserActivityHistory;
UserAvatar: UserAvatar;
UserCountryStatistic: UserCountryStatistic;
UserFormatStatistic: UserFormatStatistic;
UserGenreStatistic: UserGenreStatistic;
UserLengthStatistic: UserLengthStatistic;
UserModData: UserModData;
UserOptions: UserOptions;
UserPreviousName: UserPreviousName;
UserReleaseYearStatistic: UserReleaseYearStatistic;
UserScoreStatistic: UserScoreStatistic;
UserStaffStatistic: UserStaffStatistic;
UserStartYearStatistic: UserStartYearStatistic;
UserStatisticTypes: UserStatisticTypes;
UserStatistics: UserStatistics;
UserStats: UserStats;
UserStatusStatistic: UserStatusStatistic;
UserStudioStatistic: UserStudioStatistic;
UserTagStatistic: UserTagStatistic;
UserVoiceActorStatistic: UserVoiceActorStatistic;
YearStats: YearStats;
}
export interface ActivityLikeNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityLikeNotification'] = ResolversParentTypes['ActivityLikeNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityMentionNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityMentionNotification'] = ResolversParentTypes['ActivityMentionNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityMessageNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityMessageNotification'] = ResolversParentTypes['ActivityMessageNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
message?: Resolver<Maybe<ResolversTypes['MessageActivity']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityReplyResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityReply'] = ResolversParentTypes['ActivityReply']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activityId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<ActivityReplyTextArgs, never>>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityReplyLikeNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityReplyLikeNotification'] = ResolversParentTypes['ActivityReplyLikeNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityReplyNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityReplyNotification'] = ResolversParentTypes['ActivityReplyNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityReplySubscribedNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityReplySubscribedNotification'] = ResolversParentTypes['ActivityReplySubscribedNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
activityId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ActivityUnionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ActivityUnion'] = ResolversParentTypes['ActivityUnion']
> {
__resolveType: TypeResolveFn<'TextActivity' | 'ListActivity' | 'MessageActivity', ParentType, ContextType>;
}
export interface AiringNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AiringNotification'] = ResolversParentTypes['AiringNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
animeId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
episode?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
contexts?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface AiringProgressionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AiringProgression'] = ResolversParentTypes['AiringProgression']
> {
episode?: Resolver<Maybe<ResolversTypes['Float']>, ParentType, ContextType>;
score?: Resolver<Maybe<ResolversTypes['Float']>, ParentType, ContextType>;
watching?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface AiringScheduleResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AiringSchedule'] = ResolversParentTypes['AiringSchedule']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
airingAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
timeUntilAiring?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
episode?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface AiringScheduleConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AiringScheduleConnection'] = ResolversParentTypes['AiringScheduleConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['AiringScheduleEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['AiringSchedule']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface AiringScheduleEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AiringScheduleEdge'] = ResolversParentTypes['AiringScheduleEdge']
> {
node?: Resolver<Maybe<ResolversTypes['AiringSchedule']>, ParentType, ContextType>;
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface AniChartUserResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['AniChartUser'] = ResolversParentTypes['AniChartUser']
> {
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
settings?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
highlights?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterResolvers<ContextType = any, ParentType extends ResolversParentTypes['Character'] = ResolversParentTypes['Character']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['CharacterName']>, ParentType, ContextType>;
image?: Resolver<Maybe<ResolversTypes['CharacterImage']>, ParentType, ContextType>;
description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<CharacterDescriptionArgs, never>>;
gender?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dateOfBirth?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
age?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
bloodType?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isFavourite?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
isFavouriteBlocked?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<CharacterMediaArgs, never>>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
favourites?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
modNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterConnection'] = ResolversParentTypes['CharacterConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['CharacterEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Character']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterEdge'] = ResolversParentTypes['CharacterEdge']
> {
node?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
role?: Resolver<Maybe<ResolversTypes['CharacterRole']>, ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
voiceActors?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>,
ParentType,
ContextType,
RequireFields<CharacterEdgeVoiceActorsArgs, never>
>;
voiceActorRoles?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffRoleType']>>>,
ParentType,
ContextType,
RequireFields<CharacterEdgeVoiceActorRolesArgs, never>
>;
media?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Media']>>>, ParentType, ContextType>;
favouriteOrder?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterImageResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterImage'] = ResolversParentTypes['CharacterImage']
> {
large?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
medium?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterNameResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterName'] = ResolversParentTypes['CharacterName']
> {
first?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
middle?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
last?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
full?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
native?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
alternative?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
alternativeSpoiler?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
userPreferred?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterSubmissionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterSubmission'] = ResolversParentTypes['CharacterSubmission']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
character?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
submission?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
submitter?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['SubmissionStatus']>, ParentType, ContextType>;
notes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
source?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterSubmissionConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterSubmissionConnection'] = ResolversParentTypes['CharacterSubmissionConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['CharacterSubmissionEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['CharacterSubmission']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CharacterSubmissionEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['CharacterSubmissionEdge'] = ResolversParentTypes['CharacterSubmissionEdge']
> {
node?: Resolver<Maybe<ResolversTypes['CharacterSubmission']>, ParentType, ContextType>;
role?: Resolver<Maybe<ResolversTypes['CharacterRole']>, ParentType, ContextType>;
voiceActors?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>, ParentType, ContextType>;
submittedVoiceActors?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffSubmission']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface CountryCodeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['CountryCode'], any> {
name: 'CountryCode';
}
export interface DeletedResolvers<ContextType = any, ParentType extends ResolversParentTypes['Deleted'] = ResolversParentTypes['Deleted']> {
deleted?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface FavouritesResolvers<ContextType = any, ParentType extends ResolversParentTypes['Favourites'] = ResolversParentTypes['Favourites']> {
anime?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<FavouritesAnimeArgs, never>>;
manga?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<FavouritesMangaArgs, never>>;
characters?: Resolver<Maybe<ResolversTypes['CharacterConnection']>, ParentType, ContextType, RequireFields<FavouritesCharactersArgs, never>>;
staff?: Resolver<Maybe<ResolversTypes['StaffConnection']>, ParentType, ContextType, RequireFields<FavouritesStaffArgs, never>>;
studios?: Resolver<Maybe<ResolversTypes['StudioConnection']>, ParentType, ContextType, RequireFields<FavouritesStudiosArgs, never>>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface FollowingNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['FollowingNotification'] = ResolversParentTypes['FollowingNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface FormatStatsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['FormatStats'] = ResolversParentTypes['FormatStats']
> {
format?: Resolver<Maybe<ResolversTypes['MediaFormat']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface FuzzyDateResolvers<ContextType = any, ParentType extends ResolversParentTypes['FuzzyDate'] = ResolversParentTypes['FuzzyDate']> {
year?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
month?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
day?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface FuzzyDateIntScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['FuzzyDateInt'], any> {
name: 'FuzzyDateInt';
}
export interface GenreStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['GenreStats'] = ResolversParentTypes['GenreStats']> {
genre?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
timeWatched?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface InternalPageResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['InternalPage'] = ResolversParentTypes['InternalPage']
> {
mediaSubmissions?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaSubmission']>>>,
ParentType,
ContextType,
RequireFields<InternalPageMediaSubmissionsArgs, never>
>;
characterSubmissions?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['CharacterSubmission']>>>,
ParentType,
ContextType,
RequireFields<InternalPageCharacterSubmissionsArgs, never>
>;
staffSubmissions?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffSubmission']>>>,
ParentType,
ContextType,
RequireFields<InternalPageStaffSubmissionsArgs, never>
>;
revisionHistory?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['RevisionHistory']>>>,
ParentType,
ContextType,
RequireFields<InternalPageRevisionHistoryArgs, never>
>;
reports?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Report']>>>, ParentType, ContextType, RequireFields<InternalPageReportsArgs, never>>;
modActions?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ModAction']>>>,
ParentType,
ContextType,
RequireFields<InternalPageModActionsArgs, never>
>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
users?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<InternalPageUsersArgs, never>>;
media?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Media']>>>, ParentType, ContextType, RequireFields<InternalPageMediaArgs, never>>;
characters?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Character']>>>,
ParentType,
ContextType,
RequireFields<InternalPageCharactersArgs, never>
>;
staff?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>, ParentType, ContextType, RequireFields<InternalPageStaffArgs, never>>;
studios?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Studio']>>>, ParentType, ContextType, RequireFields<InternalPageStudiosArgs, never>>;
mediaList?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>,
ParentType,
ContextType,
RequireFields<InternalPageMediaListArgs, never>
>;
airingSchedules?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['AiringSchedule']>>>,
ParentType,
ContextType,
RequireFields<InternalPageAiringSchedulesArgs, never>
>;
mediaTrends?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTrend']>>>,
ParentType,
ContextType,
RequireFields<InternalPageMediaTrendsArgs, never>
>;
notifications?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['NotificationUnion']>>>,
ParentType,
ContextType,
RequireFields<InternalPageNotificationsArgs, never>
>;
followers?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>,
ParentType,
ContextType,
RequireFields<InternalPageFollowersArgs, 'userId'>
>;
following?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>,
ParentType,
ContextType,
RequireFields<InternalPageFollowingArgs, 'userId'>
>;
activities?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityUnion']>>>,
ParentType,
ContextType,
RequireFields<InternalPageActivitiesArgs, never>
>;
activityReplies?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityReply']>>>,
ParentType,
ContextType,
RequireFields<InternalPageActivityRepliesArgs, never>
>;
threads?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Thread']>>>, ParentType, ContextType, RequireFields<InternalPageThreadsArgs, never>>;
threadComments?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ThreadComment']>>>,
ParentType,
ContextType,
RequireFields<InternalPageThreadCommentsArgs, never>
>;
reviews?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Review']>>>, ParentType, ContextType, RequireFields<InternalPageReviewsArgs, never>>;
recommendations?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Recommendation']>>>,
ParentType,
ContextType,
RequireFields<InternalPageRecommendationsArgs, never>
>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<InternalPageLikesArgs, never>>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface JsonScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Json'], any> {
name: 'Json';
}
export interface LikeableUnionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['LikeableUnion'] = ResolversParentTypes['LikeableUnion']
> {
__resolveType: TypeResolveFn<
'ListActivity' | 'TextActivity' | 'MessageActivity' | 'ActivityReply' | 'Thread' | 'ThreadComment',
ParentType,
ContextType
>;
}
export interface ListActivityResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ListActivity'] = ResolversParentTypes['ListActivity']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['ActivityType']>, ParentType, ContextType>;
replyCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
progress?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isLocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSubscribed?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
replies?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityReply']>>>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ListScoreStatsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ListScoreStats'] = ResolversParentTypes['ListScoreStats']
> {
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
standardDeviation?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaResolvers<ContextType = any, ParentType extends ResolversParentTypes['Media'] = ResolversParentTypes['Media']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
idMal?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
title?: Resolver<Maybe<ResolversTypes['MediaTitle']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['MediaType']>, ParentType, ContextType>;
format?: Resolver<Maybe<ResolversTypes['MediaFormat']>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['MediaStatus']>, ParentType, ContextType, RequireFields<MediaStatusArgs, never>>;
description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<MediaDescriptionArgs, never>>;
startDate?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
endDate?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
season?: Resolver<Maybe<ResolversTypes['MediaSeason']>, ParentType, ContextType>;
seasonYear?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
seasonInt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
episodes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
duration?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
chapters?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
volumes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
countryOfOrigin?: Resolver<Maybe<ResolversTypes['CountryCode']>, ParentType, ContextType>;
isLicensed?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
source?: Resolver<Maybe<ResolversTypes['MediaSource']>, ParentType, ContextType, RequireFields<MediaSourceArgs, never>>;
hashtag?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
trailer?: Resolver<Maybe<ResolversTypes['MediaTrailer']>, ParentType, ContextType>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
coverImage?: Resolver<Maybe<ResolversTypes['MediaCoverImage']>, ParentType, ContextType>;
bannerImage?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
genres?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
synonyms?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
averageScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
popularity?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
isLocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
trending?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
favourites?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
tags?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTag']>>>, ParentType, ContextType>;
relations?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType>;
characters?: Resolver<Maybe<ResolversTypes['CharacterConnection']>, ParentType, ContextType, RequireFields<MediaCharactersArgs, never>>;
staff?: Resolver<Maybe<ResolversTypes['StaffConnection']>, ParentType, ContextType, RequireFields<MediaStaffArgs, never>>;
studios?: Resolver<Maybe<ResolversTypes['StudioConnection']>, ParentType, ContextType, RequireFields<MediaStudiosArgs, never>>;
isFavourite?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
isAdult?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
nextAiringEpisode?: Resolver<Maybe<ResolversTypes['AiringSchedule']>, ParentType, ContextType>;
airingSchedule?: Resolver<
Maybe<ResolversTypes['AiringScheduleConnection']>,
ParentType,
ContextType,
RequireFields<MediaAiringScheduleArgs, never>
>;
trends?: Resolver<Maybe<ResolversTypes['MediaTrendConnection']>, ParentType, ContextType, RequireFields<MediaTrendsArgs, never>>;
externalLinks?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaExternalLink']>>>, ParentType, ContextType>;
streamingEpisodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaStreamingEpisode']>>>, ParentType, ContextType>;
rankings?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaRank']>>>, ParentType, ContextType>;
mediaListEntry?: Resolver<Maybe<ResolversTypes['MediaList']>, ParentType, ContextType>;
reviews?: Resolver<Maybe<ResolversTypes['ReviewConnection']>, ParentType, ContextType, RequireFields<MediaReviewsArgs, never>>;
recommendations?: Resolver<
Maybe<ResolversTypes['RecommendationConnection']>,
ParentType,
ContextType,
RequireFields<MediaRecommendationsArgs, never>
>;
stats?: Resolver<Maybe<ResolversTypes['MediaStats']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
autoCreateForumThread?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isRecommendationBlocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
modNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaCharacterResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaCharacter'] = ResolversParentTypes['MediaCharacter']
> {
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
role?: Resolver<Maybe<ResolversTypes['CharacterRole']>, ParentType, ContextType>;
roleNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dubGroup?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
characterName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
character?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
voiceActor?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaConnection'] = ResolversParentTypes['MediaConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Media']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaCoverImageResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaCoverImage'] = ResolversParentTypes['MediaCoverImage']
> {
extraLarge?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
large?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
medium?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
color?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaEdgeResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaEdge'] = ResolversParentTypes['MediaEdge']> {
node?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
relationType?: Resolver<Maybe<ResolversTypes['MediaRelation']>, ParentType, ContextType, RequireFields<MediaEdgeRelationTypeArgs, never>>;
isMainStudio?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
characters?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Character']>>>, ParentType, ContextType>;
characterRole?: Resolver<Maybe<ResolversTypes['CharacterRole']>, ParentType, ContextType>;
characterName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
roleNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dubGroup?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
staffRole?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
voiceActors?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>,
ParentType,
ContextType,
RequireFields<MediaEdgeVoiceActorsArgs, never>
>;
voiceActorRoles?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffRoleType']>>>,
ParentType,
ContextType,
RequireFields<MediaEdgeVoiceActorRolesArgs, never>
>;
favouriteOrder?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaExternalLinkResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaExternalLink'] = ResolversParentTypes['MediaExternalLink']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
url?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
site?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaListResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaList'] = ResolversParentTypes['MediaList']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['MediaListStatus']>, ParentType, ContextType>;
score?: Resolver<Maybe<ResolversTypes['Float']>, ParentType, ContextType, RequireFields<MediaListScoreArgs, never>>;
progress?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
progressVolumes?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
repeat?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
priority?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
private?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
notes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
hiddenFromStatusLists?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
customLists?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType, RequireFields<MediaListCustomListsArgs, never>>;
advancedScores?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
startedAt?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
completedAt?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaListCollectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaListCollection'] = ResolversParentTypes['MediaListCollection']
> {
lists?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaListGroup']>>>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
hasNextChunk?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
statusLists?: Resolver<
Maybe<ReadonlyArray<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>>>,
ParentType,
ContextType,
RequireFields<MediaListCollectionStatusListsArgs, never>
>;
customLists?: Resolver<
Maybe<ReadonlyArray<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>>>,
ParentType,
ContextType,
RequireFields<MediaListCollectionCustomListsArgs, never>
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaListGroupResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaListGroup'] = ResolversParentTypes['MediaListGroup']
> {
entries?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>, ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isCustomList?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSplitCompletedList?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['MediaListStatus']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaListOptionsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaListOptions'] = ResolversParentTypes['MediaListOptions']
> {
scoreFormat?: Resolver<Maybe<ResolversTypes['ScoreFormat']>, ParentType, ContextType>;
rowOrder?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
useLegacyLists?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
animeList?: Resolver<Maybe<ResolversTypes['MediaListTypeOptions']>, ParentType, ContextType>;
mangaList?: Resolver<Maybe<ResolversTypes['MediaListTypeOptions']>, ParentType, ContextType>;
sharedTheme?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
sharedThemeEnabled?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaListTypeOptionsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaListTypeOptions'] = ResolversParentTypes['MediaListTypeOptions']
> {
sectionOrder?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
splitCompletedSectionByFormat?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
theme?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
customLists?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
advancedScoring?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
advancedScoringEnabled?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaRankResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaRank'] = ResolversParentTypes['MediaRank']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
rank?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<ResolversTypes['MediaRankType'], ParentType, ContextType>;
format?: Resolver<ResolversTypes['MediaFormat'], ParentType, ContextType>;
year?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
season?: Resolver<Maybe<ResolversTypes['MediaSeason']>, ParentType, ContextType>;
allTime?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
context?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaStats'] = ResolversParentTypes['MediaStats']> {
scoreDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ScoreDistribution']>>>, ParentType, ContextType>;
statusDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StatusDistribution']>>>, ParentType, ContextType>;
airingProgression?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['AiringProgression']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaStreamingEpisodeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaStreamingEpisode'] = ResolversParentTypes['MediaStreamingEpisode']
> {
title?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
thumbnail?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
url?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
site?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaSubmissionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaSubmission'] = ResolversParentTypes['MediaSubmission']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
submitter?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['SubmissionStatus']>, ParentType, ContextType>;
submitterStats?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
notes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
source?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
changes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
submission?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
characters?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaSubmissionComparison']>>>, ParentType, ContextType>;
staff?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaSubmissionComparison']>>>, ParentType, ContextType>;
studios?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaSubmissionComparison']>>>, ParentType, ContextType>;
relations?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaEdge']>>>, ParentType, ContextType>;
externalLinks?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaExternalLink']>>>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaSubmissionComparisonResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaSubmissionComparison'] = ResolversParentTypes['MediaSubmissionComparison']
> {
submission?: Resolver<Maybe<ResolversTypes['MediaSubmissionEdge']>, ParentType, ContextType>;
character?: Resolver<Maybe<ResolversTypes['MediaCharacter']>, ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['StaffEdge']>, ParentType, ContextType>;
studio?: Resolver<Maybe<ResolversTypes['StudioEdge']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaSubmissionEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaSubmissionEdge'] = ResolversParentTypes['MediaSubmissionEdge']
> {
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
characterRole?: Resolver<Maybe<ResolversTypes['CharacterRole']>, ParentType, ContextType>;
staffRole?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
roleNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dubGroup?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
characterName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isMain?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
character?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
characterSubmission?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
voiceActor?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
voiceActorSubmission?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
staffSubmission?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
studio?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTagResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaTag'] = ResolversParentTypes['MediaTag']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
category?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
rank?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
isGeneralSpoiler?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isMediaSpoiler?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isAdult?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTitleResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaTitle'] = ResolversParentTypes['MediaTitle']> {
romaji?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<MediaTitleRomajiArgs, never>>;
english?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<MediaTitleEnglishArgs, never>>;
native?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<MediaTitleNativeArgs, never>>;
userPreferred?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTrailerResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaTrailer'] = ResolversParentTypes['MediaTrailer']
> {
id?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
site?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
thumbnail?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTrendResolvers<ContextType = any, ParentType extends ResolversParentTypes['MediaTrend'] = ResolversParentTypes['MediaTrend']> {
mediaId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
date?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
trending?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
averageScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
popularity?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
inProgress?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
releasing?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
episode?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTrendConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaTrendConnection'] = ResolversParentTypes['MediaTrendConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTrendEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTrend']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MediaTrendEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MediaTrendEdge'] = ResolversParentTypes['MediaTrendEdge']
> {
node?: Resolver<Maybe<ResolversTypes['MediaTrend']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MessageActivityResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['MessageActivity'] = ResolversParentTypes['MessageActivity']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
recipientId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
messengerId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['ActivityType']>, ParentType, ContextType>;
replyCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
message?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<MessageActivityMessageArgs, never>>;
isLocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSubscribed?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isPrivate?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
recipient?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
messenger?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
replies?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityReply']>>>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ModActionResolvers<ContextType = any, ParentType extends ResolversParentTypes['ModAction'] = ResolversParentTypes['ModAction']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
mod?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['ModActionType']>, ParentType, ContextType>;
objectId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
objectType?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
data?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface MutationResolvers<ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> {
UpdateUser?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<MutationUpdateUserArgs, never>>;
SaveMediaListEntry?: Resolver<Maybe<ResolversTypes['MediaList']>, ParentType, ContextType, RequireFields<MutationSaveMediaListEntryArgs, never>>;
UpdateMediaListEntries?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>,
ParentType,
ContextType,
RequireFields<MutationUpdateMediaListEntriesArgs, never>
>;
DeleteMediaListEntry?: Resolver<
Maybe<ResolversTypes['Deleted']>,
ParentType,
ContextType,
RequireFields<MutationDeleteMediaListEntryArgs, never>
>;
DeleteCustomList?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteCustomListArgs, never>>;
SaveTextActivity?: Resolver<Maybe<ResolversTypes['TextActivity']>, ParentType, ContextType, RequireFields<MutationSaveTextActivityArgs, never>>;
SaveMessageActivity?: Resolver<
Maybe<ResolversTypes['MessageActivity']>,
ParentType,
ContextType,
RequireFields<MutationSaveMessageActivityArgs, never>
>;
SaveListActivity?: Resolver<Maybe<ResolversTypes['ListActivity']>, ParentType, ContextType, RequireFields<MutationSaveListActivityArgs, never>>;
DeleteActivity?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteActivityArgs, never>>;
ToggleActivitySubscription?: Resolver<
Maybe<ResolversTypes['ActivityUnion']>,
ParentType,
ContextType,
RequireFields<MutationToggleActivitySubscriptionArgs, never>
>;
SaveActivityReply?: Resolver<
Maybe<ResolversTypes['ActivityReply']>,
ParentType,
ContextType,
RequireFields<MutationSaveActivityReplyArgs, never>
>;
DeleteActivityReply?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteActivityReplyArgs, never>>;
ToggleLike?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<MutationToggleLikeArgs, never>>;
ToggleLikeV2?: Resolver<Maybe<ResolversTypes['LikeableUnion']>, ParentType, ContextType, RequireFields<MutationToggleLikeV2Args, never>>;
ToggleFollow?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<MutationToggleFollowArgs, never>>;
ToggleFavourite?: Resolver<Maybe<ResolversTypes['Favourites']>, ParentType, ContextType, RequireFields<MutationToggleFavouriteArgs, never>>;
UpdateFavouriteOrder?: Resolver<
Maybe<ResolversTypes['Favourites']>,
ParentType,
ContextType,
RequireFields<MutationUpdateFavouriteOrderArgs, never>
>;
SaveReview?: Resolver<Maybe<ResolversTypes['Review']>, ParentType, ContextType, RequireFields<MutationSaveReviewArgs, never>>;
DeleteReview?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteReviewArgs, never>>;
RateReview?: Resolver<Maybe<ResolversTypes['Review']>, ParentType, ContextType, RequireFields<MutationRateReviewArgs, never>>;
SaveRecommendation?: Resolver<
Maybe<ResolversTypes['Recommendation']>,
ParentType,
ContextType,
RequireFields<MutationSaveRecommendationArgs, never>
>;
SaveThread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType, RequireFields<MutationSaveThreadArgs, never>>;
DeleteThread?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteThreadArgs, never>>;
ToggleThreadSubscription?: Resolver<
Maybe<ResolversTypes['Thread']>,
ParentType,
ContextType,
RequireFields<MutationToggleThreadSubscriptionArgs, never>
>;
SaveThreadComment?: Resolver<
Maybe<ResolversTypes['ThreadComment']>,
ParentType,
ContextType,
RequireFields<MutationSaveThreadCommentArgs, never>
>;
DeleteThreadComment?: Resolver<Maybe<ResolversTypes['Deleted']>, ParentType, ContextType, RequireFields<MutationDeleteThreadCommentArgs, never>>;
UpdateAniChartSettings?: Resolver<
Maybe<ResolversTypes['Json']>,
ParentType,
ContextType,
RequireFields<MutationUpdateAniChartSettingsArgs, never>
>;
UpdateAniChartHighlights?: Resolver<
Maybe<ResolversTypes['Json']>,
ParentType,
ContextType,
RequireFields<MutationUpdateAniChartHighlightsArgs, never>
>;
}
export interface NotificationOptionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['NotificationOption'] = ResolversParentTypes['NotificationOption']
> {
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
enabled?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface NotificationUnionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['NotificationUnion'] = ResolversParentTypes['NotificationUnion']
> {
__resolveType: TypeResolveFn<
| 'AiringNotification'
| 'FollowingNotification'
| 'ActivityMessageNotification'
| 'ActivityMentionNotification'
| 'ActivityReplyNotification'
| 'ActivityReplySubscribedNotification'
| 'ActivityLikeNotification'
| 'ActivityReplyLikeNotification'
| 'ThreadCommentMentionNotification'
| 'ThreadCommentReplyNotification'
| 'ThreadCommentSubscribedNotification'
| 'ThreadCommentLikeNotification'
| 'ThreadLikeNotification'
| 'RelatedMediaAdditionNotification',
ParentType,
ContextType
>;
}
export interface PageResolvers<ContextType = any, ParentType extends ResolversParentTypes['Page'] = ResolversParentTypes['Page']> {
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
users?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<PageUsersArgs, never>>;
media?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Media']>>>, ParentType, ContextType, RequireFields<PageMediaArgs, never>>;
characters?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Character']>>>,
ParentType,
ContextType,
RequireFields<PageCharactersArgs, never>
>;
staff?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>, ParentType, ContextType, RequireFields<PageStaffArgs, never>>;
studios?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Studio']>>>, ParentType, ContextType, RequireFields<PageStudiosArgs, never>>;
mediaList?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaList']>>>, ParentType, ContextType, RequireFields<PageMediaListArgs, never>>;
airingSchedules?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['AiringSchedule']>>>,
ParentType,
ContextType,
RequireFields<PageAiringSchedulesArgs, never>
>;
mediaTrends?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTrend']>>>,
ParentType,
ContextType,
RequireFields<PageMediaTrendsArgs, never>
>;
notifications?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['NotificationUnion']>>>,
ParentType,
ContextType,
RequireFields<PageNotificationsArgs, never>
>;
followers?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<PageFollowersArgs, 'userId'>>;
following?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<PageFollowingArgs, 'userId'>>;
activities?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityUnion']>>>,
ParentType,
ContextType,
RequireFields<PageActivitiesArgs, never>
>;
activityReplies?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityReply']>>>,
ParentType,
ContextType,
RequireFields<PageActivityRepliesArgs, never>
>;
threads?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Thread']>>>, ParentType, ContextType, RequireFields<PageThreadsArgs, never>>;
threadComments?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ThreadComment']>>>,
ParentType,
ContextType,
RequireFields<PageThreadCommentsArgs, never>
>;
reviews?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Review']>>>, ParentType, ContextType, RequireFields<PageReviewsArgs, never>>;
recommendations?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['Recommendation']>>>,
ParentType,
ContextType,
RequireFields<PageRecommendationsArgs, never>
>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType, RequireFields<PageLikesArgs, never>>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface PageInfoResolvers<ContextType = any, ParentType extends ResolversParentTypes['PageInfo'] = ResolversParentTypes['PageInfo']> {
total?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
perPage?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
currentPage?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
lastPage?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
hasNextPage?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ParsedMarkdownResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ParsedMarkdown'] = ResolversParentTypes['ParsedMarkdown']
> {
html?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> {
Page?: Resolver<Maybe<ResolversTypes['Page']>, ParentType, ContextType, RequireFields<QueryPageArgs, never>>;
Media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType, RequireFields<QueryMediaArgs, never>>;
MediaTrend?: Resolver<Maybe<ResolversTypes['MediaTrend']>, ParentType, ContextType, RequireFields<QueryMediaTrendArgs, never>>;
AiringSchedule?: Resolver<Maybe<ResolversTypes['AiringSchedule']>, ParentType, ContextType, RequireFields<QueryAiringScheduleArgs, never>>;
Character?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType, RequireFields<QueryCharacterArgs, never>>;
Staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType, RequireFields<QueryStaffArgs, never>>;
MediaList?: Resolver<Maybe<ResolversTypes['MediaList']>, ParentType, ContextType, RequireFields<QueryMediaListArgs, never>>;
MediaListCollection?: Resolver<
Maybe<ResolversTypes['MediaListCollection']>,
ParentType,
ContextType,
RequireFields<QueryMediaListCollectionArgs, never>
>;
GenreCollection?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
MediaTagCollection?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['MediaTag']>>>,
ParentType,
ContextType,
RequireFields<QueryMediaTagCollectionArgs, never>
>;
User?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<QueryUserArgs, never>>;
Viewer?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
Notification?: Resolver<Maybe<ResolversTypes['NotificationUnion']>, ParentType, ContextType, RequireFields<QueryNotificationArgs, never>>;
Studio?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType, RequireFields<QueryStudioArgs, never>>;
Review?: Resolver<Maybe<ResolversTypes['Review']>, ParentType, ContextType, RequireFields<QueryReviewArgs, never>>;
Activity?: Resolver<Maybe<ResolversTypes['ActivityUnion']>, ParentType, ContextType, RequireFields<QueryActivityArgs, never>>;
ActivityReply?: Resolver<Maybe<ResolversTypes['ActivityReply']>, ParentType, ContextType, RequireFields<QueryActivityReplyArgs, never>>;
Following?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<QueryFollowingArgs, 'userId'>>;
Follower?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<QueryFollowerArgs, 'userId'>>;
Thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType, RequireFields<QueryThreadArgs, never>>;
ThreadComment?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['ThreadComment']>>>,
ParentType,
ContextType,
RequireFields<QueryThreadCommentArgs, never>
>;
Recommendation?: Resolver<Maybe<ResolversTypes['Recommendation']>, ParentType, ContextType, RequireFields<QueryRecommendationArgs, never>>;
Like?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<QueryLikeArgs, never>>;
Markdown?: Resolver<Maybe<ResolversTypes['ParsedMarkdown']>, ParentType, ContextType, RequireFields<QueryMarkdownArgs, 'markdown'>>;
AniChartUser?: Resolver<Maybe<ResolversTypes['AniChartUser']>, ParentType, ContextType>;
SiteStatistics?: Resolver<Maybe<ResolversTypes['SiteStatistics']>, ParentType, ContextType>;
MediaTagUser?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType, RequireFields<QueryMediaTagUserArgs, never>>;
}
export interface RecommendationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['Recommendation'] = ResolversParentTypes['Recommendation']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
rating?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
userRating?: Resolver<Maybe<ResolversTypes['RecommendationRating']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
mediaRecommendation?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface RecommendationConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['RecommendationConnection'] = ResolversParentTypes['RecommendationConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['RecommendationEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Recommendation']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface RecommendationEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['RecommendationEdge'] = ResolversParentTypes['RecommendationEdge']
> {
node?: Resolver<Maybe<ResolversTypes['Recommendation']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface RelatedMediaAdditionNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['RelatedMediaAdditionNotification'] = ResolversParentTypes['RelatedMediaAdditionNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
mediaId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ReportResolvers<ContextType = any, ParentType extends ResolversParentTypes['Report'] = ResolversParentTypes['Report']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
reporter?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
reported?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
reason?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
cleared?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ReviewResolvers<ContextType = any, ParentType extends ResolversParentTypes['Review'] = ResolversParentTypes['Review']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaType?: Resolver<Maybe<ResolversTypes['MediaType']>, ParentType, ContextType>;
summary?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
body?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<ReviewBodyArgs, never>>;
rating?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
ratingAmount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
userRating?: Resolver<Maybe<ResolversTypes['ReviewRating']>, ParentType, ContextType>;
score?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
private?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
updatedAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ReviewConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ReviewConnection'] = ResolversParentTypes['ReviewConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ReviewEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Review']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ReviewEdgeResolvers<ContextType = any, ParentType extends ResolversParentTypes['ReviewEdge'] = ResolversParentTypes['ReviewEdge']> {
node?: Resolver<Maybe<ResolversTypes['Review']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface RevisionHistoryResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['RevisionHistory'] = ResolversParentTypes['RevisionHistory']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
action?: Resolver<Maybe<ResolversTypes['RevisionHistoryAction']>, ParentType, ContextType>;
changes?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['Media']>, ParentType, ContextType>;
character?: Resolver<Maybe<ResolversTypes['Character']>, ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
studio?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ScoreDistributionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ScoreDistribution'] = ResolversParentTypes['ScoreDistribution']
> {
score?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface SiteStatisticsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['SiteStatistics'] = ResolversParentTypes['SiteStatistics']
> {
users?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsUsersArgs, never>>;
anime?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsAnimeArgs, never>>;
manga?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsMangaArgs, never>>;
characters?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsCharactersArgs, never>>;
staff?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsStaffArgs, never>>;
studios?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsStudiosArgs, never>>;
reviews?: Resolver<Maybe<ResolversTypes['SiteTrendConnection']>, ParentType, ContextType, RequireFields<SiteStatisticsReviewsArgs, never>>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface SiteTrendResolvers<ContextType = any, ParentType extends ResolversParentTypes['SiteTrend'] = ResolversParentTypes['SiteTrend']> {
date?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
change?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface SiteTrendConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['SiteTrendConnection'] = ResolversParentTypes['SiteTrendConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['SiteTrendEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['SiteTrend']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface SiteTrendEdgeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['SiteTrendEdge'] = ResolversParentTypes['SiteTrendEdge']
> {
node?: Resolver<Maybe<ResolversTypes['SiteTrend']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffResolvers<ContextType = any, ParentType extends ResolversParentTypes['Staff'] = ResolversParentTypes['Staff']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<Maybe<ResolversTypes['StaffName']>, ParentType, ContextType>;
language?: Resolver<Maybe<ResolversTypes['StaffLanguage']>, ParentType, ContextType>;
languageV2?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
image?: Resolver<Maybe<ResolversTypes['StaffImage']>, ParentType, ContextType>;
description?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<StaffDescriptionArgs, never>>;
primaryOccupations?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
gender?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dateOfBirth?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
dateOfDeath?: Resolver<Maybe<ResolversTypes['FuzzyDate']>, ParentType, ContextType>;
age?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
yearsActive?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Int']>>>, ParentType, ContextType>;
homeTown?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
bloodType?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isFavourite?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
isFavouriteBlocked?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
staffMedia?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<StaffStaffMediaArgs, never>>;
characters?: Resolver<Maybe<ResolversTypes['CharacterConnection']>, ParentType, ContextType, RequireFields<StaffCharactersArgs, never>>;
characterMedia?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<StaffCharacterMediaArgs, never>>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
submitter?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
submissionStatus?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
submissionNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
favourites?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
modNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StaffConnection'] = ResolversParentTypes['StaffConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Staff']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffEdgeResolvers<ContextType = any, ParentType extends ResolversParentTypes['StaffEdge'] = ResolversParentTypes['StaffEdge']> {
node?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
role?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
favouriteOrder?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffImageResolvers<ContextType = any, ParentType extends ResolversParentTypes['StaffImage'] = ResolversParentTypes['StaffImage']> {
large?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
medium?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffNameResolvers<ContextType = any, ParentType extends ResolversParentTypes['StaffName'] = ResolversParentTypes['StaffName']> {
first?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
middle?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
last?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
full?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
native?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
alternative?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['String']>>>, ParentType, ContextType>;
userPreferred?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffRoleTypeResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StaffRoleType'] = ResolversParentTypes['StaffRoleType']
> {
voiceActor?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
roleNotes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
dubGroup?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['StaffStats'] = ResolversParentTypes['StaffStats']> {
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
timeWatched?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StaffSubmissionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StaffSubmission'] = ResolversParentTypes['StaffSubmission']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
submission?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
submitter?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['SubmissionStatus']>, ParentType, ContextType>;
notes?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
source?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StatusDistributionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StatusDistribution'] = ResolversParentTypes['StatusDistribution']
> {
status?: Resolver<Maybe<ResolversTypes['MediaListStatus']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StudioResolvers<ContextType = any, ParentType extends ResolversParentTypes['Studio'] = ResolversParentTypes['Studio']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
isAnimationStudio?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
media?: Resolver<Maybe<ResolversTypes['MediaConnection']>, ParentType, ContextType, RequireFields<StudioMediaArgs, never>>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isFavourite?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
favourites?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StudioConnectionResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StudioConnection'] = ResolversParentTypes['StudioConnection']
> {
edges?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StudioEdge']>>>, ParentType, ContextType>;
nodes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Studio']>>>, ParentType, ContextType>;
pageInfo?: Resolver<Maybe<ResolversTypes['PageInfo']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StudioEdgeResolvers<ContextType = any, ParentType extends ResolversParentTypes['StudioEdge'] = ResolversParentTypes['StudioEdge']> {
node?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType>;
id?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
isMain?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
favouriteOrder?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface StudioStatsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['StudioStats'] = ResolversParentTypes['StudioStats']
> {
studio?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
timeWatched?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface TagStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['TagStats'] = ResolversParentTypes['TagStats']> {
tag?: Resolver<Maybe<ResolversTypes['MediaTag']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
timeWatched?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface TextActivityResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['TextActivity'] = ResolversParentTypes['TextActivity']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['ActivityType']>, ParentType, ContextType>;
replyCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<TextActivityTextArgs, never>>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isLocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSubscribed?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
replies?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ActivityReply']>>>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadResolvers<ContextType = any, ParentType extends ResolversParentTypes['Thread'] = ResolversParentTypes['Thread']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
title?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
body?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<ThreadBodyArgs, never>>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
replyUserId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
replyCommentId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
replyCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
viewCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
isLocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSticky?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isSubscribed?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
repliedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
updatedAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
replyUser?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
categories?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ThreadCategory']>>>, ParentType, ContextType>;
mediaCategories?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['Media']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCategoryResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadCategory'] = ResolversParentTypes['ThreadCategory']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCommentResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadComment'] = ResolversParentTypes['ThreadComment']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
threadId?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<ThreadCommentCommentArgs, never>>;
likeCount?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
isLiked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
updatedAt?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
likes?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
childComments?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCommentLikeNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadCommentLikeNotification'] = ResolversParentTypes['ThreadCommentLikeNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
commentId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['ThreadComment']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCommentMentionNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadCommentMentionNotification'] = ResolversParentTypes['ThreadCommentMentionNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
commentId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['ThreadComment']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCommentReplyNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadCommentReplyNotification'] = ResolversParentTypes['ThreadCommentReplyNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
commentId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['ThreadComment']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadCommentSubscribedNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadCommentSubscribedNotification'] = ResolversParentTypes['ThreadCommentSubscribedNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
commentId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['ThreadComment']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface ThreadLikeNotificationResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['ThreadLikeNotification'] = ResolversParentTypes['ThreadLikeNotification']
> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
userId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['NotificationType']>, ParentType, ContextType>;
threadId?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
context?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
thread?: Resolver<Maybe<ResolversTypes['Thread']>, ParentType, ContextType>;
comment?: Resolver<Maybe<ResolversTypes['ThreadComment']>, ParentType, ContextType>;
user?: Resolver<Maybe<ResolversTypes['User']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> {
id?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
about?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType, RequireFields<UserAboutArgs, never>>;
avatar?: Resolver<Maybe<ResolversTypes['UserAvatar']>, ParentType, ContextType>;
bannerImage?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
isFollowing?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isFollower?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
isBlocked?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
bans?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
options?: Resolver<Maybe<ResolversTypes['UserOptions']>, ParentType, ContextType>;
mediaListOptions?: Resolver<Maybe<ResolversTypes['MediaListOptions']>, ParentType, ContextType>;
favourites?: Resolver<Maybe<ResolversTypes['Favourites']>, ParentType, ContextType, RequireFields<UserFavouritesArgs, never>>;
statistics?: Resolver<Maybe<ResolversTypes['UserStatisticTypes']>, ParentType, ContextType>;
unreadNotificationCount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
siteUrl?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
donatorTier?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
donatorBadge?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
moderatorRoles?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ModRole']>>>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
stats?: Resolver<Maybe<ResolversTypes['UserStats']>, ParentType, ContextType>;
moderatorStatus?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
previousNames?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['UserPreviousName']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserActivityHistoryResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserActivityHistory'] = ResolversParentTypes['UserActivityHistory']
> {
date?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
level?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserAvatarResolvers<ContextType = any, ParentType extends ResolversParentTypes['UserAvatar'] = ResolversParentTypes['UserAvatar']> {
large?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
medium?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserCountryStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserCountryStatistic'] = ResolversParentTypes['UserCountryStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
country?: Resolver<Maybe<ResolversTypes['CountryCode']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserFormatStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserFormatStatistic'] = ResolversParentTypes['UserFormatStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
format?: Resolver<Maybe<ResolversTypes['MediaFormat']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserGenreStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserGenreStatistic'] = ResolversParentTypes['UserGenreStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
genre?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserLengthStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserLengthStatistic'] = ResolversParentTypes['UserLengthStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
length?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserModDataResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserModData'] = ResolversParentTypes['UserModData']
> {
alts?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['User']>>>, ParentType, ContextType>;
bans?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
ip?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
counts?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>;
privacy?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
email?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserOptionsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserOptions'] = ResolversParentTypes['UserOptions']
> {
titleLanguage?: Resolver<Maybe<ResolversTypes['UserTitleLanguage']>, ParentType, ContextType>;
displayAdultContent?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
airingNotifications?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>;
profileColor?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
notificationOptions?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['NotificationOption']>>>, ParentType, ContextType>;
timezone?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
activityMergeTime?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
staffNameLanguage?: Resolver<Maybe<ResolversTypes['UserStaffNameLanguage']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserPreviousNameResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserPreviousName'] = ResolversParentTypes['UserPreviousName']
> {
name?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
updatedAt?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserReleaseYearStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserReleaseYearStatistic'] = ResolversParentTypes['UserReleaseYearStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
releaseYear?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserScoreStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserScoreStatistic'] = ResolversParentTypes['UserScoreStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
score?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStaffStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStaffStatistic'] = ResolversParentTypes['UserStaffStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
staff?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStartYearStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStartYearStatistic'] = ResolversParentTypes['UserStartYearStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
startYear?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStatisticTypesResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStatisticTypes'] = ResolversParentTypes['UserStatisticTypes']
> {
anime?: Resolver<Maybe<ResolversTypes['UserStatistics']>, ParentType, ContextType>;
manga?: Resolver<Maybe<ResolversTypes['UserStatistics']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStatisticsResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStatistics'] = ResolversParentTypes['UserStatistics']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
standardDeviation?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
episodesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
volumesRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
formats?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserFormatStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsFormatsArgs, never>
>;
statuses?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserStatusStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsStatusesArgs, never>
>;
scores?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserScoreStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsScoresArgs, never>
>;
lengths?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserLengthStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsLengthsArgs, never>
>;
releaseYears?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserReleaseYearStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsReleaseYearsArgs, never>
>;
startYears?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserStartYearStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsStartYearsArgs, never>
>;
genres?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserGenreStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsGenresArgs, never>
>;
tags?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserTagStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsTagsArgs, never>
>;
countries?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserCountryStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsCountriesArgs, never>
>;
voiceActors?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserVoiceActorStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsVoiceActorsArgs, never>
>;
staff?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserStaffStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsStaffArgs, never>
>;
studios?: Resolver<
Maybe<ReadonlyArray<Maybe<ResolversTypes['UserStudioStatistic']>>>,
ParentType,
ContextType,
RequireFields<UserStatisticsStudiosArgs, never>
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['UserStats'] = ResolversParentTypes['UserStats']> {
watchedTime?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
chaptersRead?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
activityHistory?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['UserActivityHistory']>>>, ParentType, ContextType>;
animeStatusDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StatusDistribution']>>>, ParentType, ContextType>;
mangaStatusDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StatusDistribution']>>>, ParentType, ContextType>;
animeScoreDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ScoreDistribution']>>>, ParentType, ContextType>;
mangaScoreDistribution?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['ScoreDistribution']>>>, ParentType, ContextType>;
animeListScores?: Resolver<Maybe<ResolversTypes['ListScoreStats']>, ParentType, ContextType>;
mangaListScores?: Resolver<Maybe<ResolversTypes['ListScoreStats']>, ParentType, ContextType>;
favouredGenresOverview?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['GenreStats']>>>, ParentType, ContextType>;
favouredGenres?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['GenreStats']>>>, ParentType, ContextType>;
favouredTags?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['TagStats']>>>, ParentType, ContextType>;
favouredActors?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffStats']>>>, ParentType, ContextType>;
favouredStaff?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StaffStats']>>>, ParentType, ContextType>;
favouredStudios?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['StudioStats']>>>, ParentType, ContextType>;
favouredYears?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['YearStats']>>>, ParentType, ContextType>;
favouredFormats?: Resolver<Maybe<ReadonlyArray<Maybe<ResolversTypes['FormatStats']>>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStatusStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStatusStatistic'] = ResolversParentTypes['UserStatusStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
status?: Resolver<Maybe<ResolversTypes['MediaListStatus']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserStudioStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserStudioStatistic'] = ResolversParentTypes['UserStudioStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
studio?: Resolver<Maybe<ResolversTypes['Studio']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserTagStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserTagStatistic'] = ResolversParentTypes['UserTagStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
tag?: Resolver<Maybe<ResolversTypes['MediaTag']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface UserVoiceActorStatisticResolvers<
ContextType = any,
ParentType extends ResolversParentTypes['UserVoiceActorStatistic'] = ResolversParentTypes['UserVoiceActorStatistic']
> {
count?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
meanScore?: Resolver<ResolversTypes['Float'], ParentType, ContextType>;
minutesWatched?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
chaptersRead?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
mediaIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
voiceActor?: Resolver<Maybe<ResolversTypes['Staff']>, ParentType, ContextType>;
characterIds?: Resolver<ReadonlyArray<Maybe<ResolversTypes['Int']>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface YearStatsResolvers<ContextType = any, ParentType extends ResolversParentTypes['YearStats'] = ResolversParentTypes['YearStats']> {
year?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
amount?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
meanScore?: Resolver<Maybe<ResolversTypes['Int']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
}
export interface Resolvers<ContextType = any> {
ActivityLikeNotification?: ActivityLikeNotificationResolvers<ContextType>;
ActivityMentionNotification?: ActivityMentionNotificationResolvers<ContextType>;
ActivityMessageNotification?: ActivityMessageNotificationResolvers<ContextType>;
ActivityReply?: ActivityReplyResolvers<ContextType>;
ActivityReplyLikeNotification?: ActivityReplyLikeNotificationResolvers<ContextType>;
ActivityReplyNotification?: ActivityReplyNotificationResolvers<ContextType>;
ActivityReplySubscribedNotification?: ActivityReplySubscribedNotificationResolvers<ContextType>;
ActivityUnion?: ActivityUnionResolvers<ContextType>;
AiringNotification?: AiringNotificationResolvers<ContextType>;
AiringProgression?: AiringProgressionResolvers<ContextType>;
AiringSchedule?: AiringScheduleResolvers<ContextType>;
AiringScheduleConnection?: AiringScheduleConnectionResolvers<ContextType>;
AiringScheduleEdge?: AiringScheduleEdgeResolvers<ContextType>;
AniChartUser?: AniChartUserResolvers<ContextType>;
Character?: CharacterResolvers<ContextType>;
CharacterConnection?: CharacterConnectionResolvers<ContextType>;
CharacterEdge?: CharacterEdgeResolvers<ContextType>;
CharacterImage?: CharacterImageResolvers<ContextType>;
CharacterName?: CharacterNameResolvers<ContextType>;
CharacterSubmission?: CharacterSubmissionResolvers<ContextType>;
CharacterSubmissionConnection?: CharacterSubmissionConnectionResolvers<ContextType>;
CharacterSubmissionEdge?: CharacterSubmissionEdgeResolvers<ContextType>;
CountryCode?: GraphQLScalarType;
Deleted?: DeletedResolvers<ContextType>;
Favourites?: FavouritesResolvers<ContextType>;
FollowingNotification?: FollowingNotificationResolvers<ContextType>;
FormatStats?: FormatStatsResolvers<ContextType>;
FuzzyDate?: FuzzyDateResolvers<ContextType>;
FuzzyDateInt?: GraphQLScalarType;
GenreStats?: GenreStatsResolvers<ContextType>;
InternalPage?: InternalPageResolvers<ContextType>;
Json?: GraphQLScalarType;
LikeableUnion?: LikeableUnionResolvers<ContextType>;
ListActivity?: ListActivityResolvers<ContextType>;
ListScoreStats?: ListScoreStatsResolvers<ContextType>;
Media?: MediaResolvers<ContextType>;
MediaCharacter?: MediaCharacterResolvers<ContextType>;
MediaConnection?: MediaConnectionResolvers<ContextType>;
MediaCoverImage?: MediaCoverImageResolvers<ContextType>;
MediaEdge?: MediaEdgeResolvers<ContextType>;
MediaExternalLink?: MediaExternalLinkResolvers<ContextType>;
MediaList?: MediaListResolvers<ContextType>;
MediaListCollection?: MediaListCollectionResolvers<ContextType>;
MediaListGroup?: MediaListGroupResolvers<ContextType>;
MediaListOptions?: MediaListOptionsResolvers<ContextType>;
MediaListTypeOptions?: MediaListTypeOptionsResolvers<ContextType>;
MediaRank?: MediaRankResolvers<ContextType>;
MediaStats?: MediaStatsResolvers<ContextType>;
MediaStreamingEpisode?: MediaStreamingEpisodeResolvers<ContextType>;
MediaSubmission?: MediaSubmissionResolvers<ContextType>;
MediaSubmissionComparison?: MediaSubmissionComparisonResolvers<ContextType>;
MediaSubmissionEdge?: MediaSubmissionEdgeResolvers<ContextType>;
MediaTag?: MediaTagResolvers<ContextType>;
MediaTitle?: MediaTitleResolvers<ContextType>;
MediaTrailer?: MediaTrailerResolvers<ContextType>;
MediaTrend?: MediaTrendResolvers<ContextType>;
MediaTrendConnection?: MediaTrendConnectionResolvers<ContextType>;
MediaTrendEdge?: MediaTrendEdgeResolvers<ContextType>;
MessageActivity?: MessageActivityResolvers<ContextType>;
ModAction?: ModActionResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
NotificationOption?: NotificationOptionResolvers<ContextType>;
NotificationUnion?: NotificationUnionResolvers<ContextType>;
Page?: PageResolvers<ContextType>;
PageInfo?: PageInfoResolvers<ContextType>;
ParsedMarkdown?: ParsedMarkdownResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
Recommendation?: RecommendationResolvers<ContextType>;
RecommendationConnection?: RecommendationConnectionResolvers<ContextType>;
RecommendationEdge?: RecommendationEdgeResolvers<ContextType>;
RelatedMediaAdditionNotification?: RelatedMediaAdditionNotificationResolvers<ContextType>;
Report?: ReportResolvers<ContextType>;
Review?: ReviewResolvers<ContextType>;
ReviewConnection?: ReviewConnectionResolvers<ContextType>;
ReviewEdge?: ReviewEdgeResolvers<ContextType>;
RevisionHistory?: RevisionHistoryResolvers<ContextType>;
ScoreDistribution?: ScoreDistributionResolvers<ContextType>;
SiteStatistics?: SiteStatisticsResolvers<ContextType>;
SiteTrend?: SiteTrendResolvers<ContextType>;
SiteTrendConnection?: SiteTrendConnectionResolvers<ContextType>;
SiteTrendEdge?: SiteTrendEdgeResolvers<ContextType>;
Staff?: StaffResolvers<ContextType>;
StaffConnection?: StaffConnectionResolvers<ContextType>;
StaffEdge?: StaffEdgeResolvers<ContextType>;
StaffImage?: StaffImageResolvers<ContextType>;
StaffName?: StaffNameResolvers<ContextType>;
StaffRoleType?: StaffRoleTypeResolvers<ContextType>;
StaffStats?: StaffStatsResolvers<ContextType>;
StaffSubmission?: StaffSubmissionResolvers<ContextType>;
StatusDistribution?: StatusDistributionResolvers<ContextType>;
Studio?: StudioResolvers<ContextType>;
StudioConnection?: StudioConnectionResolvers<ContextType>;
StudioEdge?: StudioEdgeResolvers<ContextType>;
StudioStats?: StudioStatsResolvers<ContextType>;
TagStats?: TagStatsResolvers<ContextType>;
TextActivity?: TextActivityResolvers<ContextType>;
Thread?: ThreadResolvers<ContextType>;
ThreadCategory?: ThreadCategoryResolvers<ContextType>;
ThreadComment?: ThreadCommentResolvers<ContextType>;
ThreadCommentLikeNotification?: ThreadCommentLikeNotificationResolvers<ContextType>;
ThreadCommentMentionNotification?: ThreadCommentMentionNotificationResolvers<ContextType>;
ThreadCommentReplyNotification?: ThreadCommentReplyNotificationResolvers<ContextType>;
ThreadCommentSubscribedNotification?: ThreadCommentSubscribedNotificationResolvers<ContextType>;
ThreadLikeNotification?: ThreadLikeNotificationResolvers<ContextType>;
User?: UserResolvers<ContextType>;
UserActivityHistory?: UserActivityHistoryResolvers<ContextType>;
UserAvatar?: UserAvatarResolvers<ContextType>;
UserCountryStatistic?: UserCountryStatisticResolvers<ContextType>;
UserFormatStatistic?: UserFormatStatisticResolvers<ContextType>;
UserGenreStatistic?: UserGenreStatisticResolvers<ContextType>;
UserLengthStatistic?: UserLengthStatisticResolvers<ContextType>;
UserModData?: UserModDataResolvers<ContextType>;
UserOptions?: UserOptionsResolvers<ContextType>;
UserPreviousName?: UserPreviousNameResolvers<ContextType>;
UserReleaseYearStatistic?: UserReleaseYearStatisticResolvers<ContextType>;
UserScoreStatistic?: UserScoreStatisticResolvers<ContextType>;
UserStaffStatistic?: UserStaffStatisticResolvers<ContextType>;
UserStartYearStatistic?: UserStartYearStatisticResolvers<ContextType>;
UserStatisticTypes?: UserStatisticTypesResolvers<ContextType>;
UserStatistics?: UserStatisticsResolvers<ContextType>;
UserStats?: UserStatsResolvers<ContextType>;
UserStatusStatistic?: UserStatusStatisticResolvers<ContextType>;
UserStudioStatistic?: UserStudioStatisticResolvers<ContextType>;
UserTagStatistic?: UserTagStatisticResolvers<ContextType>;
UserVoiceActorStatistic?: UserVoiceActorStatisticResolvers<ContextType>;
YearStats?: YearStatsResolvers<ContextType>;
}
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType>; | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NodesApiService, setupTestBed } from '@alfresco/adf-core';
import { ContentTestingModule } from '../testing/content.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { AspectListComponent } from './aspect-list.component';
import { AspectListService } from './aspect-list.service';
import { of } from 'rxjs';
import { AspectEntry } from '@alfresco/js-api';
import { delay } from 'rxjs/operators';
const aspectListMock: AspectEntry[] = [{
entry: {
parentId: 'frs:aspectZero',
id: 'frs:AspectOne',
description: 'First Aspect with random description',
title: 'FirstAspect',
properties: [
{
id: 'channelPassword',
title: 'The authenticated channel password',
dataType: 'd:propA'
},
{
id: 'channelUsername',
title: 'The authenticated channel username',
dataType: 'd:propB'
}
]
}
},
{
entry: {
parentId: 'frs:AspectZer',
id: 'frs:SecondAspect',
description: 'Second Aspect description',
title: 'SecondAspect',
properties: [
{
id: 'assetId',
title: 'Published Asset Id',
dataType: 'd:text'
},
{
id: 'assetUrl',
title: 'Published Asset URL',
dataType: 'd:text'
}
]
}
}];
const customAspectListMock: AspectEntry[] = [{
entry: {
parentId: 'cst:parentAspect',
id: 'cst:customAspect',
description: 'Custom Aspect with random description',
title: 'CustomAspect',
properties: [
{
id: 'channelPassword',
title: 'The authenticated channel password',
dataType: 'd:propA'
},
{
id: 'channelUsername',
title: 'The authenticated channel username',
dataType: 'd:propB'
}
]
}
},
{
entry: {
parentId: 'cst:commonaspect',
id: 'cst:nonamedAspect',
description: '',
title: '',
properties: [
{
id: 'channelPassword',
title: 'The authenticated channel password',
dataType: 'd:propA'
}
]
}
}];
describe('AspectListComponent', () => {
let component: AspectListComponent;
let fixture: ComponentFixture<AspectListComponent>;
let aspectListService: AspectListService;
let nodeService: NodesApiService;
setupTestBed({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [AspectListService]
});
describe('Loading', () => {
beforeEach(() => {
fixture = TestBed.createComponent(AspectListComponent);
component = fixture.componentInstance;
nodeService = TestBed.inject(NodesApiService);
aspectListService = TestBed.inject(AspectListService);
});
it('should show the loading spinner when result is loading', () => {
const delayReusult = of(null).pipe(delay(0));
spyOn(nodeService, 'getNode').and.returnValue(delayReusult);
spyOn(aspectListService, 'getAspects').and.returnValue(delayReusult);
fixture.detectChanges();
const spinner = fixture.nativeElement.querySelector('#adf-aspect-spinner');
expect(spinner).toBeDefined();
expect(spinner).not.toBeNull();
});
});
describe('When passing a node id', () => {
beforeEach(() => {
fixture = TestBed.createComponent(AspectListComponent);
component = fixture.componentInstance;
aspectListService = TestBed.inject(AspectListService);
spyOn(aspectListService, 'getAspects').and.returnValue(of([...aspectListMock, ...customAspectListMock]));
spyOn(aspectListService, 'getCustomAspects').and.returnValue(of(customAspectListMock));
spyOn(aspectListService, 'getVisibleAspects').and.returnValue(['frs:AspectOne']);
nodeService = TestBed.inject(NodesApiService);
spyOn(nodeService, 'getNode').and.returnValue(of({ id: 'fake-node-id', aspectNames: ['frs:AspectOne'] } as any));
component.nodeId = 'fake-node-id';
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
it('should return true when same aspect list selected', () => {
expect(component.hasEqualAspect).toBe(true);
});
it('should return false when different aspect list selected', () => {
component.clear();
expect(component.hasEqualAspect).toBe(false);
});
it('should show all the aspects', () => {
const firstElement = fixture.nativeElement.querySelector('#aspect-list-FirstAspect');
const secondElement = fixture.nativeElement.querySelector('#aspect-list-SecondAspect');
expect(firstElement).not.toBeNull();
expect(firstElement).toBeDefined();
expect(secondElement).not.toBeNull();
expect(secondElement).toBeDefined();
});
it('should show aspect id when name or title is not set', () => {
const noNameAspect: HTMLElement = fixture.nativeElement.querySelector('#aspect-list-cst-nonamedAspect .adf-aspect-list-element-title');
expect(noNameAspect).toBeDefined();
expect(noNameAspect).not.toBeNull();
expect(noNameAspect.innerText).toBe('cst:nonamedAspect');
});
it('should show the details when a row is clicked', () => {
const firstElement = fixture.nativeElement.querySelector('#aspect-list-FirstAspect');
firstElement.click();
fixture.detectChanges();
const firstElementDesc = fixture.nativeElement.querySelector('#aspect-list-0-description');
expect(firstElementDesc).not.toBeNull();
expect(firstElementDesc).toBeDefined();
const firstElementPropertyTable = fixture.nativeElement.querySelector('#aspect-list-0-properties-table');
expect(firstElementPropertyTable).not.toBeNull();
expect(firstElementPropertyTable).toBeDefined();
const nameProperties = fixture.nativeElement.querySelectorAll('#aspect-list-0-properties-table tbody .mat-column-name');
expect(nameProperties[0]).not.toBeNull();
expect(nameProperties[0]).toBeDefined();
expect(nameProperties[0].innerText).toBe('channelPassword');
expect(nameProperties[1]).not.toBeNull();
expect(nameProperties[1]).toBeDefined();
expect(nameProperties[1].innerText).toBe('channelUsername');
const titleProperties = fixture.nativeElement.querySelectorAll('#aspect-list-0-properties-table tbody .mat-column-title');
expect(titleProperties[0]).not.toBeNull();
expect(titleProperties[0]).toBeDefined();
expect(titleProperties[0].innerText).toBe('The authenticated channel password');
expect(titleProperties[1]).not.toBeNull();
expect(titleProperties[1]).toBeDefined();
expect(titleProperties[1].innerText).toBe('The authenticated channel username');
const dataTypeProperties = fixture.nativeElement.querySelectorAll('#aspect-list-0-properties-table tbody .mat-column-dataType');
expect(dataTypeProperties[0]).not.toBeNull();
expect(dataTypeProperties[0]).toBeDefined();
expect(dataTypeProperties[0].innerText).toBe('d:propA');
expect(dataTypeProperties[1]).not.toBeNull();
expect(dataTypeProperties[1]).toBeDefined();
expect(dataTypeProperties[1].innerText).toBe('d:propB');
});
it('should show as checked the node properties', () => {
const firstAspectCheckbox: HTMLInputElement = fixture.nativeElement.querySelector('#aspect-list-0-check-input');
expect(firstAspectCheckbox).toBeDefined();
expect(firstAspectCheckbox).not.toBeNull();
expect(firstAspectCheckbox.checked).toBeTruthy();
});
it('should remove aspects unchecked', (done) => {
const secondElement = fixture.nativeElement.querySelector('#aspect-list-1-check-input');
expect(secondElement).toBeDefined();
expect(secondElement).not.toBeNull();
expect(secondElement.checked).toBeFalsy();
secondElement.click();
fixture.detectChanges();
expect(component.nodeAspects.length).toBe(2);
expect(component.nodeAspects[1]).toBe('frs:SecondAspect');
component.valueChanged.subscribe((aspects) => {
expect(aspects.length).toBe(1);
expect(aspects[0]).toBe('frs:AspectOne');
done();
});
secondElement.click();
fixture.detectChanges();
});
it('should reset the properties on reset', (done) => {
const secondElement = fixture.nativeElement.querySelector('#aspect-list-1-check-input');
expect(secondElement).toBeDefined();
expect(secondElement).not.toBeNull();
expect(secondElement.checked).toBeFalsy();
secondElement.click();
fixture.detectChanges();
expect(component.nodeAspects.length).toBe(2);
component.valueChanged.subscribe((aspects) => {
expect(aspects.length).toBe(1);
done();
});
component.reset();
});
it('should clear all the properties on clear', (done) => {
expect(component.nodeAspects.length).toBe(1);
component.valueChanged.subscribe((aspects) => {
expect(aspects.length).toBe(0);
done();
});
component.clear();
});
});
describe('When no node id is passed', () => {
beforeEach(() => {
fixture = TestBed.createComponent(AspectListComponent);
component = fixture.componentInstance;
aspectListService = TestBed.inject(AspectListService);
spyOn(aspectListService, 'getAspects').and.returnValue(of(aspectListMock));
fixture.detectChanges();
});
afterEach(() => {
fixture.destroy();
});
it('should show all the aspects', () => {
const firstElement = fixture.nativeElement.querySelector('#aspect-list-FirstAspect');
const secondElement = fixture.nativeElement.querySelector('#aspect-list-SecondAspect');
expect(firstElement).not.toBeNull();
expect(firstElement).toBeDefined();
expect(secondElement).not.toBeNull();
expect(secondElement).toBeDefined();
});
});
}); | the_stack |
import { JavaArrayListMarshaller, JavaHashSetMarshaller } from "../JavaCollectionMarshaller";
import {
JavaArrayList,
JavaBigDecimal,
JavaBigInteger,
JavaBoolean,
JavaByte,
JavaDate,
JavaDouble,
JavaFloat,
JavaHashMap,
JavaHashSet,
JavaInteger,
JavaLong,
JavaOptional,
JavaShort,
JavaString
} from "../../../java-wrappers";
import { MarshallingContext } from "../../MarshallingContext";
import { ErraiObjectConstants } from "../../model/ErraiObjectConstants";
import { MarshallerProvider } from "../../MarshallerProvider";
import { JavaBigIntegerMarshaller } from "../JavaBigIntegerMarshaller";
import { Portable } from "../../Portable";
import { NumValBasedErraiObject } from "../../model/NumValBasedErraiObject";
import { NumberUtils } from "../../../util/NumberUtils";
import { UnmarshallingContext } from "../../UnmarshallingContext";
import { ValueBasedErraiObject } from "../../model/ValueBasedErraiObject";
import { JavaType } from "../../../java-wrappers/JavaType";
describe("marshall", () => {
const encodedType = ErraiObjectConstants.ENCODED_TYPE;
const objectId = ErraiObjectConstants.OBJECT_ID;
const value = ErraiObjectConstants.VALUE;
let context: MarshallingContext;
beforeEach(() => {
MarshallerProvider.initialize();
context = new MarshallingContext();
});
test("with empty collection, should serialize normally", () => {
const arrayListScenario = () => {
const input = new JavaArrayList([]);
return { fqcn: JavaType.ARRAY_LIST, output: new JavaArrayListMarshaller().marshall(input, context) };
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set([]));
return { fqcn: JavaType.HASH_SET, output: new JavaHashSetMarshaller().marshall(input, context) };
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: []
});
});
});
test("with JavaNumber collection, should wrap every element into an errai object", () => {
const numberArray = [new JavaInteger("1"), new JavaInteger("2"), new JavaInteger("3")];
const arrayListScenario = () => {
const input = new JavaArrayList(numberArray);
return { fqcn: JavaType.ARRAY_LIST, output: new JavaArrayListMarshaller().marshall(input, context) };
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set(numberArray));
return { fqcn: JavaType.HASH_SET, output: new JavaHashSetMarshaller().marshall(input, context) };
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: [
new NumValBasedErraiObject(JavaType.INTEGER, 1).asErraiObject(),
new NumValBasedErraiObject(JavaType.INTEGER, 2).asErraiObject(),
new NumValBasedErraiObject(JavaType.INTEGER, 3).asErraiObject()
]
});
});
});
test("with JavaBoolean collection, should wrap every element into an errai object", () => {
const booleanArray = [new JavaBoolean(true), new JavaBoolean(false)];
const arrayListScenario = () => {
const input = new JavaArrayList(booleanArray);
return { fqcn: JavaType.ARRAY_LIST, output: new JavaArrayListMarshaller().marshall(input, context) };
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set(booleanArray));
return { fqcn: JavaType.HASH_SET, output: new JavaHashSetMarshaller().marshall(input, context) };
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: [
new NumValBasedErraiObject(JavaType.BOOLEAN, true).asErraiObject(),
new NumValBasedErraiObject(JavaType.BOOLEAN, false).asErraiObject()
]
});
});
});
test("with JavaBigNumber collection, should serialize every element normally", () => {
const bigIntegerMarshaller = new JavaBigIntegerMarshaller();
const bigNumberArray = [new JavaBigInteger("1"), new JavaBigInteger("2"), new JavaBigInteger("3")];
const arrayListScenario = () => {
const input = new JavaArrayList(bigNumberArray);
return { fqcn: JavaType.ARRAY_LIST, output: new JavaArrayListMarshaller().marshall(input, context) };
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set(bigNumberArray));
return { fqcn: JavaType.HASH_SET, output: new JavaHashSetMarshaller().marshall(input, context) };
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: [
{
...(bigIntegerMarshaller.marshall(new JavaBigInteger("1"), context) as any),
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex)
},
{
...(bigIntegerMarshaller.marshall(new JavaBigInteger("2"), context) as any),
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex)
},
{
...(bigIntegerMarshaller.marshall(new JavaBigInteger("3"), context) as any),
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex)
}
]
});
});
});
test("with custom object collection, should serialize every element normally", () => {
const portableArray = [
new MyPortable({ foo: "foo1", bar: "bar1" }),
new MyPortable({ foo: "foo2", bar: "bar2" }),
new MyPortable({ foo: "foo3", bar: "bar3" })
];
const arrayListScenario = () => {
const input = new JavaArrayList(portableArray);
return {
fqcn: JavaType.ARRAY_LIST,
output: new JavaArrayListMarshaller().marshall(input, new MarshallingContext())
};
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set(portableArray));
return {
fqcn: JavaType.HASH_SET,
output: new JavaHashSetMarshaller().marshall(input, new MarshallingContext())
};
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: [
{
[encodedType]: "com.portable.my",
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
foo: "foo1",
bar: "bar1"
},
{
[encodedType]: "com.portable.my",
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
foo: "foo2",
bar: "bar2"
},
{
[encodedType]: "com.portable.my",
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
foo: "foo3",
bar: "bar3"
}
]
});
});
});
test("with collection containing null elements, should serialize every element normally", () => {
const arrayListScenario = () => {
const input = new JavaArrayList([null]);
return {
fqcn: JavaType.ARRAY_LIST,
output: new JavaArrayListMarshaller().marshall(input, new MarshallingContext())
};
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set([null]));
return {
fqcn: JavaType.HASH_SET,
output: new JavaHashSetMarshaller().marshall(input, new MarshallingContext())
};
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
expect(output).toStrictEqual({
[encodedType]: fqcn,
[objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex),
[value]: [null]
});
});
});
test("with custom pojo array containing repeated elements, should cache inner objects and don't repeat data", () => {
const repeatedValue = new Node({ data: "foo1", left: undefined, right: undefined });
const portableArray = [repeatedValue, new Node({ data: "foo2", left: undefined, right: repeatedValue })];
const arrayListScenario = () => {
const input = new JavaArrayList(portableArray);
return {
fqcn: JavaType.ARRAY_LIST,
output: new JavaArrayListMarshaller().marshall(input, new MarshallingContext())
};
};
const hashSetScenario = () => {
const input = new JavaHashSet(new Set(portableArray));
return {
fqcn: JavaType.HASH_SET,
output: new JavaHashSetMarshaller().marshall(input, new MarshallingContext())
};
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const { fqcn, output } = outputFunc();
const rootObjId = output![objectId];
expect(output![encodedType]).toEqual(fqcn);
expect(rootObjId).toMatch(NumberUtils.nonNegativeIntegerRegex);
const rootObjValue = output![value] as any[];
const foo2Objects = rootObjValue.filter(obj => obj.data === "foo2");
expect(foo2Objects.length).toEqual(1);
const uniqueObjId = foo2Objects[0][objectId];
expect(uniqueObjId).toMatch(NumberUtils.nonNegativeIntegerRegex);
const repeatedObjects = rootObjValue.filter(obj => obj.data !== "foo2");
expect(repeatedObjects.length).toEqual(1);
const repeatedObjId = repeatedObjects[0][objectId];
expect(repeatedObjId).toMatch(NumberUtils.nonNegativeIntegerRegex);
expect(rootObjValue).toEqual([
{ [encodedType]: "com.app.my.Node", [objectId]: repeatedObjId, data: "foo1", left: null, right: null },
{
[encodedType]: "com.app.my.Node",
[objectId]: uniqueObjId,
data: "foo2",
right: { [encodedType]: "com.app.my.Node", [objectId]: repeatedObjId },
left: null
}
]);
});
});
test("root null object, should serialize to null", () => {
const input = null as any;
const arrayListScenario = () => {
return new JavaArrayListMarshaller().marshall(input, new MarshallingContext());
};
const hashSetScenario = () => {
return new JavaHashSetMarshaller().marshall(input, new MarshallingContext());
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const output = outputFunc();
expect(output).toBeNull();
});
});
test("root undefined object, should serialize to null", () => {
const input = undefined as any;
const arrayListScenario = () => {
return new JavaArrayListMarshaller().marshall(input, new MarshallingContext());
};
const hashSetScenario = () => {
return new JavaHashSetMarshaller().marshall(input, new MarshallingContext());
};
[arrayListScenario, hashSetScenario].forEach(outputFunc => {
const output = outputFunc();
expect(output).toBeNull();
});
});
});
describe("unmarshall", () => {
beforeEach(() => {
MarshallerProvider.initialize();
});
test("with empty collection, should unmarshall to empty collection", () => {
const arrayInput = {
input: new JavaArrayList([]),
marshaller: new JavaArrayListMarshaller(),
expected: []
};
const setInput = {
input: new JavaHashSet(new Set([])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with Array collection, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([["foo"]]),
marshaller: new JavaArrayListMarshaller(),
expected: [["foo"]]
};
const setInput = {
input: new JavaHashSet(new Set([["foo"]])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([["foo"]])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaArrayList collection, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaArrayList(["foo"])]),
marshaller: new JavaArrayListMarshaller(),
expected: [["foo"]]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaArrayList(["foo"])])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([["foo"]])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with Set input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new Set(["foo"])]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Set(["foo"])]
};
const setInput = {
input: new JavaHashSet(new Set([new Set(["foo"])])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Set(["foo"])])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with HashSet input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaHashSet(new Set(["foo"]))]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Set(["foo"])]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaHashSet(new Set(["foo"]))])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Set(["foo"])])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with Map input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new Map([["foo", "bar"]])]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Map([["foo", "bar"]])]
};
const setInput = {
input: new JavaHashSet(new Set([new Map([["foo", "bar"]])])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Map([["foo", "bar"]])])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaHashMap input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaHashMap(new Map([["foo", "bar"]]))]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Map([["foo", "bar"]])]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaHashMap(new Map([["foo", "bar"]]))])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Map([["foo", "bar"]])])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with Date input, should unmarshall correctly", () => {
const baseDate = new Date();
const arrayInput = {
input: new JavaArrayList([new Date(baseDate)]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Date(baseDate)]
};
const setInput = {
input: new JavaHashSet(new Set([new Date(baseDate)])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Date(baseDate)])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaDate input, should unmarshall correctly", () => {
const baseDate = new Date();
const arrayInput = {
input: new JavaArrayList([new JavaDate(new Date(baseDate))]),
marshaller: new JavaArrayListMarshaller(),
expected: [new Date(baseDate)]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaDate(new Date(baseDate))])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new Date(baseDate)])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with Boolean input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([false]),
marshaller: new JavaArrayListMarshaller(),
expected: [false]
};
const setInput = {
input: new JavaHashSet(new Set([false])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([false])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaBoolean input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaBoolean(false)]),
marshaller: new JavaArrayListMarshaller(),
expected: [false]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaBoolean(false)])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([false])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with String input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList(["foo"]),
marshaller: new JavaArrayListMarshaller(),
expected: ["foo"]
};
const setInput = {
input: new JavaHashSet(new Set(["foo"])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set(["foo"])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaString input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaString("foo")]),
marshaller: new JavaArrayListMarshaller(),
expected: ["foo"]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaString("foo")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set(["foo"])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaOptional input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaOptional("foo")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaOptional("foo")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaOptional("foo")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaOptional("foo")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaBigDecimal input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaBigDecimal("1.1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaBigDecimal("1.1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaBigDecimal("1.1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaBigDecimal("1.1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaBigInteger should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaBigInteger("1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaBigInteger("1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaBigInteger("1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaBigInteger("1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaLong input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaLong("1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaLong("1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaLong("1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaLong("1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaByte input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaByte("1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaByte("1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaByte("1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaByte("1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaDouble input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaDouble("1.1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaDouble("1.1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaDouble("1.1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaDouble("1.1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaFloat input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaFloat("1.1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaFloat("1.1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaFloat("1.1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaFloat("1.1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaInteger input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaInteger("1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaInteger("1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaInteger("1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaInteger("1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with JavaShort input, should unmarshall correctly", () => {
const arrayInput = {
input: new JavaArrayList([new JavaShort("1")]),
marshaller: new JavaArrayListMarshaller(),
expected: [new JavaShort("1")]
};
const setInput = {
input: new JavaHashSet(new Set([new JavaShort("1")])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new JavaShort("1")])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(new Map()));
expect(output).toEqual(scenario.expected);
});
});
test("with custom object optional, should unmarshall correctly", () => {
const oracle = new Map([["com.portable.my", () => new MyPortable({} as any)]]);
const arrayInput = {
input: new JavaArrayList([new MyPortable({ foo: "bar", bar: "foo" })]),
marshaller: new JavaArrayListMarshaller(),
expected: [new MyPortable({ foo: "bar", bar: "foo" })]
};
const setInput = {
input: new JavaHashSet(new Set([new MyPortable({ foo: "bar", bar: "foo" })])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set([new MyPortable({ foo: "bar", bar: "foo" })])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(oracle));
expect(output).toEqual(scenario.expected);
});
});
test("with root null object, should unmarshall to undefined", () => {
[new JavaArrayListMarshaller(), new JavaHashSetMarshaller()].forEach(marshaller => {
const output = marshaller.unmarshall(null as any, new UnmarshallingContext(new Map()));
expect(output).toBeUndefined();
});
});
test("with root undefined object, should unmarshall to undefined", () => {
[new JavaArrayListMarshaller(), new JavaHashSetMarshaller()].forEach(marshaller => {
const output = marshaller.unmarshall(undefined as any, new UnmarshallingContext(new Map()));
expect(output).toBeUndefined();
});
});
test("with undefined value inside ErraiObject, should throw error", () => {
const arrayInput = {
input: new ValueBasedErraiObject(JavaType.ARRAY_LIST, undefined).asErraiObject(),
marshaller: new JavaArrayListMarshaller()
};
const setInput = {
input: new ValueBasedErraiObject(JavaType.HASH_SET, undefined).asErraiObject(),
marshaller: new JavaHashSetMarshaller()
};
[arrayInput, setInput].forEach(scenario => {
expect(() => scenario.marshaller.unmarshall(scenario.input, new UnmarshallingContext(new Map()))).toThrowError();
});
});
test("with null value inside ErraiObject, should throw error", () => {
const arrayInput = {
input: new ValueBasedErraiObject(JavaType.ARRAY_LIST, null).asErraiObject(),
marshaller: new JavaArrayListMarshaller()
};
const setInput = {
input: new ValueBasedErraiObject(JavaType.HASH_SET, null).asErraiObject(),
marshaller: new JavaHashSetMarshaller()
};
[arrayInput, setInput].forEach(scenario => {
expect(() => scenario.marshaller.unmarshall(scenario.input, new UnmarshallingContext(new Map()))).toThrowError();
});
});
test("with non array value inside ErraiObject, should throw error", () => {
const arrayInput = {
input: new ValueBasedErraiObject(JavaType.ARRAY_LIST, false).asErraiObject(),
marshaller: new JavaArrayListMarshaller()
};
const setInput = {
input: new ValueBasedErraiObject(JavaType.HASH_SET, false).asErraiObject(),
marshaller: new JavaHashSetMarshaller()
};
[arrayInput, setInput].forEach(scenario => {
expect(() => scenario.marshaller.unmarshall(scenario.input, new UnmarshallingContext(new Map()))).toThrowError();
});
});
test("with custom pojo containing repeated elements, should reuse cached objects and don't recreate data", () => {
const oracle = new Map([["com.app.my.Node", () => new Node({} as any)]]);
const repeatedValue = new Node({ data: "foo1" });
const portableArray = [repeatedValue, new Node({ data: "foo2", right: repeatedValue })];
const arrayInput = {
input: new JavaArrayList(portableArray),
marshaller: new JavaArrayListMarshaller(),
expected: portableArray
};
const setInput = {
input: new JavaHashSet(new Set(portableArray)),
marshaller: new JavaHashSetMarshaller(),
expected: new Set(portableArray)
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const output = scenario.marshaller.unmarshall(input, new UnmarshallingContext(oracle));
// compares value equality
expect(output).toEqual(scenario.expected);
// check if the repeated object was reused from cache
const asArray = Array.from(scenario.expected);
const repeatedNode = asArray[0];
const uniqueNode = asArray[1];
expect(repeatedNode).toBe(uniqueNode.right!);
});
});
test("with repeated collection unmarshalling, should reuse cached collection and don't recreate it", () => {
const arrayInput = {
input: new JavaArrayList(["list"]),
marshaller: new JavaArrayListMarshaller(),
expected: ["list"]
};
const setInput = {
input: new JavaHashSet(new Set(["set"])),
marshaller: new JavaHashSetMarshaller(),
expected: new Set(["set"])
};
[arrayInput, setInput].forEach(scenario => {
const input = (scenario.marshaller as any).marshall(scenario.input as any, new MarshallingContext());
const context = new UnmarshallingContext(new Map());
const output = scenario.marshaller.unmarshall(input, context);
const repeatedOutput = scenario.marshaller.unmarshall(input, context);
expect(output).toEqual(scenario.expected);
expect(output).toBe(repeatedOutput!);
});
});
});
class MyPortable implements Portable<MyPortable> {
private readonly _fqcn = "com.portable.my";
public readonly foo: string;
public readonly bar: string;
constructor(self: { foo: string; bar: string }) {
Object.assign(this, self);
}
}
class Node implements Portable<Node> {
private readonly _fqcn = "com.app.my.Node";
public readonly data: any;
public readonly left?: Node;
public readonly right?: Node;
constructor(self: { data: any; left?: Node; right?: Node }) {
Object.assign(this, self);
}
} | the_stack |
import { BotAdapter, WebRequest, BotFrameworkAdapterSettings, IUserTokenProvider, TokenResponse, TurnContext, ConversationReference } from 'botbuilder';
import { AppCredentials, JwtTokenValidation, MicrosoftAppCredentials, SimpleCredentialProvider, TokenApiClient, TokenApiModels, TokenStatus, TokenExchangeRequest, SignInUrlResponse } from 'botframework-connector';
import { parse as parseQueryString } from 'qs';
// Constants taken from BotFrameworkAdapter.ts
const OAUTH_ENDPOINT = 'https://api.botframework.com';
const US_GOV_OAUTH_ENDPOINT = 'https://api.botframework.azure.us';
import { USER_AGENT } from 'botbuilder/lib/botFrameworkAdapter';
/**
* Adds helper functions to the default BotAdapter
*/
export abstract class CustomWebAdapter extends BotAdapter implements IUserTokenProvider {
/**
* Workaround for [ABS OAuth cards](https://github.com/microsoft/botbuilder-js/pull/1812)
*/
public name = 'Web Adapter';
// OAuth Properties
protected readonly oAuthSettings: BotFrameworkAdapterSettings;
protected readonly credentials: AppCredentials;
protected readonly credentialsProvider: SimpleCredentialProvider;
public readonly TokenApiClientCredentialsKey: symbol = Symbol('TokenApiClientCredentials');
/**
* Creates a new CustomWebAdapter instance.
* @param botFrameworkAdapterSettings configuration settings for the adapter.
*/
public constructor(botFrameworkAdapterSettings?: BotFrameworkAdapterSettings) {
super();
this.oAuthSettings = botFrameworkAdapterSettings;
if (this.oAuthSettings?.appId) {
this.credentials = new MicrosoftAppCredentials(
this.oAuthSettings.appId,
this.oAuthSettings.appPassword || '',
this.oAuthSettings.channelAuthTenant
);
this.credentialsProvider = new SimpleCredentialProvider(
this.credentials.appId,
this.oAuthSettings.appPassword || ''
);
}
}
/**
* Retrieve body from WebRequest
* Works with Express & Restify
* @protected
* @param req incoming web request
*/
protected retrieveBody(req: WebRequest): Promise<any> {
const contentType = req.headers['content-type'] || req.headers['Content-Type'];
return new Promise((resolve: any, reject: any): void => {
if (req.body) {
try {
resolve(req.body);
} catch (err) {
reject(err);
}
} else {
let requestData = '';
req.on('data', (chunk: string): void => {
requestData += chunk;
});
req.on('end', (): void => {
try {
if (contentType?.includes('application/x-www-form-urlencoded')) {
req.body = parseQueryString(requestData);
} else {
req.body = JSON.parse(requestData);
}
resolve(req.body);
} catch (err) {
reject(err);
}
});
}
});
}
/**
* Copied from `BotFrameworkAdapter.ts` to support { type: 'delay' } activity.
* @param timeout timeout in milliseconds
* @default 1000
*/
protected delay(timeout: number): Promise<void> {
timeout = (typeof timeout === 'number' ? timeout : 1000);
return new Promise((resolve): void => {
setTimeout(resolve, timeout);
});
}
// OAuth functionality copied from BotFrameworkAdapter.ts
/**
* Asynchronously attempts to retrieve the token for a user that's in a login flow.
*
* @param context The context object for the turn.
* @param connectionName The name of the auth connection to use.
* @param magicCode Optional. The validation code the user entered.
* @param oAuthAppCredentials AppCredentials for OAuth.
*
* @returns A [TokenResponse](xref:botframework-schema.TokenResponse) object that contains the user token.
*/
public async getUserToken(context: TurnContext, connectionName: string, magicCode?: string): Promise<TokenResponse>;
public async getUserToken(context: TurnContext, connectionName: string, magicCode?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenResponse>;
public async getUserToken(context: TurnContext, connectionName: string, magicCode?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenResponse> {
if (!context.activity.from || !context.activity.from.id) {
throw new Error(`CustomWebAdapter.getUserToken(): missing from or from.id`);
}
if (!connectionName) {
throw new Error('getUserToken() requires a connectionName but none was provided.');
}
const userId: string = context.activity.from.id;
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, oAuthAppCredentials);
context.turnState.set(this.TokenApiClientCredentialsKey, client);
const result: TokenApiModels.UserTokenGetTokenResponse = await client.userToken.getToken(userId, connectionName, { code: magicCode, channelId: context.activity.channelId });
if (!result || !result.token || result._response.status == 404) {
return undefined;
} else {
return result as TokenResponse;
}
}
/**
* Asynchronously signs out the user from the token server.
*
* @param context The context object for the turn.
* @param connectionName The name of the auth connection to use.
* @param userId The ID of user to sign out.
* @param oAuthAppCredentials AppCredentials for OAuth.
*/
public async signOutUser(context: TurnContext, connectionName?: string, userId?: string): Promise<void>;
public async signOutUser(context: TurnContext, connectionName?: string, userId?: string, oAuthAppCredentials?: AppCredentials): Promise<void>;
public async signOutUser(context: TurnContext, connectionName?: string, userId?: string, oAuthAppCredentials?: AppCredentials): Promise<void> {
if (!context.activity.from || !context.activity.from.id) {
throw new Error(`CustomWebAdapter.signOutUser(): missing from or from.id`);
}
if (!userId) {
userId = context.activity.from.id;
}
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, oAuthAppCredentials);
context.turnState.set(this.TokenApiClientCredentialsKey, client);
await client.userToken.signOut(userId, { connectionName: connectionName, channelId: context.activity.channelId });
}
/**
* Asynchronously gets a sign-in link from the token server that can be sent as part
* of a [SigninCard](xref:botframework-schema.SigninCard).
*
* @param context The context object for the turn.
* @param connectionName The name of the auth connection to use.
* @param oAuthAppCredentials AppCredentials for OAuth.
* @param userId The user id that will be associated with the token.
* @param finalRedirect The final URL that the OAuth flow will redirect to.
*/
public async getSignInLink(context: TurnContext, connectionName: string, oAuthAppCredentials?: AppCredentials, userId?: string, finalRedirect?: string): Promise<string> {
if (userId && userId != context.activity.from.id) {
throw new ReferenceError(`cannot retrieve OAuth signin link for a user that's different from the conversation`);
}
const conversation: Partial<ConversationReference> = TurnContext.getConversationReference(context.activity);
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, oAuthAppCredentials);
context.turnState.set(this.TokenApiClientCredentialsKey, client);
const state: any = {
ConnectionName: connectionName,
Conversation: conversation,
MsAppId: (client.credentials as AppCredentials).appId,
RelatesTo: context.activity.relatesTo
};
const finalState: string = Buffer.from(JSON.stringify(state)).toString('base64');
return (await client.botSignIn.getSignInUrl(finalState, { channelId: context.activity.channelId, finalRedirect }))._response.bodyAsText;
}
/**
* Asynchronously retrieves the token status for each configured connection for the given user.
*
* @param context The context object for the turn.
* @param userId Optional. If present, the ID of the user to retrieve the token status for.
* Otherwise, the ID of the user who sent the current activity is used.
* @param includeFilter Optional. A comma-separated list of connection's to include. If present,
* the `includeFilter` parameter limits the tokens this method returns.
* @param oAuthAppCredentials AppCredentials for OAuth.
*
* @returns The [TokenStatus](xref:botframework-connector.TokenStatus) objects retrieved.
*/
public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string): Promise<TokenStatus[]>;
public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenStatus[]>;
public async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string, oAuthAppCredentials?: AppCredentials): Promise<TokenStatus[]> {
if (!userId && (!context.activity.from || !context.activity.from.id)) {
throw new Error(`CustomWebAdapter.getTokenStatus(): missing from or from.id`);
}
userId = userId || context.activity.from.id;
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, oAuthAppCredentials);
context.turnState.set(this.TokenApiClientCredentialsKey, client);
return (await client.userToken.getTokenStatus(userId, { channelId: context.activity.channelId, include: includeFilter }))._response.parsedBody;
}
/**
* Asynchronously signs out the user from the token server.
*
* @param context The context object for the turn.
* @param connectionName The name of the auth connection to use.
* @param resourceUrls The list of resource URLs to retrieve tokens for.
* @param oAuthAppCredentials AppCredentials for OAuth.
*
* @returns A map of the [TokenResponse](xref:botframework-schema.TokenResponse) objects by resource URL.
*/
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[]): Promise<{ [propertyName: string]: TokenResponse }>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{ [propertyName: string]: TokenResponse }>;
public async getAadTokens(context: TurnContext, connectionName: string, resourceUrls: string[], oAuthAppCredentials?: AppCredentials): Promise<{ [propertyName: string]: TokenResponse }> {
if (!context.activity.from || !context.activity.from.id) {
throw new Error(`CustomWebAdapter.getAadTokens(): missing from or from.id`);
}
const userId: string = context.activity.from.id;
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, oAuthAppCredentials);
context.turnState.set(this.TokenApiClientCredentialsKey, client);
return (await client.userToken.getAadTokens(userId, connectionName, { resourceUrls: resourceUrls }, { channelId: context.activity.channelId }))._response.parsedBody as { [propertyName: string]: TokenResponse };
}
/**
* Asynchronously Get the raw signin resource to be sent to the user for signin.
*
* @param context The context object for the turn.
* @param connectionName The name of the auth connection to use.
* @param userId The user id that will be associated with the token.
* @param finalRedirect The final URL that the OAuth flow will redirect to.
*
* @returns The [BotSignInGetSignInResourceResponse](xref:botframework-connector.BotSignInGetSignInResourceResponse) object.
*/
public async getSignInResource(context: TurnContext, connectionName: string, userId?: string, finalRedirect?: string, appCredentials?: AppCredentials): Promise<SignInUrlResponse> {
if (!connectionName) {
throw new Error('getUserToken() requires a connectionName but none was provided.');
}
if (!context.activity.from || !context.activity.from.id) {
throw new Error(`CustomWebAdapter.getSignInResource(): missing from or from.id`);
}
// what to do when userId is null (same for finalRedirect)
if (userId && context.activity.from.id != userId) {
throw new Error('CustomWebAdapter.getSiginInResource(): cannot get signin resource for a user that is different from the conversation');
}
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, appCredentials);
const conversation: Partial<ConversationReference> = TurnContext.getConversationReference(context.activity);
const state: any = {
ConnectionName: connectionName,
Conversation: conversation,
relatesTo: context.activity.relatesTo,
MSAppId: (client.credentials as AppCredentials).appId
};
const finalState: string = Buffer.from(JSON.stringify(state)).toString('base64');
const options: TokenApiModels.BotSignInGetSignInResourceOptionalParams = { finalRedirect: finalRedirect };
return await (client.botSignIn.getSignInResource(finalState, options));
}
/**
* Asynchronously Performs a token exchange operation such as for single sign-on.
* @param context Context for the current turn of conversation with the user.
* @param connectionName Name of the auth connection to use.
* @param userId The user id that will be associated with the token.
* @param tokenExchangeRequest The exchange request details, either a token to exchange or a uri to exchange.
*/
public async exchangeToken(context: TurnContext, connectionName: string, userId: string, tokenExchangeRequest: TokenExchangeRequest, appCredentials?: AppCredentials): Promise<TokenResponse> {
if (!connectionName) {
throw new Error('exchangeToken() requires a connectionName but none was provided.');
}
if (!userId) {
throw new Error('exchangeToken() requires an userId but none was provided.');
}
if (tokenExchangeRequest && !tokenExchangeRequest.token && !tokenExchangeRequest.uri) {
throw new Error('CustomWebAdapter.exchangeToken(): Either a Token or Uri property is required on the TokenExchangeRequest');
}
const url: string = this.oauthApiUrl(context);
const client: TokenApiClient = this.createTokenApiClient(url, appCredentials);
return (await client.userToken.exchangeAsync(userId, connectionName, context.activity.channelId, tokenExchangeRequest))._response.parsedBody as TokenResponse;
}
/**
* Creates an OAuth API client.
*
* @param serviceUrl The client's service URL.
* @param oAuthAppCredentials AppCredentials for OAuth.
*
* @remarks
* Override this in a derived class to create a mock OAuth API client for unit testing.
*/
protected createTokenApiClient(serviceUrl: string, oAuthAppCredentials: AppCredentials): TokenApiClient {
const tokenApiClientCredentials = oAuthAppCredentials ? oAuthAppCredentials : this.credentials;
const client = new TokenApiClient(tokenApiClientCredentials, { baseUri: serviceUrl, userAgent: USER_AGENT });
return client;
}
/**
* Gets the OAuth API endpoint.
*
* @param contextOrServiceUrl The URL of the channel server to query or
* a [TurnContext](xref:botbuilder-core.TurnContext). For a turn context, the context's
* [activity](xref:botbuilder-core.TurnContext.activity).[serviceUrl](xref:botframework-schema.Activity.serviceUrl)
* is used for the URL.
*
* @remarks
* Override this in a derived class to create a mock OAuth API endpoint for unit testing.
*/
protected oauthApiUrl(contextOrServiceUrl: TurnContext | string): string {
const isEmulatingOAuthCards = false;
return isEmulatingOAuthCards ?
(typeof contextOrServiceUrl === 'object' ? contextOrServiceUrl.activity.serviceUrl : contextOrServiceUrl) :
(this.oAuthSettings.oAuthEndpoint ? this.oAuthSettings.oAuthEndpoint :
JwtTokenValidation.isGovernment(this.oAuthSettings.channelService) ?
US_GOV_OAUTH_ENDPOINT : OAUTH_ENDPOINT);
}
} | the_stack |
export type AccountMigrationEvent = UkCoBoostpowerSupportKafkaMessages.AccountMigrationEvent;
export namespace ComOvoenergyKafkaCommonEvent {
export const EventMetadataName = "com.ovoenergy.kafka.common.event.EventMetadata";
/**
* Metadata, to be used in each event class
*/
export interface EventMetadata {
/**
* A globally unique ID for this Kafka message
*/
eventId: string;
/**
* An ID that can be used to link all the requests and Kafka messages in a given transaction. If you already have a trace token from a previous event/request, you should copy it here. If this is the very start of a transaction, you should generate a fresh trace token and put it here. A UUID is suitable
*/
traceToken: string;
/**
* A timestamp for when the event was created (in epoch millis)
*/
createdAt: number;
}
}
export namespace UkCoBoostpowerSupportKafkaMessages {
export const AccountMigrationCancelledEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent";
/**
* Triggered by Migration Service. Before T2 signals that a siemens account migration has been cancelled. Migration is about to be restarted for the same account that means a new AccountMigrationScheduledEvent with a new flow id will be sent.Consumers should not react on this in normal case.
*/
export interface AccountMigrationCancelledEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The unique national reference for Meter Point Administration Number
*/
mpan: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* Because dates as Decimal are the best!
*/
effectiveEnrollmentDateAsDecimal: number;
/**
* The time when the migration was cancelled (in epoch millis)
*/
cancelledAt: number;
}
export const AccountMigrationCompletedEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent";
/**
* Triggered by SMILE. After SMILE processed the AccountMigrationValidatedEvent and switched over to Billy from Siemens they trigger this event to inform consumers like BIT CSA portal and Salesforce to do the necessary steps for the switchover
*/
export interface AccountMigrationCompletedEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the migration was completed (in epoch millis)
*/
completedAt: number;
}
export const AccountMigrationRollBackInitiatedEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent";
/**
* Triggered by Migration Service. After T2 it signals that a siemens account migration roll back was initiated. SMILE should change the data master system for the account from Billy to Siemens and inform other system about the result.
*/
export interface AccountMigrationRollBackInitiatedEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the migration rollback was initiated (in epoch millis)
*/
rollBackInitiatedAt: number;
}
export const AccountMigrationRolledBackEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent";
/**
* Triggered by SMILE. As the response to the AccountMigrationRollBackInitiatedEvent, SMILE indicates that mastering system for account data has been restored to be Siemens.As an action to this Billy, BIT CSA portal and Salesforce can do the necessary steps to clean up internal data and switch over to use Siemens data.
*/
export interface AccountMigrationRolledBackEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the migration was rolled back (in epoch millis)
*/
rolledBackAt: number;
}
export const AccountMigrationScheduledEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent";
/**
* Triggered by Migration Service. At T-2 it signals that a siemens account migration has been scheduled for T0 (effectiveEnrollmentDate).Consumers should do the necessary steps like removing primary card functionality in PAYG account service. If consumers see a new AccountMigrationScheduledEvent with a new flow id then they have to update their internal state with the new flow id since every subsequent message in the migration flow will use the same id
*/
export interface AccountMigrationScheduledEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The unique national reference for Meter Point Administration Number
*/
mpan: string;
/**
* The date when the customer came on supply with Boost (in epoch days)
*/
supplyStartDate: number;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the migration was scheduled (in epoch millis)
*/
scheduledAt: number;
}
export const AccountMigrationValidatedEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent";
/**
* Triggered by Balance Service. At T2 it signals that a siemens balance and transaction history was migrated to the new balance platform and the validation was successful. Billy is ready to be the source for balance and transaction history data. SMILE should change the data master system for the account from Siemens to Billy and inform other system about the result
*/
export interface AccountMigrationValidatedEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the migrated balance and transactions were validated (in epoch millis)
*/
validatedAt: number;
}
export const BalanceRetrievedMigrationEventName = "uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent";
/**
* Triggered by Migration Service. At T1 signals that a siemens balance and transaction history is available for Billy. Contains details.
*/
export interface BalanceRetrievedMigrationEvent {
metadata: ComOvoenergyKafkaCommonEvent.EventMetadata;
/**
* Globally unique identifier for the enrollment
*/
enrollmentId: string;
/**
* Unique identifier for the customer. GentrackId/SiemensId. Usually 7 digits.
*/
accountId: string;
/**
* The unique national reference for Meter Point Administration Number
*/
mpan: string;
/**
* The date when the account is going to be enrolled for the new balance platform (in epoch days)
*/
effectiveEnrollmentDate: number;
/**
* The time when the balance and transaction history was fetched (in epoch millis)
*/
retrievedAt: number;
}
export const AccountMigrationEventName = "uk.co.boostpower.support.kafka.messages.AccountMigrationEvent";
/**
* Account migration related events. It describes several flows: 1. Happy path: AccountMigrationScheduledEvent -> BalanceRetrievedMigrationEvent -> AccountMigrationValidatedEvent -> AccountMigrationCompletedEvent 2. Cancel where the migration is about the be restarted: AccountMigrationScheduledEvent -> BalanceRetrievedMigrationEvent -> AccountMigrationCancelledEvent -> Start from the beginning, AccountMigrationScheduledEvent -> AccountMigrationCancelledEvent -> Start from the beginning 3. Rollback: AccountMigrationScheduledEvent -> BalanceRetrievedMigrationEvent -> AccountMigrationValidatedEvent -> AccountMigrationCompletedEvent -> AccountMigrationRollBackInitiatedEvent -> AccountMigrationRolledBackEvent -> Start from the beginning AccountMigrationScheduledEvent generates a flow id which is used in every subsequent migration message to be grouped together
*/
export interface AccountMigrationEvent {
event: {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationCancelledEvent;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationCompletedEvent;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationRollBackInitiatedEvent;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationRolledBackEvent;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationScheduledEvent;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent": UkCoBoostpowerSupportKafkaMessages.AccountMigrationValidatedEvent;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent"?: never;
} | {
"uk.co.boostpower.support.kafka.messages.AccountMigrationCancelledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationCompletedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRollBackInitiatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationRolledBackEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationScheduledEvent"?: never;
"uk.co.boostpower.support.kafka.messages.AccountMigrationValidatedEvent"?: never;
"uk.co.boostpower.support.kafka.messages.BalanceRetrievedMigrationEvent": UkCoBoostpowerSupportKafkaMessages.BalanceRetrievedMigrationEvent;
};
}
} | the_stack |
import * as baseQueue from '../queue/queue';
// The |QueueFeeder| is the abstraction for events to be handled.
export interface QueueFeeder<Feed,Result> {
// Number of things in the queue to be handled.
getLength() : number;
// Called by code that wants |x| to be handled. Returns a promise for
// when |x| is handled. Queues |x| until it can be handled.
handle(x:Feed) : Promise<Result>;
}
// The |HandlerQueueStats| class contains increment-only counters
// characterizing the state and history of a |QueueHandler|.
export class HandlerQueueStats {
// Total events ever input by the HandlerQueue. Intent:
//
// queued_events + immediately_handled_events + rejected_events =
// total_events.
//
// queued_events - queued_handled_events - rejected_events = number
// of events in queue right now.
total_events : number = 0;
// Ever-queued-events
queued_events : number = 0;
// Events that were immediately handled (b/c there was a handler set).
immediately_handled_events : number = 0;
// Events that were handled after going through the queue.
queued_handled_events : number = 0;
// Number of events rejected in a queue clear.
rejected_events : number = 0;
// Number of times a handler was set on this queue (the handler was
// previously null).
handler_set_count : number = 0;
// Number of times a handler was changed on this queue (the handler
// was previously non-null).
handler_change_count : number = 0;
// Number of times a handler was un-set on this queue (when then
// handler previously non-null).
handler_clear_count : number = 0;
// Number of times we set a new handler while we have an existing
// promise, causing a rejection of that promise.
handler_rejections : number = 0;
}
// The |QueueHandler| is the abstraction for the stream of functions that
// handles events.
export interface QueueHandler<Feed,Result> {
// Clears the queue, and rejects promises for |handle| callers that added
// entries in the queue.
clear() : void;
// Number of things in the queue to be handled.
getLength() : number;
// The |setHandler|'s handler function |f| will be called on the next element
// until the queue is empty or the handler itself is changed (e.g. if
// |stopHandling()| is called while handling an event then further events
// will be queued until a new handler is set).
setHandler(f:(x:Feed) => Promise<Result>) : void;
// As above, but takes a sync function handler.
setSyncHandler(f:(x:Feed) => Result) : void;
// Sets the next function to handle something in the handler queue. Returns
// a promise for the result of the next handled event in the queue. Note: if
// the queue is empty, the promise resolves the next time `handle` is called
// (assuming by then the queue isn't stopped or handler changed by then).
setNextHandler(f:(x:Feed) => Promise<Result>) : Promise<Result>;
// As above, but takes a sync handler.
setSyncNextHandler(f:(x:Feed) => Result) : Promise<Result>;
// Returns true if on of the |set*| functions has been called but
// |stopHandling| has not. Returns false after |stopHandling| has been
// called.
isHandling() : boolean;
// The queue stops being handled and all future that |handle| is called on
// are queued. If |setSyncNextHandler| or |setAsyncNextHandler| has been
// called, then its return promise is rejected.
stopHandling() : void;
// Get statistics on queue handler.
getStats() : HandlerQueueStats;
}
// Internal helper class. Holds an object called |thing| of type |T| and
// provides a promise for a new result object of type |T2|. The idea is that
// |T2| is will be result of some async function applied to |thing|. This
// helper supports the function that gerates the new object to be known async
// (i.e. later), but still being able to promise a promise for the result
// immidiately.
//
// Assumes fulfill/reject are called exclusively and only once.
class PendingPromiseHandler<T,T2> {
public promise :Promise<T2>
private fulfill_ :(x:T2) => void;
private reject_ :(e:Error) => void;
private completed_ :boolean;
constructor(public thing:T) {
// This holds the T object, and fulfills with a T2 when fulfill is called
// with T2. The point is we can give back the promise now but fulfill can
// be called later.
this.promise = new Promise<T2>((F,R) => {
this.fulfill_ = F;
this.reject_ = R;
});
this.completed_ = false;
}
public reject = (e:Error) : void => {
if (this.completed_) {
console.error('reject must not be called on a completed promise.');
return;
}
this.completed_ = true;
this.reject_(e);
}
public handleWith = (handler:(x:T) => Promise<T2>) : void => {
if (this.completed_) {
console.error('handleWith must not be called on a completed promise.');
return;
}
this.completed_ = true;
handler(this.thing).then(this.fulfill_);
}
}
// The |Queue| class provides a |QueueFeeder| and a |QueueHandler|. The idea is
// that the QueueHandler processes inputs of type |Feed| from the |QueueFeeder|
// and gives back promises for objects of type |Result|. The handle function
// takes objects of type |Feed| and promises objects of type |Result| (the
// handler may run asynchonously).
//
// When the handler is set to |null|, objects are queued up to be handled. When
// the handler is set to not a non-null function, everything in the queue is
// handled by that function. There are some convenience functions for stopping
// Handling, and hanlding just the next event/element.
//
// CONSIDER: this is a kind of co-promise, and can probably be
// extended/generalized.
export class Queue<Feed,Result>
implements QueueFeeder<Feed,Result>, QueueHandler<Feed,Result> {
// The queue of things to handle.
private queue_ = new baseQueue.Queue<PendingPromiseHandler<Feed, Result>>();
// Handler function for things on the queue. When null, things queue up.
// When non-null, gets called on the thing to handle. When set, called on
// everything in the queue in FIFO order.
private handler_ :(x:Feed) => Promise<Result> = null;
// We store a handler's promise rejection function and call it when
// `setHandler` is called and we had a previously promised handler. We need
// to do this because the old handler would never fulfill the old promise as
// it is no longer attached.
private rejectFn_ : (e:Error) => void = null;
// Handler statistics.
private stats_ = new HandlerQueueStats();
// CONSIDER: allow queue to be size-bounded? Reject on too much stuff?
constructor() {}
public getLength = () : number => {
return this.queue_.length;
}
public isHandling = () : boolean => {
return this.handler_ !== null;
}
public getStats = () : HandlerQueueStats => {
return this.stats_;
}
// handle or queue the given thing.
public handle = (x:Feed) : Promise<Result> => {
this.stats_.total_events++;
if (this.handler_) {
this.stats_.immediately_handled_events++;
return this.handler_(x);
}
var pendingThing = new PendingPromiseHandler(x);
this.queue_.push(pendingThing);
this.stats_.queued_events++;
return pendingThing.promise;
}
// Run the handler function on the queue until queue is empty or handler is
// null. Note: a handler may itself setHandler to being null, doing so
// should pause proccessing of the queue.
private processQueue_ = () : void => {
while (this.handler_ && this.queue_.length > 0) {
this.stats_.queued_handled_events++;
this.queue_.shift().handleWith(this.handler_);
}
}
// Clears the queue, and rejects all promises to handle things on the queue.
public clear = () : void => {
while (this.queue_.length > 0) {
var pendingThing = this.queue_.shift();
this.stats_.rejected_events++;
pendingThing.reject(new Error('Cleared by Handler'));
}
}
// Calling setHandler with null pauses handling and queues all objects to be
// handled.
//
// If you have an unfulfilled promise, calling setHandler rejects the old
// promise.
public setHandler = (handler:(x:Feed) => Promise<Result>) : void => {
if (!handler) {
throw new Error('handler must not be null');
}
if (this.rejectFn_) {
this.stats_.handler_rejections++;
this.rejectFn_(new Error('Cancelled by a call to setHandler'));
this.rejectFn_ = null;
}
if (this.handler_ === null) {
this.stats_.handler_set_count++;
} else {
this.stats_.handler_change_count++;
}
this.handler_ = handler;
this.processQueue_();
}
// Convenience function for handler to be an ordinary function without a
// promise result.
public setSyncHandler = (handler:(x:Feed) => Result) : void => {
this.setHandler((x:Feed) => { return Promise.resolve(handler(x)); });
}
// Reject the previous promise handler if it exists and stop handling stuff.
public stopHandling = () => {
if (this.rejectFn_) {
this.stats_.handler_rejections++;
this.rejectFn_(new Error('Cancelled by a call to setHandler'));
this.rejectFn_ = null;
}
if (this.handler_) {
this.handler_ = null;
this.stats_.handler_clear_count++;
}
}
// A convenience function that takes a T => Promise<Result> function and sets
// the handler to a function that will return the promise for the next thing
// to handle and then unset the handler after that so that only the next
// thing in the queue is handled.
//
// Note: this sets the Handler to fulfill this promise when there is
// something to handle.
public setNextHandler = (handler:(x:Feed) => Promise<Result>)
: Promise<Result> => {
return new Promise((F,R) => {
this.setHandler((x:Feed) : Promise<Result> => {
// Note: we don't call stopHandling() within this handler because that
// would reject the promise we're about to fulfill.
this.handler_ = null;
this.rejectFn_ = null;
this.stats_.handler_clear_count++;
var resultPromise = handler(x);
resultPromise.then(F);
return resultPromise;
});
if (this.handler_) {
// If |handler| has not already run, and removed itself, leave a
// rejection function behind as well.
this.rejectFn_ = R;
}
});
}
// Convenience function for handling next element with an ordinary function.
public setSyncNextHandler = (handler:(x:Feed) => Result) : Promise<Result> => {
return this.setNextHandler((x:Feed) => {
return Promise.resolve(handler(x));
});
}
} // class Queue | the_stack |
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DebugElement } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, flushMicrotasks, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { of, throwError } from 'rxjs';
import { createDummies, dispatchFakeEvent, fastTestSetup, typeInElement } from '../../../../../test/helpers';
import { MockDialog, MockDialogRef } from '../../../../../test/mocks/browser';
import { VcsAccountDummy } from '../../../../core/dummies';
import { VcsAccount, VcsAuthenticationTypes, VcsPrimaryEmailNotExistsError } from '../../../../core/vcs';
import { ConfirmDialogComponent, ConfirmDialogData } from '../../../shared/confirm-dialog';
import { Dialog, DialogRef } from '../../../ui/dialog';
import { RadioButtonComponent } from '../../../ui/radio';
import { UiModule } from '../../../ui/ui.module';
import { VCS_ACCOUNT_DATABASE, VcsAccountDatabase, VcsAccountDatabaseProvider } from '../../vcs-account-database';
import { VcsAccountItemComponent } from '../../vcs-view';
import { VcsRemoteGithubProvider } from '../vcs-remote-github-provider';
import { VcsRemoteProviderFactory } from '../vcs-remote-provider-factory';
import { GithubAccountsDialogComponent } from './github-accounts-dialog.component';
import Spy = jasmine.Spy;
describe('browser.vcs.vcsAuthentication.GithubAccountsDialogComponent', () => {
let fixture: ComponentFixture<GithubAccountsDialogComponent>;
let component: GithubAccountsDialogComponent;
let mockDialog: MockDialog;
let mockDialogRef: MockDialogRef<GithubAccountsDialogComponent>;
let thisMockDialog: MockDialog;
let accountDB: VcsAccountDatabase;
let github: VcsRemoteGithubProvider;
const vcsAccountDummy = new VcsAccountDummy();
function makeAccountsToBeLoadedWith(
accounts: VcsAccount[] = createDummies(vcsAccountDummy, 5),
): VcsAccount[] {
// If it is already spy...
if ((accountDB.getAllAccounts as Spy).and) {
(accountDB.getAllAccounts as Spy).and.returnValue(Promise.resolve(accounts));
} else {
spyOn(accountDB, 'getAllAccounts').and.returnValue(Promise.resolve(accounts));
}
return accounts;
}
function switchAuthMethodOption(type: VcsAuthenticationTypes): void {
const options = fixture.debugElement.queryAll(By.directive(RadioButtonComponent));
const option = options.find(opt => opt.componentInstance.value === type);
if (option) {
const inputEl = option.query(By.css('input[type=radio]'));
dispatchFakeEvent(inputEl.nativeElement, 'change');
fixture.detectChanges();
}
}
const getAccountItemDeList = (): DebugElement[] => fixture.debugElement.queryAll(
By.css('.GithubAccountsDialog__accounts > gd-vcs-account-item'),
);
const getUserNameInputEl = (): HTMLInputElement =>
fixture.debugElement.query(By.css('#github-username-input')).nativeElement as HTMLInputElement;
const getPasswordInputEl = (): HTMLInputElement =>
fixture.debugElement.query(By.css('#github-password-input')).nativeElement as HTMLInputElement;
const getTokenInputEl = (): HTMLInputElement =>
fixture.debugElement.query(By.css('#github-token-input')).nativeElement as HTMLInputElement;
const getLoginAndAddAccountButtonEl = (): HTMLButtonElement =>
fixture.debugElement.query(
By.css('.GithubAccountsDialog__loginAndAddAccountButton'),
).nativeElement as HTMLButtonElement;
fastTestSetup();
beforeAll(async () => {
mockDialog = new MockDialog();
mockDialogRef = new MockDialogRef(mockDialog, GithubAccountsDialogComponent);
thisMockDialog = new MockDialog();
await TestBed
.configureTestingModule({
imports: [
UiModule,
HttpClientTestingModule,
NoopAnimationsModule,
],
providers: [
{ provide: DialogRef, useValue: mockDialogRef },
VcsRemoteProviderFactory,
VcsAccountDatabaseProvider,
],
declarations: [
VcsAccountItemComponent,
GithubAccountsDialogComponent,
],
})
.overrideComponent(GithubAccountsDialogComponent, {
set: {
providers: [{ provide: Dialog, useValue: thisMockDialog }],
},
})
.compileComponents();
});
beforeEach(() => {
accountDB = TestBed.get(VCS_ACCOUNT_DATABASE);
fixture = TestBed.createComponent(GithubAccountsDialogComponent);
component = fixture.componentInstance;
github = component['github'];
});
afterEach(async () => {
thisMockDialog.closeAll();
await accountDB.accounts.clear();
});
describe('accounts list', () => {
it('should load accounts from account database and show in the list.', fakeAsync(() => {
const accounts = makeAccountsToBeLoadedWith();
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
fixture.whenStable().then(() => fixture.detectChanges());
flush();
const itemDeList = getAccountItemDeList();
expect(itemDeList.length).toEqual(accounts.length);
itemDeList.forEach((itemDe, index) => {
expect((itemDe.componentInstance as VcsAccountItemComponent).account).toEqual(accounts[index]);
});
}));
it('should show empty state if there are not accounts exists.', fakeAsync(() => {
makeAccountsToBeLoadedWith([]);
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.GithubAccountsDialog__emptyState'))).not.toBeNull();
}));
// TODO(@seokju-na): Cannot test focus key manager.
// For some reason, a '1 timer(s) run in the queue' error occurs when I dispatch the key event.
// I think we should research this area when we can afford it later.
});
describe('accounts tools', () => {
it('should remove account and reload accounts when click remove account button.', fakeAsync(() => {
makeAccountsToBeLoadedWith();
fixture.detectChanges();
flush();
fixture.detectChanges();
// Next load
spyOn(accountDB, 'deleteAccountByEmail').and.callThrough();
makeAccountsToBeLoadedWith(createDummies(vcsAccountDummy, 4));
const target = getAccountItemDeList()[1];
(target.componentInstance as VcsAccountItemComponent).removeThis.emit();
flushMicrotasks();
fixture.detectChanges();
expect(accountDB.deleteAccountByEmail)
.toHaveBeenCalledWith((target.componentInstance as VcsAccountItemComponent).account.email);
}));
});
describe('login and add account form', () => {
it('should authorize with basic and add account. After add new account completes, '
+ 'should reset form.', fakeAsync(() => {
makeAccountsToBeLoadedWith();
fixture.detectChanges();
flush();
fixture.detectChanges();
switchAuthMethodOption(VcsAuthenticationTypes.BASIC);
typeInElement('username', getUserNameInputEl());
typeInElement('password', getPasswordInputEl());
fixture.detectChanges();
const newAccount = vcsAccountDummy.create(VcsAuthenticationTypes.BASIC);
spyOn(github, 'authorizeByBasic').and.returnValue(of(newAccount));
spyOn(accountDB, 'addNewAccount').and.callThrough();
getLoginAndAddAccountButtonEl().click();
fixture.detectChanges();
expect(github.authorizeByBasic).toHaveBeenCalledWith('username', 'password');
expect(accountDB.addNewAccount).toHaveBeenCalledWith(newAccount);
// Should form reset
expect(component.addAccountFormGroup.value).toEqual({
type: VcsAuthenticationTypes.BASIC,
userName: '',
password: '',
token: '',
});
}));
it('should authorize with oauth2 token and add account. After add new account completes, '
+ 'should reset form.', fakeAsync(() => {
makeAccountsToBeLoadedWith();
fixture.detectChanges();
flush();
fixture.detectChanges();
switchAuthMethodOption(VcsAuthenticationTypes.OAUTH2_TOKEN);
typeInElement('token', getTokenInputEl());
fixture.detectChanges();
const newAccount = vcsAccountDummy.create(VcsAuthenticationTypes.OAUTH2_TOKEN);
spyOn(github, 'authorizeByOauth2Token').and.returnValue(of(newAccount));
spyOn(accountDB, 'addNewAccount').and.callThrough();
getLoginAndAddAccountButtonEl().click();
fixture.detectChanges();
expect(github.authorizeByOauth2Token).toHaveBeenCalledWith('token');
expect(accountDB.addNewAccount).toHaveBeenCalledWith(newAccount);
// Should form reset
expect(component.addAccountFormGroup.value).toEqual({
type: VcsAuthenticationTypes.OAUTH2_TOKEN,
userName: '',
password: '',
token: '',
});
}));
it('should get primary email when user does not has email.', fakeAsync(() => {
makeAccountsToBeLoadedWith();
fixture.detectChanges();
flush();
fixture.detectChanges();
switchAuthMethodOption(VcsAuthenticationTypes.OAUTH2_TOKEN);
typeInElement('token', getTokenInputEl());
fixture.detectChanges();
const newAccount: VcsAccount = {
...vcsAccountDummy.create(VcsAuthenticationTypes.OAUTH2_TOKEN),
email: null,
};
spyOn(github, 'authorizeByOauth2Token').and.returnValue(of(newAccount));
spyOn(github, 'getPrimaryEmail').and.returnValue(of('test@test.com'));
spyOn(accountDB, 'addNewAccount').and.callThrough();
getLoginAndAddAccountButtonEl().click();
fixture.detectChanges();
expect(github.authorizeByOauth2Token).toHaveBeenCalledWith('token');
expect(github.getPrimaryEmail).toHaveBeenCalledWith(newAccount.authentication);
expect(accountDB.addNewAccount).toHaveBeenCalledWith({
...newAccount,
email: 'test@test.com',
} as VcsAccount);
}));
it('should open alert when \'VcsPrimaryEmailNotExists\' exception thrown.', fakeAsync(() => {
makeAccountsToBeLoadedWith();
fixture.detectChanges();
flush();
fixture.detectChanges();
switchAuthMethodOption(VcsAuthenticationTypes.OAUTH2_TOKEN);
typeInElement('token', getTokenInputEl());
fixture.detectChanges();
const newAccount: VcsAccount = {
...vcsAccountDummy.create(VcsAuthenticationTypes.OAUTH2_TOKEN),
email: null,
};
spyOn(github, 'authorizeByOauth2Token').and.returnValue(of(newAccount));
spyOn(github, 'getPrimaryEmail').and.returnValue(throwError(new VcsPrimaryEmailNotExistsError()));
getLoginAndAddAccountButtonEl().click();
fixture.detectChanges();
const alert = thisMockDialog.getByComponent<ConfirmDialogComponent,
ConfirmDialogData,
boolean>(
ConfirmDialogComponent,
);
expect(alert).toBeDefined();
expect(alert.config.data.title).toEqual('Cannot read email from github.com');
expect(alert.config.data.isAlert).toEqual(true);
}));
});
}); | the_stack |
import React, { FunctionComponent, useEffect, useMemo, useState } from "react";
import {
Keyboard,
KeyboardEvent,
Platform,
StyleSheet,
Text,
View,
ViewStyle,
} from "react-native";
import { useStyle } from "../../styles";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { PanGestureHandler } from "react-native-gesture-handler";
import { useModalState, useModalTransision } from "../base";
import Animated, { Easing } from "react-native-reanimated";
import {
DefaultAcceleration,
DefaultCloseVelocity,
DefaultOpenVelocity,
} from "../base/const";
const useAnimatedValueSet = () => {
const [state] = useState(() => {
return {
clock: new Animated.Clock(),
finished: new Animated.Value(0),
time: new Animated.Value(0),
frameTime: new Animated.Value(0),
value: new Animated.Value(0),
};
});
return state;
};
// CONTRACT: Use with { disableSafeArea: true, align: "bottom" } modal options.
export const CardModal: FunctionComponent<{
title?: string;
right?: React.ReactElement;
childrenContainerStyle?: ViewStyle;
disableGesture?: boolean;
}> = ({
title,
right,
children,
childrenContainerStyle,
disableGesture = false,
}) => {
const style = useStyle();
const safeAreaInsets = useSafeAreaInsets();
const [
softwareKeyboardBottomPadding,
setSoftwareKeyboardBottomPadding,
] = useState(0);
useEffect(() => {
const onKeyboarFrame = (e: KeyboardEvent) => {
setSoftwareKeyboardBottomPadding(
e.endCoordinates.height - safeAreaInsets.bottom
);
};
const onKeyboardClearFrame = () => {
setSoftwareKeyboardBottomPadding(0);
};
// No need to do this on android
if (Platform.OS !== "android") {
Keyboard.addListener("keyboardWillShow", onKeyboarFrame);
Keyboard.addListener("keyboardWillChangeFrame", onKeyboarFrame);
Keyboard.addListener("keyboardWillHide", onKeyboardClearFrame);
return () => {
Keyboard.removeListener("keyboardWillShow", onKeyboarFrame);
Keyboard.removeListener("keyboardWillChangeFrame", onKeyboarFrame);
Keyboard.removeListener("keyboardWillHide", onKeyboardClearFrame);
};
}
}, [safeAreaInsets.bottom]);
const animatedValueSet = useAnimatedValueSet();
const modal = useModalState();
const modalTransition = useModalTransision();
const animatedKeyboardPaddingBottom = useMemo(() => {
return Animated.block([
Animated.cond(
Animated.and(
Animated.neq(animatedValueSet.value, softwareKeyboardBottomPadding),
Animated.not(Animated.clockRunning(animatedValueSet.clock))
),
[
Animated.debug(
"start clock for keyboard avoiding",
animatedValueSet.value
),
Animated.set(animatedValueSet.finished, 0),
Animated.set(animatedValueSet.time, 0),
Animated.set(animatedValueSet.frameTime, 0),
Animated.startClock(animatedValueSet.clock),
]
),
Animated.timing(
animatedValueSet.clock,
{
finished: animatedValueSet.finished,
position: animatedValueSet.value,
time: animatedValueSet.time,
frameTime: animatedValueSet.frameTime,
},
{
toValue: softwareKeyboardBottomPadding,
duration: 175,
easing: Easing.linear,
}
),
Animated.cond(
animatedValueSet.finished,
Animated.stopClock(animatedValueSet.clock)
),
animatedValueSet.value,
]);
}, [
animatedValueSet.clock,
animatedValueSet.finished,
animatedValueSet.frameTime,
animatedValueSet.time,
animatedValueSet.value,
softwareKeyboardBottomPadding,
]);
const [startTranslateY] = useState(() => new Animated.Value(0));
const [openVelocityValue] = useState(() => new Animated.Value(0));
const [closeVelocityValue] = useState(() => new Animated.Value(0));
const [velocityYAcceleration] = useState(() => new Animated.Value(1));
const onGestureEvent = useMemo(() => {
const openVelocity =
modal.openTransitionVelocity ??
modal.transitionVelocity ??
DefaultOpenVelocity;
const closeVelocity =
modal.closeTransitionVelocity ??
modal.transitionVelocity ??
DefaultCloseVelocity;
const acceleration = modal.transitionAcceleration ?? DefaultAcceleration;
return Animated.event([
{
nativeEvent: ({
velocityY,
translationY,
state,
}: {
velocityY: number;
translationY: number;
state: number;
}) => {
return Animated.block([
Animated.cond(
// Check that the state is BEGEN or ACTIVE.
Animated.and(
Animated.or(Animated.eq(state, 2), Animated.eq(state, 4)),
modalTransition.isOpen
),
[
// When the tocuh is active, but the "isPaused" is 0, it would be the case that the status is changed and first enter.
// So, this time is enough to set the starting translation Y position.
Animated.cond(
modalTransition.isPaused,
0,
Animated.set(startTranslateY, modalTransition.translateY)
),
// If touch is active, set the "isPaused" as 1 to prevent the transition.
Animated.set(modalTransition.isPaused, 1),
// Set the translationY on the modal transition.
Animated.set(
modalTransition.translateY,
Animated.add(startTranslateY, translationY)
),
// TranslationY on the modal transition can be negative.
Animated.cond(
Animated.lessOrEq(modalTransition.translateY, 0),
Animated.set(modalTransition.translateY, 0)
),
// Set the velocityYAcceleration
Animated.set(
velocityYAcceleration,
// velocityYAcceleration should be between 1 ~ 2.
// And, velocityYAcceleration is the velocityY / 1750
Animated.max(
1,
Animated.min(
2,
Animated.divide(Animated.abs(velocityY), 1750)
)
)
),
],
// If the status is not active, and the "isPaused" is not yet changed to the 1,
// it means that the it is the first time from the status is changed.
Animated.cond(modalTransition.isPaused, [
// If the remaining closing translateY (startY - translateY) is lesser or equal than 250,
// or "velocityY" from gesture is greater or equal than 100, try to close the modal.
// Else, just return to the open status.
Animated.cond(
Animated.not(
Animated.or(
Animated.and(
Animated.lessOrEq(
Animated.abs(
Animated.sub(
modalTransition.translateY,
modalTransition.startY
)
),
250
),
Animated.greaterOrEq(velocityY, -30)
),
Animated.greaterOrEq(velocityY, 100)
)
),
[
[
Animated.stopClock(modalTransition.clock),
Animated.set(modalTransition.finished, 0),
Animated.set(modalTransition.time, 0),
// No need to set.
// Animated.set(modalTransition.translateY, transition.startY),
Animated.set(modalTransition.frameTime, 0),
Animated.startClock(modalTransition.clock),
],
// Set the duration
Animated.cond(
Animated.greaterThan(openVelocity, 0),
[
Animated.set(
openVelocityValue,
Animated.max(
openVelocity,
Animated.multiply(
openVelocity,
Animated.pow(
acceleration,
Animated.divide(
Animated.abs(modalTransition.translateY),
100
)
)
)
)
),
Animated.set(
openVelocityValue,
Animated.multiply(
openVelocityValue,
velocityYAcceleration
)
),
Animated.debug(
"velocityYAcceleration",
velocityYAcceleration
),
Animated.set(
modalTransition.duration,
Animated.multiply(
Animated.divide(
Animated.abs(modalTransition.translateY),
openVelocityValue
),
1000
)
),
],
Animated.set(modalTransition.duration, 0)
),
Animated.set(modalTransition.durationSetOnExternal, 1),
Animated.set(modalTransition.isOpen, 1),
],
[
[
Animated.stopClock(modalTransition.clock),
Animated.set(modalTransition.finished, 0),
Animated.set(modalTransition.time, 0),
// No need to set.
// Animated.set(modalTransition.translateY, transition.startY),
Animated.set(modalTransition.frameTime, 0),
Animated.startClock(modalTransition.clock),
],
// Set the duration
Animated.cond(
Animated.greaterThan(closeVelocity, 0),
[
Animated.set(
closeVelocityValue,
Animated.max(
closeVelocity,
Animated.multiply(
closeVelocity,
Animated.pow(
acceleration,
Animated.divide(
Animated.abs(
Animated.sub(
modalTransition.translateY,
modalTransition.startY
)
),
100
)
)
)
)
),
Animated.set(
closeVelocityValue,
Animated.multiply(
closeVelocityValue,
velocityYAcceleration
)
),
Animated.debug(
"velocityYAcceleration",
velocityYAcceleration
),
Animated.set(
modalTransition.duration,
Animated.multiply(
Animated.divide(
Animated.abs(
Animated.sub(
modalTransition.translateY,
modalTransition.startY
)
),
closeVelocityValue
),
1000
)
),
],
Animated.set(modalTransition.duration, 0)
),
Animated.set(modalTransition.durationSetOnExternal, 1),
Animated.set(modalTransition.isOpen, 0),
Animated.call([], () => {
modal.close();
}),
]
),
Animated.set(modalTransition.isPaused, 0),
])
),
]);
},
},
]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
modal.close,
modal.closeTransitionVelocity,
modal.openTransitionVelocity,
modal.transitionVelocity,
modalTransition.clock,
modalTransition.duration,
modalTransition.finished,
modalTransition.frameTime,
modalTransition.isOpen,
modalTransition.isPaused,
modalTransition.time,
modalTransition.translateY,
modalTransition.startY,
startTranslateY,
]);
return (
<Animated.View
style={StyleSheet.flatten([
style.flatten([
"background-color-white",
"border-radius-top-left-8",
"border-radius-top-right-8",
"overflow-hidden",
]),
{
paddingBottom: Animated.add(
safeAreaInsets.bottom,
animatedKeyboardPaddingBottom
),
},
])}
>
<PanGestureHandler
onGestureEvent={onGestureEvent}
onHandlerStateChange={onGestureEvent}
enabled={!disableGesture}
>
{/* Below view is not animated, but to let the gesture handler to accept the animated block, you should set the children of the gesture handler as the Animated.View */}
<Animated.View style={style.flatten(["padding-x-page"])}>
<View style={style.flatten(["items-center", "margin-bottom-16"])}>
{!disableGesture ? (
<View
style={style.flatten([
"margin-top-8",
"width-58",
"height-5",
"border-radius-16",
"background-color-card-modal-handle",
])}
/>
) : null}
</View>
{title ? (
<React.Fragment>
<View
style={style.flatten([
"flex-row",
"items-center",
"margin-bottom-16",
])}
>
<Text style={style.flatten(["h4", "color-text-black-high"])}>
{title}
</Text>
{right}
</View>
<View
style={style.flatten([
"height-1",
"background-color-border-white",
])}
/>
</React.Fragment>
) : null}
</Animated.View>
</PanGestureHandler>
<View
style={StyleSheet.flatten([
style.flatten(["padding-page", "padding-top-16"]),
childrenContainerStyle,
])}
>
{children}
</View>
</Animated.View>
);
}; | the_stack |
import { SpreadsheetHelper } from '../util/spreadsheethelper.spec';
import { defaultData } from '../util/datasource.spec';
import { CellModel, getCell, SpreadsheetModel, Spreadsheet } from '../../../src/index';
/**
* Spreadsheet Ribbon spec
*/
describe('Spreadsheet Ribbon integration module ->', (): void => {
let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet');
let model: SpreadsheetModel;
describe('Public method ->', (): void => {
beforeAll((done: Function) => {
model = {
sheets: [
{
ranges: [{ dataSource: defaultData }]
}
]
};
helper.initializeSpreadsheet(model, done);
});
afterAll((): void => {
helper.invoke('destroy');
});
it('Enable & Disable ribbon tab', (done: Function): void => {
helper.invoke('enableRibbonTabs', [['Home', 'Data'], false]);
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[2].classList).toContain('e-overlay');
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[5].classList).toContain('e-overlay');
helper.invoke('enableRibbonTabs', [['Home', 'Data']]);
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[2].classList).not.toContain('e-overlay');
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[5].classList).not.toContain('e-overlay');
done();
});
it('Hide & show ribbon tab', (done: Function): void => {
helper.invoke('hideRibbonTabs', [['Insert', 'View']]);
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[3].classList).toContain('e-hide');
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[6].classList).toContain('e-hide');
helper.invoke('hideRibbonTabs', [['Insert', 'View'], false]);
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[3].classList).not.toContain('e-hide');
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-toolbar-items').children[6].classList).not.toContain('e-hide');
done();
});
it('Enable & Disable toolbar items', (done: Function): void => {
helper.invoke('enableToolbarItems', ['Home', ['spreadsheet_cut'], false]); // Check this now
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[3].classList).toContain('e-overlay');
helper.invoke('enableToolbarItems', ['Home', ['spreadsheet_cut']]);
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[3].classList).not.toContain('e-overlay');
done();
});
it('Hide & Show toolbar items', (done: Function): void => {
helper.invoke('hideToolbarItems', ['Home', [4, 7]]); // Check this now
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[4].classList).toContain('e-hide');
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[7].classList).toContain('e-hide');
helper.invoke('hideToolbarItems', ['Home', [4, 7], false]);
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[4].classList).not.toContain('e-hide');
// expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items').children[7].classList).not.toContain('e-hide');
done();
});
it('Enable & Disable File menu items', (done: Function): void => {
helper.invoke('enableFileMenuItems', [['File'], false]);
expect(helper.getElementFromSpreadsheet('.e-ribbon #' + helper.id + '_File').classList).toContain('e-disabled');
helper.invoke('enableFileMenuItems', [['File']]);
expect(helper.getElementFromSpreadsheet('.e-ribbon #' + helper.id + '_File').classList).not.toContain('e-disabled');
done();
});
it('Hide & Show File menu items', (done: Function): void => {
helper.invoke('hideFileMenuItems', [['File']]);
expect(helper.getElementFromSpreadsheet('.e-ribbon #' + helper.id + '_File').classList).toContain('e-menu-hide');
helper.invoke('hideFileMenuItems', [['File'], false]);
expect(helper.getElementFromSpreadsheet('.e-ribbon #' + helper.id + '_File').classList).not.toContain('e-menu-hide');
done();
});
it('Add File menu items', (done: Function): void => {
helper.invoke('addFileMenuItems', [[{ text: 'Print' }], 'Save As', false]);
helper.click('.e-ribbon #' + helper.id + '_File');
setTimeout(() => {
expect(helper.getElement('.e-menu-popup li:nth-child(3)').textContent).toBe('Print');
helper.click('.e-menu-popup li:nth-child(3)');
done();
});
});
});
describe('UI interaction checking ->', (): void => {
let instance: Spreadsheet;
beforeAll((done: Function) => {
model = {
sheets: [
{
ranges: [{ dataSource: defaultData }]
}
]
};
helper.initializeSpreadsheet(model, done);
instance = helper.getInstance();
});
afterAll((): void => {
helper.invoke('destroy');
});
it('Bold testing', (): void => {
helper.click('_bold');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontWeight).toEqual('bold'); // model checking
expect(instance.getCell(0, 0).style.fontWeight).toEqual('bold'); // dom checking
// for undo checking
helper.click('_undo');
expect(getCell(0, 0, instance.getActiveSheet()).style).toBeNull();
expect(instance.getCell(0, 0).style.fontWeight).toEqual('');
// for redo checking
helper.click('_redo');
expect(instance.getCell(0, 0).style.fontWeight).toEqual('bold');
// remove bold checking
helper.click('_bold');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontWeight).toEqual('normal');
expect(instance.getCell(0, 0).style.fontWeight).toEqual('normal');
});
it('Italic testing', (): void => {
helper.click('_italic');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontStyle).toEqual('italic');
expect(instance.getCell(0, 0).style.fontStyle).toEqual('italic');
// for undo checking
helper.click('_undo');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontWeight).toEqual('normal');
expect(instance.getCell(0, 0).style.fontStyle).toEqual('');
// for redo checking
helper.click('_redo');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontStyle).toEqual('italic');
expect(instance.getCell(0, 0).style.fontStyle).toEqual('italic');
// remove italic checking
helper.click('_italic');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontStyle).toEqual('normal');
expect(instance.getCell(0, 0).style.fontStyle).toEqual('normal');
});
it('StrikeThrough testing', (): void => {
helper.click('_line-through');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('line-through');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('line-through');
// for undo checking
helper.click('_undo');
expect(getCell(0, 0, instance.getActiveSheet()).style.fontStyle).toEqual('normal');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('');
// for redo checking
helper.click('_redo');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('line-through');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('line-through');
// remove line through checking
helper.click('_line-through');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('none');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('none');
});
it('Underline testing', (): void => {
helper.click('_underline');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline');
// for undo checking
helper.click('_undo');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('none');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('none');
// for redo checking
helper.click('_redo');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline');
// remove line through checking
helper.click('_underline');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('none');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('none');
});
it('Underline & StrikeThrough testing', (): void => {
helper.click('_underline');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline');
helper.click('_line-through');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline line-through');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline line-through');
// for undo checking
helper.click('_undo');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline');
// for redo checking
helper.click('_redo');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('underline line-through');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('underline line-through');
helper.click('_underline');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('line-through');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('line-through');
helper.click('_line-through');
expect(getCell(0, 0, instance.getActiveSheet()).style.textDecoration).toEqual('none');
expect(instance.getCell(0, 0).style.textDecoration).toEqual('none');
});
it('Cut testing', (done: Function) => {
helper.click('_bold');
helper.click('_italic');
helper.click('_underline');
helper.click('_cut');
setTimeout(() => {
helper.invoke('selectRange', ['K1']);
helper.click('_paste');
let cell: CellModel = getCell(0, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
//undo testing
helper.click('_undo');
cell = getCell(0, 10, instance.getActiveSheet());
expect(cell.value).toEqual('');
expect(cell.style).toBeNull();
done();
}, 100);
});
it('Cut-redo testing', (done: Function) => {
let cell: CellModel = getCell(0, 10, instance.getActiveSheet());
helper.click('_redo');
setTimeout(() => {
cell = getCell(0, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
done();
}, 10);
});
it('Copy testing', (done: Function) => {
helper.click('_copy');
setTimeout(() => {
helper.invoke('selectRange', ['K2']);
helper.click('_paste');
// Copied cell
let cell: CellModel = getCell(0, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
// Pasted the copied content cell
cell = getCell(1, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
//undo testing
helper.invoke('undo', null);
cell = getCell(1, 10, instance.getActiveSheet());
expect(cell.value).toEqual('');
expect(cell.style).toBeNull();
done();
}, 100);
});
it('Copy-redo testing', (done: Function) => {
let cell: CellModel = getCell(0, 10, instance.getActiveSheet());
helper.invoke('redo', null);
setTimeout(() => {
cell = getCell(1, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
done()
}, 10);
});
it('Paste testing', (): void => {
helper.invoke('selectRange', ['K3']);
helper.click('_paste');
let cell: CellModel = getCell(2, 10, instance.getActiveSheet());
expect(cell.value).toEqual('Item Name');
expect(cell.style.fontWeight).toEqual('bold');
expect(cell.style.fontStyle).toEqual('italic');
expect(cell.style.textDecoration).toEqual('underline');
});
it('Text color testing', (): void => {
helper.invoke('selectRange', ['K4']);
helper.click('_font_color_picker .e-split-btn');
expect(getCell(3, 10, instance.getActiveSheet()).style.color).toEqual('#000000');
helper.invoke('selectRange', ['K5']);
helper.click('_font_color_picker .e-dropdown-btn');
helper.click('.e-colorpicker-popup.e-popup-open span[aria-label="#ed7d31ff"]');
expect(getCell(4, 10, instance.getActiveSheet()).style.color).toEqual('#ed7d31');
// undo checking
helper.click('_undo');
expect(getCell(4, 10, instance.getActiveSheet()).style).toBeNull();
// redo checking
helper.click('_redo');
expect(getCell(4, 10, instance.getActiveSheet()).style.color).toEqual('#ed7d31');
});
it('Text color mode switcher testing', (): void => {
helper.invoke('selectRange', ['K6']);
helper.click('_font_color_picker .e-dropdown-btn');
helper.click('.e-colorpicker-popup.e-popup-open .e-switch-ctrl-btn button');
helper.click('.e-colorpicker-popup.e-popup-open .e-switch-ctrl-btn .e-apply');
expect(getCell(5, 10, instance.getActiveSheet()).style.color).toEqual('#ed7d31');
});
it('Fill color testing', (): void => {
helper.invoke('selectRange', ['K4']);
helper.click('_fill_color_picker .e-split-btn');
expect(getCell(3, 10, instance.getActiveSheet()).style.backgroundColor).toEqual('#ffff00');
helper.invoke('selectRange', ['K5']);
helper.click('_fill_color_picker .e-dropdown-btn');
helper.click('.e-colorpicker-popup.e-popup-open span[aria-label="#00ffffff"]');
expect(getCell(4, 10, instance.getActiveSheet()).style.backgroundColor).toEqual('#00ffff');
// undo checking
helper.click('_undo');
expect(getCell(4, 10, instance.getActiveSheet()).style.backgroundColor).toBeUndefined();
// redo checking
helper.click('_redo');
expect(getCell(4, 10, instance.getActiveSheet()).style.backgroundColor).toEqual('#00ffff');
});
it('Fill color mode switcher testing', (): void => {
helper.invoke('selectRange', ['K6']);
helper.click('_fill_color_picker .e-dropdown-btn');
helper.click('.e-colorpicker-popup.e-popup-open .e-switch-ctrl-btn button');
helper.click('.e-colorpicker-popup.e-popup-open .e-switch-ctrl-btn .e-apply');
expect(getCell(5, 10, instance.getActiveSheet()).style.backgroundColor).toEqual('#00ffff');
});
it('Font testing', (): void => {
helper.click('_font_name .e-btn-icon');
helper.click(`#${helper.id}_font_name-popup li:nth-child(2)`);
expect(getCell(5, 10, instance.getActiveSheet()).style.fontFamily).toEqual('Arial Black');
expect(instance.getCell(5, 10).style.fontFamily).toEqual('"Arial Black"');
expect(helper.getElement(`#${helper.id}_font_name .e-tbar-btn-text`).textContent).toEqual('Arial Black');
// undo checking
helper.click('_undo');
expect(getCell(5, 10, instance.getActiveSheet()).style.fontFamily).toBeUndefined();
// redo checking
helper.click('_redo');
expect(getCell(5, 10, instance.getActiveSheet()).style.fontFamily).toEqual('Arial Black');
});
it('Font testing', (): void => {
helper.click('_number_format .e-btn-icon');
helper.click(`#${helper.id}_number_format-popup li:nth-child(2)`);
expect(getCell(5, 10, instance.getActiveSheet()).format).toEqual('0.00');
// undo checking
helper.click('_undo');
expect(getCell(5, 10, instance.getActiveSheet()).format).toBeUndefined();
// redo checking
helper.click('_redo');
expect(getCell(5, 10, instance.getActiveSheet()).format).toEqual('0.00');
});
it('File Menu New testing', (done: Function) => {
setTimeout((): void => {
helper.click('.e-add-sheet-tab');
helper.click('.e-file-menu li');
setTimeout((): void => {
expect(helper.getElement('.e-menu-popup.e-file-menu')).not.toBeNull();
helper.click('.e-menu-popup.e-file-menu li[id="' + helper.id + '_New"]');
setTimeout((): void => {
helper.click('.e-dialog.e-popup-open button.e-primary');
setTimeout((): void => {
expect(helper.getInstance().sheets.length).toBe(1);
done();
}, 10);
}, 10);
}, 10);
}, 20);
});
//Checked for code coverage.
it('File Menu Open testing', (done: Function) => {
setTimeout(
(): void => {
let fileElem: HTMLInputElement = <HTMLInputElement>helper.getElementFromSpreadsheet('#spreadsheet_fileUpload')
let eventArg: Event = new Event('change');
fileElem.dispatchEvent(eventArg);
done();
},
20);
});
it('Collapse expand testing', (): void => {
expect(helper.getElement('.e-ribbon .e-drop-icon').title).toEqual('Collapse Toolbar');
helper.click('.e-ribbon .e-drop-icon');
expect(helper.hasClass('e-collapsed', helper.getRibbonElement())).toBeTruthy();
expect(helper.getElement('.e-ribbon .e-drop-icon').title).toEqual('Expand Toolbar');
helper.click('.e-ribbon .e-drop-icon');
expect(helper.hasClass('e-collapsed', helper.getRibbonElement())).toBeFalsy();
expect(helper.getElement('.e-ribbon .e-drop-icon').title).toEqual('Collapse Toolbar');
});
});
describe('CR-Issues ->', () => {
describe('I257035 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ showRibbon: true }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Add toolbar items', (done: Function): void => {
helper.invoke('addToolbarItems', ['Home', [{ type: 'Separator' }, { text: 'Custom', tooltipText: 'Custom Btn' }], 20]);
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items .e-hscroll-content').children[20].classList).toContain('e-separator');
expect(helper.getElementFromSpreadsheet('.e-ribbon .e-content .e-toolbar-items .e-hscroll-content').children[21].textContent).toBe('Custom');
done();
});
});
});
}); | the_stack |
import * as _ from 'lodash';
import { chai } from 'mochainon';
import * as memoize from 'memoizee';
import type * as BalenaSdk from '../../';
import type { AnyObject } from '../../typings/utils';
import { toWritable } from '../../lib/util/types';
import { getInitialOrganization } from './utils';
// tslint:disable-next-line:no-var-requires
chai.use(require('chai-samsam'));
const { expect } = chai;
export const IS_BROWSER = typeof window !== 'undefined' && window !== null;
let apiUrl: string;
let env: AnyObject;
export let balenaSdkExports: typeof BalenaSdk;
let opts: BalenaSdk.SdkOptions;
if (IS_BROWSER) {
// tslint:disable-next-line:no-var-requires
require('js-polyfills/es6');
balenaSdkExports = window.balenaSdk;
// @ts-expect-error
env = window.__env__;
apiUrl = env.TEST_API_URL || 'https://api.balena-cloud.com';
opts = {
apiUrl,
builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.'),
};
} else {
// tslint:disable-next-line:no-var-requires
balenaSdkExports = require('../..');
// tslint:disable-next-line:no-var-requires
const settings = require('balena-settings-client');
({ env } = process);
apiUrl = env.TEST_API_URL || settings.get('apiUrl');
opts = {
apiUrl,
builderUrl: env.TEST_BUILDER_URL || apiUrl.replace('api.', 'builder.'),
dataDirectory: settings.get('dataDirectory'),
};
}
_.assign(opts, {
isBrowser: IS_BROWSER,
retries: 3,
});
console.log(`Running SDK tests against: ${opts.apiUrl}`);
console.log(`TEST_USERNAME: ${env?.TEST_USERNAME}`);
const buildCredentials = function () {
if (!env) {
throw new Error('Missing environment object?!');
}
const creds = {
email: env.TEST_EMAIL,
password: env.TEST_PASSWORD,
username: env.TEST_USERNAME,
member: {
email: env.TEST_MEMBER_EMAIL,
password: env.TEST_MEMBER_PASSWORD,
username: env.TEST_MEMBER_USERNAME,
},
paid: {
email: env.TEST_PAID_EMAIL,
password: env.TEST_PAID_PASSWORD,
},
register: {
email: env.TEST_REGISTER_EMAIL,
password: env.TEST_REGISTER_PASSWORD,
username: env.TEST_REGISTER_USERNAME,
},
};
if (
// TODO: this should include the paid account eventually as well
![creds.email, creds.register.email].every(
(email) => email == null || email.includes('+testsdk'),
)
) {
throw new Error(
'Missing environment credentials, all emails must include `+testsdk` to avoid accidental deletion',
);
}
if (
!_.every([
creds.email != null,
creds.password != null,
creds.username != null,
creds.member.email != null,
creds.member.password != null,
creds.member.username != null,
creds.register.email != null,
creds.register.password != null,
creds.register.username != null,
])
) {
throw new Error('Missing environment credentials');
}
return creds;
};
export const getSdk = balenaSdkExports.getSdk;
export { opts as sdkOpts };
export const balena = getSdk(opts);
export async function resetUser() {
const isLoggedIn = await balena.auth.isLoggedIn();
if (!isLoggedIn) {
return;
}
return Promise.all([
balena.pine.delete({
resource: 'application',
options: {
$filter: { 1: 1 },
},
}),
balena.pine.delete({
resource: 'user__has__public_key',
options: {
$filter: { 1: 1 },
},
}),
balena.pine
.delete<BalenaSdk.ApiKey>({
resource: 'api_key',
// only delete named user api keys
options: {
$filter: {
name: {
$ne: null,
},
},
},
})
.catch(_.noop),
resetInitialOrganization(),
resetTestOrgs(),
]);
}
export const credentials = buildCredentials();
export function givenLoggedInUserWithApiKey(beforeFn: Mocha.HookFunction) {
beforeFn(async () => {
await balena.auth.login({
email: credentials.email,
password: credentials.password,
});
const { body } = await balena.request.send({
method: 'POST',
url: '/api-key/user/full',
baseUrl: opts.apiUrl,
body: {
name: 'apiKey',
},
});
await balena.auth.logout();
await balena.auth.loginWithToken(body);
await resetUser();
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(() => resetUser());
}
export function givenLoggedInUser(beforeFn: Mocha.HookFunction) {
beforeFn(async () => {
await balena.auth.login({
email: credentials.email,
password: credentials.password,
});
await resetUser();
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(() => resetUser());
}
export function loginPaidUser() {
return balena.auth.login({
email: credentials.paid.email,
password: credentials.paid.password,
});
}
async function resetInitialOrganization() {
const userId = await balena.auth.getUserId();
const initialOrg = await getInitialOrganization();
await balena.pine.delete({
resource: 'organization_membership',
options: {
$filter: {
user: { $ne: userId },
is_member_of__organization: initialOrg.id,
},
},
});
}
export function givenInitialOrganization(beforeFn: Mocha.HookFunction) {
beforeFn(async function () {
this.initialOrg = await getInitialOrganization();
});
}
const getDeviceType = memoize(
(deviceTypeId: number) =>
balena.pine.get({
resource: 'device_type',
id: deviceTypeId,
options: {
$select: 'slug',
},
}),
{
promise: true,
primitive: true,
},
);
const TEST_ORGANIZATION_NAME = 'FooBar sdk test created organization';
async function resetTestOrgs() {
const orgs = await balena.pine.get({
resource: 'organization',
options: {
$select: 'id',
$filter: {
name: TEST_ORGANIZATION_NAME,
},
},
});
await Promise.all(
orgs.map(({ id }) =>
balena.pine.delete({
resource: 'organization',
id,
}),
),
);
}
export function givenAnOrganization(beforeFn: Mocha.HookFunction) {
let orgId;
beforeFn(async function () {
// make sure we start with a clean state
const orgs = await balena.models.organization.getAll({
$select: ['id', 'name'],
$filter: {
name: TEST_ORGANIZATION_NAME,
},
});
// just make sure we didn't accidentaly fetched more than intended
orgs.forEach(({ name }) => expect(name).to.equal(TEST_ORGANIZATION_NAME));
await Promise.all(
orgs.map(({ id }) => balena.models.organization.remove(id)),
);
const organization = await balena.models.organization.create({
name: TEST_ORGANIZATION_NAME,
});
this.organization = organization;
orgId = organization.id;
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(async () => {
await balena.pine.delete({
resource: 'organization',
id: orgId,
});
});
}
export function givenAnApplication(beforeFn: Mocha.HookFunction) {
givenInitialOrganization(beforeFn);
beforeFn(async function () {
const application = await balena.models.application.create({
name: 'FooBar',
applicationType: 'microservices-starter',
deviceType: 'raspberry-pi',
organization: this.initialOrg.id,
});
expect(application)
.to.be.an('object')
.that.has.property('id')
.that.is.a('number');
this.application = application;
expect(application.is_for__device_type)
.to.be.an('object')
.that.has.property('__id')
.that.is.a('number');
this.applicationDeviceType = await getDeviceType(
this.application.is_for__device_type.__id,
);
expect(this.applicationDeviceType)
.to.be.an('object')
.that.has.property('slug')
.that.is.a('string');
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(async () => {
await balena.pine.delete({
resource: 'application',
options: {
$filter: { 1: 1 },
},
});
});
}
const resetDevices = () =>
balena.pine.delete({
resource: 'device',
options: {
$filter: { 1: 1 },
},
});
export const testDeviceOsInfo = {
os_variant: 'prod',
os_version: 'balenaOS 2.48.0+rev1',
supervisor_version: '10.8.0',
};
export function givenADevice(
beforeFn: Mocha.HookFunction,
extraDeviceProps?: BalenaSdk.PineSubmitBody<BalenaSdk.Device>,
) {
beforeFn(async function () {
const uuid = balena.models.device.generateUniqueKey();
const deviceInfo = await balena.models.device.register(
this.application.app_name,
uuid,
);
if (this.currentRelease?.commit) {
await balena.pine.patch<BalenaSdk.Device>({
resource: 'device',
body: {
is_running__release: this.currentRelease.id,
},
options: {
$filter: {
uuid: deviceInfo.uuid,
},
},
});
}
if (extraDeviceProps) {
await balena.pine.patch<BalenaSdk.Device>({
resource: 'device',
body: extraDeviceProps,
options: {
$filter: {
uuid: deviceInfo.uuid,
},
},
});
}
const device = await balena.models.device.get(deviceInfo.uuid);
this.device = device;
if (!this.currentRelease || !this.currentRelease.commit) {
return;
}
const [oldWebInstall, newWebInstall, , newDbInstall] = await Promise.all([
// Create image installs for the images on the device
balena.pine.post<BalenaSdk.ImageInstall>({
resource: 'image_install',
body: {
installs__image: this.oldWebImage.id,
is_provided_by__release: this.oldRelease.id,
device: device.id,
download_progress: null,
status: 'Running',
install_date: '2017-10-01',
},
}),
balena.pine.post<BalenaSdk.ImageInstall>({
resource: 'image_install',
body: {
installs__image: this.newWebImage.id,
is_provided_by__release: this.currentRelease.id,
device: device.id,
download_progress: 50,
status: 'Downloading',
install_date: '2017-10-30',
},
}),
balena.pine.post<BalenaSdk.ImageInstall>({
resource: 'image_install',
body: {
installs__image: this.oldDbImage.id,
is_provided_by__release: this.oldRelease.id,
device: device.id,
download_progress: 100,
status: 'deleted',
install_date: '2017-09-30',
},
}),
balena.pine.post<BalenaSdk.ImageInstall>({
resource: 'image_install',
body: {
installs__image: this.newDbImage.id,
is_provided_by__release: this.currentRelease.id,
device: device.id,
download_progress: null,
status: 'Running',
install_date: '2017-10-30',
},
}),
]);
this.oldWebInstall = oldWebInstall;
this.newWebInstall = newWebInstall;
this.newDbInstall = newDbInstall;
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(resetDevices);
}
export function givenMulticontainerApplicationWithADevice(
beforeFn: Mocha.HookFunction,
) {
givenMulticontainerApplication(beforeFn);
givenADevice(beforeFn);
}
export function givenMulticontainerApplication(beforeFn: Mocha.HookFunction) {
givenAnApplication(beforeFn);
beforeFn(async function () {
const userId = await balena.auth.getUserId();
const oldDate = new Date('2017-01-01').toISOString();
const now = new Date().toISOString();
const [webService, dbService, [oldRelease, newRelease]] = await Promise.all(
[
// Register web & DB services
balena.pine.post<BalenaSdk.Service>({
resource: 'service',
body: {
application: this.application.id,
service_name: 'web',
},
}),
balena.pine.post<BalenaSdk.Service>({
resource: 'service',
body: {
application: this.application.id,
service_name: 'db',
},
}),
// Register an old & new release of this application
(async () => {
return [
await balena.pine.post<BalenaSdk.Release>({
resource: 'release',
body: {
belongs_to__application: this.application.id,
is_created_by__user: userId,
commit: 'old-release-commit',
status: 'success' as const,
source: 'cloud',
composition: '{}',
start_timestamp: oldDate,
},
}),
await balena.pine.post<BalenaSdk.Release>({
resource: 'release',
body: {
belongs_to__application: this.application.id,
is_created_by__user: userId,
commit: 'new-release-commit',
status: 'success' as const,
source: 'cloud',
composition: '{}',
start_timestamp: now,
},
}),
];
})(),
],
);
this.webService = webService;
this.dbService = dbService;
this.oldRelease = oldRelease;
this.currentRelease = newRelease;
const [oldWebImage, newWebImage, oldDbImage, newDbImage] =
await Promise.all([
// Register an old & new web image build from the old and new
// releases, a db build in the new release only
balena.pine.post<BalenaSdk.Image>({
resource: 'image',
body: {
is_a_build_of__service: webService.id,
project_type: 'dockerfile',
content_hash: 'abc',
build_log: 'old web log',
start_timestamp: oldDate,
push_timestamp: oldDate,
status: 'success',
},
}),
balena.pine.post<BalenaSdk.Image>({
resource: 'image',
body: {
is_a_build_of__service: webService.id,
project_type: 'dockerfile',
content_hash: 'def',
build_log: 'new web log',
start_timestamp: now,
push_timestamp: now,
status: 'success',
},
}),
balena.pine.post<BalenaSdk.Image>({
resource: 'image',
body: {
is_a_build_of__service: dbService.id,
project_type: 'dockerfile',
content_hash: 'jkl',
build_log: 'old db log',
start_timestamp: oldDate,
push_timestamp: oldDate,
status: 'success',
},
}),
balena.pine.post<BalenaSdk.Image>({
resource: 'image',
body: {
is_a_build_of__service: dbService.id,
project_type: 'dockerfile',
content_hash: 'ghi',
build_log: 'new db log',
start_timestamp: now,
push_timestamp: now,
status: 'success',
},
}),
]);
this.oldWebImage = oldWebImage;
this.newWebImage = newWebImage;
this.oldDbImage = oldDbImage;
this.newDbImage = newDbImage;
await Promise.all([
// Tie the images to their corresponding releases
balena.pine.post<BalenaSdk.ReleaseImage>({
resource: 'image__is_part_of__release',
body: {
image: oldWebImage.id,
is_part_of__release: oldRelease.id,
},
}),
balena.pine.post<BalenaSdk.ReleaseImage>({
resource: 'image__is_part_of__release',
body: {
image: oldDbImage.id,
is_part_of__release: oldRelease.id,
},
}),
balena.pine.post<BalenaSdk.ReleaseImage>({
resource: 'image__is_part_of__release',
body: {
image: newWebImage.id,
is_part_of__release: newRelease.id,
},
}),
balena.pine.post<BalenaSdk.ReleaseImage>({
resource: 'image__is_part_of__release',
body: {
image: newDbImage.id,
is_part_of__release: newRelease.id,
},
}),
]);
});
const afterFn = beforeFn === beforeEach ? afterEach : after;
afterFn(function () {
return (this.currentRelease = null);
});
}
export function givenASupervisorRelease(
beforeFn: Mocha.HookFunction,
version = 'v11.12.4',
) {
beforeFn(async function () {
const supervisorRelease = await balena.pine.get({
resource: 'supervisor_release',
options: {
$filter: {
supervisor_version: version,
is_for__device_type: this.application.is_for__device_type.__id,
},
},
});
this.supervisorRelease = supervisorRelease[0];
});
}
export const applicationRetrievalFields = toWritable([
'id',
'app_name',
'slug',
] as const);
export const deviceUniqueFields = toWritable(['id', 'uuid'] as const); | the_stack |
import { Vpc } from '@aws-accelerator/cdk-constructs/src/vpc';
import * as c from '@aws-accelerator/common-config/src';
import * as cdk from '@aws-cdk/core';
import {
getStackJsonOutput,
OUTPUT_SUBSCRIPTION_REQUIRED,
StackOutput,
} from '@aws-accelerator/common-outputs/src/stack-output';
import { AccountStacks, AccountStack } from '../../../common/account-stacks';
import { createIamInstanceProfileName } from '../../../common/iam-assets';
import { LaunchConfiguration } from '@aws-accelerator/cdk-constructs/src/autoscaling';
import * as elb from '@aws-cdk/aws-autoscaling';
import { createName } from '@aws-accelerator/cdk-accelerator/src/core/accelerator-name-generator';
import { LoadBalancerOutputFinder } from '@aws-accelerator/common-outputs/src/elb';
import { DynamicSecretOutputFinder } from '@aws-accelerator/common-outputs/src/secrets';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import { Account } from '../../../utils/accounts';
import { getDynamicReplaceableValue } from '../../../common/replacements';
export interface FirewallStep4Props {
accountStacks: AccountStacks;
config: c.AcceleratorConfig;
outputs: StackOutput[];
vpcs: Vpc[];
defaultRegion: string;
accounts: Account[];
}
/**
* Creates the firewall clusters under autoscaling using LoadBalancer and targetgroups created in phase-3.
*
* The following outputs are necessary from previous steps:
* - firewall amis subscription, validation output in phase-1
* - LoadBalancer and TargetGroup created in phase-3
*/
export async function step4(props: FirewallStep4Props) {
const { accountStacks, config, outputs, vpcs, defaultRegion, accounts } = props;
const vpcConfigs = config.getVpcConfigs();
for (const [accountKey, accountConfig] of config.getAccountConfigs()) {
const firewallConfigs = accountConfig.deployments?.firewalls;
if (!firewallConfigs || firewallConfigs.length === 0) {
continue;
}
const subscriptionOutputs = getStackJsonOutput(outputs, {
outputType: 'AmiSubscriptionStatus',
accountKey,
});
for (const firewallConfig of firewallConfigs.filter(firewall => c.FirewallAutoScaleConfigType.is(firewall))) {
if (!firewallConfig.deploy || !c.FirewallAutoScaleConfigType.is(firewallConfig)) {
console.log(`Deploy set to false for "${firewallConfig.name}"`);
continue;
}
const accountStack = accountStacks.tryGetOrCreateAccountStack(accountKey, firewallConfig.region);
if (!accountStack) {
console.warn(`Cannot find account stack ${accountStack}`);
continue;
}
const subscriptionStatus = subscriptionOutputs.find(sub => sub.imageId === firewallConfig['image-id']);
if (!subscriptionStatus || (subscriptionStatus && subscriptionStatus.status === OUTPUT_SUBSCRIPTION_REQUIRED)) {
console.log(`AMI Marketplace subscription required for ImageId: ${firewallConfig['image-id']}`);
continue;
}
const vpc = vpcs.find(v => v.name === firewallConfig.vpc);
if (!vpc) {
console.log(`Skipping firewall deployment because of missing VPC "${firewallConfig.vpc}"`);
continue;
}
const vpcConfig = vpcConfigs.find(
v =>
v.vpcConfig.name === firewallConfig.vpc &&
v.accountKey === accountKey &&
v.vpcConfig.region === firewallConfig.region,
)?.vpcConfig;
if (!vpcConfig) {
console.log(`Skipping firewall deployment because of missing VPC config "${firewallConfig.vpc}"`);
continue;
}
const elbOutput = LoadBalancerOutputFinder.tryFindOneByName({
outputs,
accountKey,
name: firewallConfig['load-balancer'],
region: firewallConfig.region,
});
if (!elbOutput) {
console.warn(`Didn't find output for Gwlb : "${firewallConfig['load-balancer']}"`);
continue;
}
const keyPairs = accountConfig['key-pairs'].filter(kp => kp.region === firewallConfig.region).map(kp => kp.name);
let keyName = firewallConfig['key-pair'];
if (keyName && keyPairs.includes(keyName)) {
keyName = createName({
name: keyName,
suffixLength: 0,
});
}
await createFirewallCluster({
accountStack,
firewallConfig,
vpc,
vpcConfig,
targetGroups: Object.values(elbOutput.targets),
keyName,
userData: await addReplacementsToUserData({
userData: firewallConfig['user-data']!,
accountKey,
accountStack,
config,
defaultRegion,
outputs,
accounts,
launchConfigName: firewallConfig.name,
fwManagerName: accountConfig.deployments?.['firewall-manager']?.name || undefined,
bootstrap: firewallConfig.bootstrap,
}),
firewallManagerName: accountConfig.deployments?.['firewall-manager']?.name,
});
}
}
}
/**
* Create firewall for the given VPC and config in the given scope.
*/
async function createFirewallCluster(props: {
accountStack: AccountStack;
firewallConfig: c.FirewallAutoScaleConfigType;
vpc: Vpc;
vpcConfig: c.VpcConfig;
targetGroups: string[];
keyName?: string;
userData?: string;
firewallManagerName?: string;
}) {
const { accountStack, firewallConfig, vpc, targetGroups, keyName, userData, firewallManagerName } = props;
const {
name: firewallName,
'security-group': securityGroupName,
'fw-instance-role': instanceRoleName,
'image-id': imageId,
'instance-sizes': instanceType,
'desired-hosts': desiredCapacity,
'min-hosts': minSize,
'max-hosts': maxSize,
'max-instance-age': maxInstanceAge,
subnet: subnetName,
'block-device-mappings': deviceNames,
'create-eip': associatePublicIpAddress,
'cpu-utilization-scale-in': cpuUtilizationScaleIn,
'cpu-utilization-scale-out': cpuUtilizationScaleOut,
'apply-tags': tags,
} = firewallConfig;
const securityGroup = vpc.tryFindSecurityGroupByName(securityGroupName);
if (!securityGroup) {
console.warn(`Cannot find security group with name "${securityGroupName}" in VPC "${vpc.name}"`);
return;
}
const launchConfigurationName = createName({
name: `${firewallName}`,
suffixLength: 0,
});
const blockDeviceMappings = deviceNames.map(deviceName => ({
deviceName,
ebs: {
encrypted: true,
volumeType: 'gp2',
volumeSize: firewallConfig['root-volume-size'],
},
}));
// Create LaunchConfiguration
const launchConfig = new LaunchConfiguration(accountStack, `FirewallLaunchConfiguration-${firewallName}`, {
launchConfigurationName,
associatePublicIpAddress,
imageId,
securityGroups: [securityGroup.id],
iamInstanceProfile: instanceRoleName ? createIamInstanceProfileName(instanceRoleName) : undefined,
instanceType,
blockDeviceMappings,
keyName,
userData: userData ? cdk.Fn.base64(userData) : undefined,
});
const autoScalingGroupName = createName({
name: `${firewallName}-asg`,
suffixLength: 0,
});
const subnetIds = vpc.findSubnetIdsByName(subnetName);
const autoScaleTags: elb.CfnAutoScalingGroup.TagPropertyProperty[] = [];
/* eslint-disable no-template-curly-in-string */
for (const [key, value] of Object.entries(tags || {})) {
let tagValue = value;
let replacementValue = tagValue.match('\\${SEA::([a-zA-Z0-9-]*)}');
while (replacementValue) {
const replaceKey = replacementValue[1];
let replaceValue = replaceKey;
if (replaceKey === 'FirewallLaunchConfig') {
replaceValue = launchConfigurationName;
} else if (replaceKey === 'FirewallManager' && firewallManagerName) {
replaceValue = createName({
name: firewallManagerName,
suffixLength: 0,
});
}
tagValue = tagValue.replace(new RegExp('\\${SEA::' + replaceKey + '}', 'g'), replaceValue);
replacementValue = tagValue.match('\\${SEA::([a-zA-Z0-9-]*)}');
}
/* eslint-enable */
autoScaleTags.push({
key,
propagateAtLaunch: true,
value: tagValue,
});
}
if (!autoScaleTags.find(at => at.key === 'Name')) {
autoScaleTags.push({
key: 'Name',
value: autoScalingGroupName,
propagateAtLaunch: true,
});
}
const autoScalingGroup = new elb.CfnAutoScalingGroup(accountStack, `Firewall-AutoScalingGroup-${firewallName}`, {
autoScalingGroupName,
launchConfigurationName: launchConfig.ref,
vpcZoneIdentifier: subnetIds,
maxInstanceLifetime: maxInstanceAge * 86400,
minSize: `${minSize}`,
maxSize: `${maxSize}`,
desiredCapacity: `${desiredCapacity}`,
targetGroupArns: targetGroups,
tags: autoScaleTags,
});
if (cpuUtilizationScaleIn) {
const cpuHighScalingPolicy = new elb.CfnScalingPolicy(accountStack, `CpuUtilizationHigh-${firewallName}-Policy`, {
autoScalingGroupName: autoScalingGroup.ref,
adjustmentType: elb.AdjustmentType.CHANGE_IN_CAPACITY,
cooldown: '300',
scalingAdjustment: 1,
});
new cloudwatch.CfnAlarm(accountStack, `CpuUtilizationHigh-${firewallName}-Alarm`, {
alarmName: createName({
name: `CpuUtilizationHigh-${firewallName}`,
suffixLength: 8,
}),
alarmDescription: 'Scale-up if CPU > 80% for 10 minutes',
metricName: 'CPUUtilization',
namespace: 'AWS/EC2',
statistic: cloudwatch.Statistic.AVERAGE,
period: 300,
evaluationPeriods: 2,
threshold: cpuUtilizationScaleIn,
alarmActions: [cpuHighScalingPolicy.ref],
dimensions: [
{
name: autoScalingGroupName,
value: autoScalingGroup.ref,
},
],
comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_THRESHOLD,
});
}
if (cpuUtilizationScaleOut) {
const cpuLowScalingPolicy = new elb.CfnScalingPolicy(accountStack, `CpuUtilizationLow-${firewallName}-Policy`, {
autoScalingGroupName: autoScalingGroup.ref,
adjustmentType: elb.AdjustmentType.CHANGE_IN_CAPACITY,
cooldown: '300',
scalingAdjustment: -1,
});
new cloudwatch.CfnAlarm(accountStack, `CpuUtilizationLow-${firewallName}-Alarm`, {
alarmName: createName({
name: `CpuUtilizationLow-${firewallName}`,
suffixLength: 8,
}),
alarmDescription: 'Scale-down if CPU < 60% for 10 minutes',
metricName: 'CPUUtilization',
namespace: 'AWS/EC2',
statistic: cloudwatch.Statistic.AVERAGE,
period: 300,
evaluationPeriods: 2,
threshold: cpuUtilizationScaleOut,
alarmActions: [cpuLowScalingPolicy.ref],
dimensions: [
{
name: autoScalingGroupName,
value: autoScalingGroup.ref,
},
],
comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_THRESHOLD,
});
}
}
export async function addReplacementsToUserData(props: {
accountStack: AccountStack;
outputs: StackOutput[];
accounts?: Account[];
accountKey: string;
config: c.AcceleratorConfig;
userData: string;
defaultRegion: string;
launchConfigName?: string;
fwManagerName?: string;
fwRegion?: string;
bootstrap?: string;
}) {
const {
accountKey,
accountStack,
accounts,
config,
outputs,
defaultRegion,
launchConfigName,
fwManagerName,
fwRegion,
bootstrap,
} = props;
let { userData } = props;
/* eslint-disable no-template-curly-in-string */
while (!!userData.match('\\${SEA::([a-zA-Z0-9-]*)}')) {
const replacementMatch = userData.match('\\${SEA::([a-zA-Z0-9-]*)}');
let replaceValue: string = '';
if (replacementMatch) {
const replaceKey = replacementMatch[1];
if (replaceKey.startsWith('SECRET-')) {
const secretKey = replaceKey.split('SECRET-')?.[1];
if (secretKey) {
const secretOutput = DynamicSecretOutputFinder.tryFindOne({
accountKey,
region: accountStack.region,
outputs,
predicate: o => o.name === secretKey,
});
if (secretOutput) {
// replaceValue = cdk.SecretValue.secretsManager(secretOutput.arn).toString();
replaceValue = secretOutput.value;
} else {
console.warn(`Didn't find Secret ${secretKey} in account ${accountKey}`);
}
}
} else {
if (replaceKey === 'FirewallLaunchConfig' && launchConfigName) {
replaceValue = createName({
name: launchConfigName,
suffixLength: 0,
});
} else if (replaceKey === 'FirewallManager' && fwManagerName) {
replaceValue = createName({
name: fwManagerName,
suffixLength: 0,
});
} else if (replaceKey === 'FirewallRegion' && fwRegion) {
replaceValue = fwRegion;
} else if (replaceKey === 'BOOTSTRAP') {
if (bootstrap) {
const bootstrapValue = await addReplacementsToUserData({
userData: bootstrap,
accountKey,
accountStack,
config,
defaultRegion,
outputs,
accounts,
launchConfigName,
fwManagerName,
fwRegion,
});
replaceValue = cdk.Fn.base64(bootstrapValue);
}
} else {
replaceValue = getDynamicReplaceableValue({
paramKey: replaceKey,
outputs,
config,
accountKey,
defaultRegion,
});
}
}
userData = userData.replace(new RegExp('\\${SEA::' + replaceKey + '}', 'g'), replaceValue);
}
}
/* eslint-enable */
return userData;
} | the_stack |
module es {
export enum ComponentTransform {
position,
scale,
rotation,
}
export enum DirtyType {
clean = 0,
positionDirty = 1,
scaleDirty = 2,
rotationDirty = 4,
}
export class Transform {
/** 与此转换关联的实体 */
public readonly entity: Entity;
public hierarchyDirty: DirtyType;
public _localDirty: boolean;
public _localPositionDirty: boolean;
public _localScaleDirty: boolean;
public _localRotationDirty: boolean;
public _positionDirty: boolean;
public _worldToLocalDirty: boolean;
public _worldInverseDirty: boolean;
/**
* 值会根据位置、旋转和比例自动重新计算
*/
public _localTransform: Matrix2D = Matrix2D.identity;
/**
* 值将自动从本地和父矩阵重新计算。
*/
public _worldTransform = Matrix2D.identity;
public _rotationMatrix: Matrix2D = Matrix2D.identity;
public _translationMatrix: Matrix2D = Matrix2D.identity;
public _scaleMatrix: Matrix2D = Matrix2D.identity;
public _children: Transform[] = [];
constructor(entity: Entity) {
this.entity = entity;
this.scale = this._localScale = Vector2.one;
}
/**
* 这个转换的所有子元素
*/
public get childCount() {
return this._children.length;
}
/**
* 变换在世界空间的旋转度
*/
public get rotationDegrees(): number {
return MathHelper.toDegrees(this._rotation);
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotationDegrees(value: number) {
this.setRotation(MathHelper.toRadians(value));
}
/**
* 旋转相对于父变换旋转的角度
*/
public get localRotationDegrees(): number {
return MathHelper.toDegrees(this._localRotation);
}
/**
* 旋转相对于父变换旋转的角度
* @param value
*/
public set localRotationDegrees(value: number) {
this.localRotation = MathHelper.toRadians(value);
}
public get localToWorldTransform(): Matrix2D {
this.updateTransform();
return this._worldTransform;
}
public _parent: Transform;
/**
* 获取此转换的父转换
*/
public get parent() {
return this._parent;
}
/**
* 设置此转换的父转换
* @param value
*/
public set parent(value: Transform) {
this.setParent(value);
}
public _worldToLocalTransform = Matrix2D.identity;
public get worldToLocalTransform(): Matrix2D {
if (this._worldToLocalDirty) {
if (this.parent == null) {
this._worldToLocalTransform = Matrix2D.identity;
} else {
this.parent.updateTransform();
this._worldToLocalTransform = Matrix2D.invert(this.parent._worldTransform);
}
this._worldToLocalDirty = false;
}
return this._worldToLocalTransform;
}
public _worldInverseTransform = Matrix2D.identity;
public get worldInverseTransform(): Matrix2D {
this.updateTransform();
if (this._worldInverseDirty) {
this._worldInverseTransform = Matrix2D.invert(this._worldTransform);
this._worldInverseDirty = false;
}
return this._worldInverseTransform;
}
public _position: Vector2 = Vector2.zero;
/**
* 变换在世界空间中的位置
*/
public get position(): Vector2 {
this.updateTransform();
if (this._positionDirty) {
if (this.parent == null) {
this._position = this._localPosition;
} else {
this.parent.updateTransform();
Vector2Ext.transformR(this._localPosition, this.parent._worldTransform, this._position);
}
this._positionDirty = false;
}
return this._position;
}
/**
* 变换在世界空间中的位置
* @param value
*/
public set position(value: Vector2) {
this.setPosition(value.x, value.y);
}
public _scale: Vector2 = Vector2.one;
/**
* 变换在世界空间的缩放
*/
public get scale(): Vector2 {
this.updateTransform();
return this._scale;
}
/**
* 变换在世界空间的缩放
* @param value
*/
public set scale(value: Vector2) {
this.setScale(value);
}
public _rotation: number = 0;
/**
* 在世界空间中以弧度旋转的变换
*/
public get rotation(): number {
this.updateTransform();
return this._rotation;
}
/**
* 变换在世界空间的旋转度
* @param value
*/
public set rotation(value: number) {
this.setRotation(value);
}
public _localPosition: Vector2 = Vector2.zero;
/**
* 转换相对于父转换的位置。如果转换没有父元素,则与transform.position相同
*/
public get localPosition(): Vector2 {
this.updateTransform();
return this._localPosition;
}
/**
* 转换相对于父转换的位置。如果转换没有父元素,则与transform.position相同
* @param value
*/
public set localPosition(value: Vector2) {
this.setLocalPosition(value);
}
public _localScale: Vector2 = Vector2.one;
/**
* 转换相对于父元素的比例。如果转换没有父元素,则与transform.scale相同
*/
public get localScale(): Vector2 {
this.updateTransform();
return this._localScale;
}
/**
* 转换相对于父元素的比例。如果转换没有父元素,则与transform.scale相同
* @param value
*/
public set localScale(value: Vector2) {
this.setLocalScale(value);
}
public _localRotation: number = 0;
/**
* 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同
*/
public get localRotation(): number {
this.updateTransform();
return this._localRotation;
}
/**
* 相对于父变换的旋转,变换的旋转。如果转换没有父元素,则与transform.rotation相同
* @param value
*/
public set localRotation(value: number) {
this.setLocalRotation(value);
}
/**
* 返回在索引处的转换子元素
* @param index
*/
public getChild(index: number): Transform {
return this._children[index];
}
/**
* 设置此转换的父转换
* @param parent
*/
public setParent(parent: Transform): Transform {
if (this._parent == parent)
return this;
if (this._parent != null) {
const index = this._parent._children.findIndex(t => t == this);
if (index != -1)
this._parent._children.splice(index, 1);
}
if (parent != null) {
parent._children.push(this);
}
this._parent = parent;
this.setDirty(DirtyType.positionDirty);
return this;
}
/**
* 设置转换在世界空间中的位置
* @param x
* @param y
*/
public setPosition(x: number, y: number): Transform {
let position = new Vector2(x, y);
if (position.equals(this._position))
return this;
this._position = position;
if (this.parent != null) {
this.localPosition = Vector2.transform(this._position, this.worldToLocalTransform);
} else {
this.localPosition = position;
}
this._positionDirty = false;
return this;
}
/**
* 设置转换相对于父转换的位置。如果转换没有父元素,则与transform.position相同
* @param localPosition
*/
public setLocalPosition(localPosition: Vector2): Transform {
if (localPosition.equals(this._localPosition))
return this;
this._localPosition = localPosition;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.positionDirty);
return this;
}
/**
* 设置变换在世界空间的旋转度
* @param radians
*/
public setRotation(radians: number): Transform {
this._rotation = radians;
if (this.parent != null) {
this.localRotation = this.parent.rotation + radians;
} else {
this.localRotation = radians;
}
return this;
}
/**
* 设置变换在世界空间的旋转度
* @param degrees
*/
public setRotationDegrees(degrees: number): Transform {
return this.setRotation(MathHelper.toRadians(degrees));
}
/**
* 旋转精灵的顶部,使其朝向位置
* @param pos
*/
public lookAt(pos: Vector2) {
const sign = this.position.x > pos.x ? -1 : 1;
const vectorToAlignTo = this.position.sub(pos).normalize();
this.rotation = sign * Math.acos(vectorToAlignTo.dot(Vector2.unitY));
}
/**
* 相对于父变换的旋转设置变换的旋转。如果转换没有父元素,则与transform.rotation相同
* @param radians
*/
public setLocalRotation(radians: number) {
this._localRotation = radians;
this._localDirty = this._positionDirty = this._localPositionDirty = this._localRotationDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.rotationDirty);
return this;
}
/**
* 相对于父变换的旋转设置变换的旋转。如果转换没有父元素,则与transform.rotation相同
* @param degrees
*/
public setLocalRotationDegrees(degrees: number): Transform {
return this.setLocalRotation(MathHelper.toRadians(degrees));
}
/**
* 设置变换在世界空间中的缩放
* @param scale
*/
public setScale(scale: Vector2): Transform {
this._scale = scale;
if (this.parent != null) {
this.localScale = Vector2.divide(scale, this.parent._scale);
} else {
this.localScale = scale;
}
return this;
}
/**
* 设置转换相对于父对象的比例。如果转换没有父元素,则与transform.scale相同
* @param scale
*/
public setLocalScale(scale: Vector2): Transform {
this._localScale = scale;
this._localDirty = this._positionDirty = this._localScaleDirty = true;
this.setDirty(DirtyType.scaleDirty);
return this;
}
/**
* 对精灵坐标进行四舍五入
*/
public roundPosition() {
this.position = Vector2Ext.round(this._position);
}
public updateTransform() {
if (this.hierarchyDirty != DirtyType.clean) {
if (this.parent != null)
this.parent.updateTransform();
if (this._localDirty) {
if (this._localPositionDirty) {
Matrix2D.createTranslation(this._localPosition.x, this._localPosition.y, this._translationMatrix);
this._localPositionDirty = false;
}
if (this._localRotationDirty) {
Matrix2D.createRotation(this._localRotation, this._rotationMatrix);
this._localRotationDirty = false;
}
if (this._localScaleDirty) {
Matrix2D.createScale(this._localScale.x, this._localScale.y, this._scaleMatrix);
this._localScaleDirty = false;
}
Matrix2D.multiply(this._scaleMatrix, this._rotationMatrix, this._localTransform);
Matrix2D.multiply(this._localTransform, this._translationMatrix, this._localTransform);
if (this.parent == null) {
this._worldTransform = this._localTransform;
this._rotation = this._localRotation;
this._scale = this._localScale;
this._worldInverseDirty = true;
}
this._localDirty = false;
}
if (this.parent != null) {
Matrix2D.multiply(this._localTransform, this.parent._worldTransform, this._worldTransform);
this._rotation = this._localRotation + this.parent._rotation;
this._scale = this.parent._scale.multiply(this._localScale);;
this._worldInverseDirty = true;
}
this._worldToLocalDirty = true;
this._positionDirty = true;
this.hierarchyDirty = DirtyType.clean;
}
}
public setDirty(dirtyFlagType: DirtyType) {
if ((this.hierarchyDirty & dirtyFlagType) == 0) {
this.hierarchyDirty |= dirtyFlagType;
switch (dirtyFlagType) {
case DirtyType.positionDirty:
this.entity.onTransformChanged(ComponentTransform.position);
break;
case DirtyType.rotationDirty:
this.entity.onTransformChanged(ComponentTransform.rotation);
break;
case DirtyType.scaleDirty:
this.entity.onTransformChanged(ComponentTransform.scale);
break;
}
// 告诉子项发生了变换
for (let i = 0; i < this._children.length; i++)
this._children[i].setDirty(dirtyFlagType);
}
}
/**
* 从另一个transform属性进行拷贝
* @param transform
*/
public copyFrom(transform: Transform) {
this._position = transform.position.clone();
this._localPosition = transform._localPosition.clone();
this._rotation = transform._rotation;
this._localRotation = transform._localRotation;
this._scale = transform._scale;
this._localScale = transform._localScale;
this.setDirty(DirtyType.positionDirty);
this.setDirty(DirtyType.rotationDirty);
this.setDirty(DirtyType.scaleDirty);
}
public toString(): string {
return `[Transform: parent: ${this.parent}, position: ${this.position}, rotation: ${this.rotation},
scale: ${this.scale}, localPosition: ${this._localPosition}, localRotation: ${this._localRotation},
localScale: ${this._localScale}]`;
}
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js';
import '../settings_shared_css.js';
import '../site_favicon.js';
import '../i18n_setup.js';
import './security_keys_pin_field.js';
import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {CrIconButtonElement} from 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {IronListElement} from 'chrome://resources/polymer/v3_0/iron-list/iron-list.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {Credential, SecurityKeysCredentialBrowserProxy, SecurityKeysCredentialBrowserProxyImpl, StartCredentialManagementResponse} from './security_keys_browser_proxy.js';
import {SettingsSecurityKeysPinFieldElement} from './security_keys_pin_field.js';
export enum CredentialManagementDialogPage {
INITIAL = 'initial',
PIN_PROMPT = 'pinPrompt',
PIN_ERROR = 'pinError',
CREDENTIALS = 'credentials',
EDIT = 'edit',
ERROR = 'error',
CONFIRM = 'confirm',
}
export interface SettingsSecurityKeysCredentialManagementDialogElement {
$: {
cancelButton: CrButtonElement,
confirm: HTMLElement,
confirmButton: CrButtonElement,
credentialList: IronListElement,
dialog: CrDialogElement,
displayNameInput: CrInputElement,
edit: HTMLElement,
error: HTMLElement,
pin: SettingsSecurityKeysPinFieldElement,
pinError: HTMLElement,
userNameInput: CrInputElement
};
}
const SettingsSecurityKeysCredentialManagementDialogElementBase =
WebUIListenerMixin(I18nMixin(PolymerElement));
const MAX_INPUT_LENGTH: number = 62;
export class SettingsSecurityKeysCredentialManagementDialogElement extends
SettingsSecurityKeysCredentialManagementDialogElementBase {
static get is() {
return 'settings-security-keys-credential-management-dialog';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* The ID of the element currently shown in the dialog.
*/
dialogPage_: {
type: String,
value: CredentialManagementDialogPage.INITIAL,
observer: 'dialogPageChanged_',
},
/**
* The list of credentials displayed in the dialog.
*/
credentials_: {
type: Array,
notify: true,
},
/**
* The message displayed on the "error" dialog page.
*/
errorMsg_: String,
cancelButtonVisible_: Boolean,
closeButtonVisible_: Boolean,
confirmButtonDisabled_: Boolean,
confirmButtonLabel_: String,
confirmButtonVisible_: Boolean,
confirmMsg_: String,
credentialIdToDelete_: String,
displayNameInputError_: String,
editingCredential_: Object,
editButtonVisible_: Boolean,
minPinLength_: Number,
newDisplayName_: String,
newUsername_: String,
userHandle_: String,
userNameInputError_: String,
};
}
private cancelButtonVisible_: boolean;
private closeButtonVisible_: boolean;
private confirmButtonDisabled_: boolean;
private confirmButtonLabel_: string;
private confirmButtonVisible_: boolean;
private confirmMsg_: string;
private credentialIdToDelete_: string;
private credentials_: Array<Credential>;
private dialogPage_: CredentialManagementDialogPage;
private dialogTitle_: string;
private displayNameInputError_: string;
private editingCredential_: Credential;
private editButtonVisible_: Boolean;
private errorMsg_: string;
private minPinLength_: number;
private newDisplayName_: string;
private newUsername_: string;
private userNameInputError_: string;
private browserProxy_: SecurityKeysCredentialBrowserProxy =
SecurityKeysCredentialBrowserProxyImpl.getInstance();
private showSetPINButton_: boolean = false;
connectedCallback() {
super.connectedCallback();
this.$.dialog.showModal();
this.addWebUIListener(
'security-keys-credential-management-finished',
(error: string, requiresPINChange = false) =>
this.onPinError_(error, requiresPINChange));
this.browserProxy_.startCredentialManagement().then(
(response: StartCredentialManagementResponse) => {
this.minPinLength_ = response.minPinLength;
this.editButtonVisible_ = response.supportsUpdateUserInformation;
this.dialogPage_ = CredentialManagementDialogPage.PIN_PROMPT;
});
}
private onPinError_(error: string, requiresPINChange = false) {
this.errorMsg_ = error;
this.showSetPINButton_ = requiresPINChange;
this.dialogPage_ = CredentialManagementDialogPage.PIN_ERROR;
}
private onError_(error: string) {
this.errorMsg_ = error;
this.dialogPage_ = CredentialManagementDialogPage.ERROR;
}
private submitPIN_() {
// Disable the confirm button to prevent concurrent submissions.
this.confirmButtonDisabled_ = true;
this.$.pin.trySubmit(pin => this.browserProxy_.providePIN(pin))
.then(
() => {
// Leave confirm button disabled while enumerating credentials.
this.browserProxy_.enumerateCredentials().then(
(credentials: Array<Credential>) =>
this.onCredentials_(credentials));
},
() => {
// Wrong PIN.
this.confirmButtonDisabled_ = false;
});
}
private onCredentials_(credentials: Array<Credential>) {
this.credentials_ = credentials;
this.$.credentialList.fire('iron-resize');
this.dialogPage_ = CredentialManagementDialogPage.CREDENTIALS;
}
private dialogPageChanged_() {
switch (this.dialogPage_) {
case CredentialManagementDialogPage.INITIAL:
this.cancelButtonVisible_ = true;
this.confirmButtonVisible_ = false;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementDialogTitle');
break;
case CredentialManagementDialogPage.PIN_PROMPT:
this.cancelButtonVisible_ = false;
this.confirmButtonLabel_ = this.i18n('continue');
this.confirmButtonDisabled_ = false;
this.confirmButtonVisible_ = true;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementDialogTitle');
this.$.pin.focus();
break;
case CredentialManagementDialogPage.PIN_ERROR:
this.cancelButtonVisible_ = true;
this.confirmButtonLabel_ = this.i18n('securityKeysSetPinButton');
this.confirmButtonVisible_ = this.showSetPINButton_;
this.confirmButtonDisabled_ = false;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementDialogTitle');
break;
case CredentialManagementDialogPage.CREDENTIALS:
this.cancelButtonVisible_ = false;
this.confirmButtonLabel_ = this.i18n('done');
this.confirmButtonDisabled_ = false;
this.confirmButtonVisible_ = true;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementDialogTitle');
break;
case CredentialManagementDialogPage.EDIT:
this.cancelButtonVisible_ = true;
this.confirmButtonLabel_ = this.i18n('save');
this.confirmButtonDisabled_ = false;
this.confirmButtonVisible_ = true;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysUpdateCredentialDialogTitle');
break;
case CredentialManagementDialogPage.ERROR:
this.cancelButtonVisible_ = false;
this.confirmButtonLabel_ = this.i18n('continue');
this.confirmButtonDisabled_ = false;
this.confirmButtonVisible_ = true;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementDialogTitle');
break;
case CredentialManagementDialogPage.CONFIRM:
this.cancelButtonVisible_ = true;
this.confirmButtonLabel_ = this.i18n('delete');
this.confirmButtonVisible_ = true;
this.closeButtonVisible_ = false;
this.dialogTitle_ =
this.i18n('securityKeysCredentialManagementConfirmDeleteTitle');
break;
default:
assertNotReached();
}
this.dispatchEvent(new CustomEvent(
'credential-management-dialog-ready-for-testing',
{bubbles: true, composed: true}));
}
private onConfirmButtonClick_() {
switch (this.dialogPage_) {
case CredentialManagementDialogPage.PIN_PROMPT:
this.submitPIN_();
break;
case CredentialManagementDialogPage.PIN_ERROR:
this.$.dialog.close();
this.dispatchEvent(new CustomEvent(
'credential-management-set-pin', {bubbles: true, composed: true}));
break;
case CredentialManagementDialogPage.CREDENTIALS:
this.$.dialog.close();
break;
case CredentialManagementDialogPage.EDIT:
this.updateUserInformation_();
break;
case CredentialManagementDialogPage.ERROR:
this.dialogPage_ = CredentialManagementDialogPage.CREDENTIALS;
break;
case CredentialManagementDialogPage.CONFIRM:
this.deleteCredential_();
break;
default:
assertNotReached();
}
}
private onCancelButtonClick_() {
switch (this.dialogPage_) {
case CredentialManagementDialogPage.INITIAL:
case CredentialManagementDialogPage.PIN_PROMPT:
case CredentialManagementDialogPage.PIN_ERROR:
case CredentialManagementDialogPage.CREDENTIALS:
this.$.dialog.close();
break;
case CredentialManagementDialogPage.EDIT:
case CredentialManagementDialogPage.ERROR:
case CredentialManagementDialogPage.CONFIRM:
this.dialogPage_ = CredentialManagementDialogPage.CREDENTIALS;
break;
default:
assertNotReached();
}
}
private onDialogClosed_() {
this.browserProxy_.close();
}
private close_() {
this.$.dialog.close();
}
private isEmpty_(str: string|null): boolean {
return !str || str.length === 0;
}
private onIronSelect_(e: Event) {
// Prevent this event from bubbling since it is unnecessarily triggering
// the listener within settings-animated-pages.
e.stopPropagation();
}
private onDeleteButtonClick_(e: Event) {
const target = e.target as CrIconButtonElement;
this.credentialIdToDelete_ = target.dataset['credentialid']!;
assert(!this.isEmpty_(this.credentialIdToDelete_));
this.confirmMsg_ =
this.i18n('securityKeysCredentialManagementConfirmDeleteCredential');
this.dialogPage_ = CredentialManagementDialogPage.CONFIRM;
}
private deleteCredential_() {
this.browserProxy_.deleteCredentials([this.credentialIdToDelete_])
.then((response) => {
if (!response.success) {
this.onError_(response.message);
return;
}
for (let i = 0; i < this.credentials_.length; i++) {
if (this.credentials_[i].credentialId ===
this.credentialIdToDelete_) {
this.credentials_.splice(i, 1);
break;
}
}
this.dialogPage_ = CredentialManagementDialogPage.CREDENTIALS;
});
}
private validateInput_() {
this.displayNameInputError_ =
this.newDisplayName_.length > MAX_INPUT_LENGTH ?
this.i18n('securityKeysInputTooLong') :
'';
this.userNameInputError_ = this.newUsername_.length > MAX_INPUT_LENGTH ?
this.i18n('securityKeysInputTooLong') :
'';
this.confirmButtonDisabled_ =
!this.isEmpty_(this.displayNameInputError_ + this.userNameInputError_);
}
private onUpdateButtonClick_(e: Event) {
const target = e.target as CrIconButtonElement;
for (const credential of this.credentials_) {
if (credential.credentialId === target.dataset['credentialid']!) {
this.editingCredential_ = credential;
break;
}
}
this.newDisplayName_ = this.editingCredential_.userDisplayName;
this.newUsername_ = this.editingCredential_.userName;
this.dialogPage_ = CredentialManagementDialogPage.EDIT;
}
private updateUserInformation_() {
assert(this.dialogPage_ === CredentialManagementDialogPage.EDIT);
if (this.isEmpty_(this.newUsername_)) {
this.newUsername_ = this.editingCredential_.userName;
}
if (this.isEmpty_(this.newDisplayName_)) {
this.newDisplayName_ = this.editingCredential_.userDisplayName;
}
this.browserProxy_
.updateUserInformation(
this.editingCredential_.credentialId,
this.editingCredential_.userHandle, this.newUsername_,
this.newDisplayName_)
.then((response) => {
if (!response.success) {
this.onError_(response.message);
return;
}
for (let i = 0; i < this.credentials_.length; i++) {
if (this.credentials_[i].credentialId ===
this.editingCredential_.credentialId) {
const newCred: Credential =
Object.assign({}, this.credentials_[i]);
newCred.userName = this.newUsername_;
newCred.userDisplayName = this.newDisplayName_;
this.credentials_.splice(i, 1, newCred);
this.$.credentialList.fire('iron-resize');
break;
}
}
});
this.dialogPage_ = CredentialManagementDialogPage.CREDENTIALS;
}
}
declare global {
interface HTMLElementTagNameMap {
'settings-security-keys-credential-management-dialog':
SettingsSecurityKeysCredentialManagementDialogElement;
}
}
customElements.define(
SettingsSecurityKeysCredentialManagementDialogElement.is,
SettingsSecurityKeysCredentialManagementDialogElement); | the_stack |
import {
ChangeDetectorRef,
Directive,
ElementRef,
EventEmitter,
HostBinding,
HostListener,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges
} from '@angular/core';
import {IsMobileOrTablet} from '../utils/utils';
@Directive({
selector: '[ngDropdown]'
})
export class NgDropdownDirective implements OnChanges, OnInit, OnDestroy {
@Input() public list: any[] = [];
@Input() public active: any = null;
@Input() public input: HTMLElement = null;
@Input() public element: Element = null;
@Input() public key = '';
@Input() public completion = true;
@Output() public hover: EventEmitter<any> = new EventEmitter<any>();
@Output() public selected: EventEmitter<any> = new EventEmitter<any>();
@Output() public closed: EventEmitter<any> = new EventEmitter<any>();
_open = false;
_list: { active: boolean, [value: string]: any }[] = [];
_class = '';
private inputKeydownBind = this.inputKeydown.bind(this);
private mouseoverListenerBind = this.mouseoverListener.bind(this);
private documentKeydownBind = this.documentKeydown.bind(this);
constructor(public _eref: ElementRef, private cdr: ChangeDetectorRef) {
}
/**
*
*/
ngOnInit() {
this._class = `dr-item-${this.key}-`;
if (!IsMobileOrTablet()) {
this._eref.nativeElement.addEventListener('mouseover', this.mouseoverListenerBind);
}
/**
*
*/
this.PrepareList();
}
/**
*
*/
ngOnChanges(changes: SimpleChanges) {
if (typeof changes['active'] !== 'undefined' && !changes['active'].firstChange) {
this.PrepareList();
}
if (typeof changes['list'] !== 'undefined') {
this.list = changes['list'].currentValue;
/**
*
*/
this.PrepareList();
}
}
/**
*
*/
keyDown(event: KeyboardEvent) {
event.stopImmediatePropagation();
event.stopPropagation();
/**
*
*/
switch (event.code) {
case 'ArrowDown':
this.Open();
/**
*
*/
this.SetActive(this.FindActive() + 1);
this.DropdownFocusAreaDown();
event.preventDefault();
break;
case 'ArrowUp':
this.Open();
/**
*
*/
this.SetActive(this.FindActive() - 1);
this.DropdownFocusAreaUp();
event.preventDefault();
break;
case 'Enter':
this.EmitSelected();
this.Close(null, true);
if (this.RefExists()) {
this.input.blur();
}
event.preventDefault();
break;
case 'Escape':
this.Close(null, true);
if (this.RefExists()) {
this.input.blur();
}
event.preventDefault();
break;
case 'Tab':
if (!event.shiftKey) {
this.EmitSelected();
}
this.Close(null, true);
break;
default:
return;
}
}
/**
*
*/
OnMouseOver(event: MouseEvent) {
// Mouse didn't actually move, so no logic needed.
if (event.movementX === 0 && event.movementY === 0) {
return;
}
/**
*
*/
const el: any = event.target || event.srcElement;
if (el.id.length > 0 && el.id.includes(this._class)) {
this.SetActive(Number(el.id.slice(this._class.length, el.id.length)));
}
}
/**
*
*/
EmitSelected() {
if (this.FindActive() > -1) {
this.selected.emit(this._list[this.FindActive()].key);
}
}
/**
*
*/
DropdownFocusAreaDown() {
const scroll = this._eref.nativeElement.offsetHeight + this._eref.nativeElement.scrollTop;
/**
*
*/
if ((this.GetElement(this.FindActive()).offsetTop + this.GetElement(this.FindActive()).offsetHeight) > scroll) {
// tslint:disable-next-line:max-line-length
this._eref.nativeElement.scrollTop = this.GetElement(this.FindActive()).offsetTop - (this._eref.nativeElement.offsetHeight - this.GetElement(this.FindActive()).offsetHeight);
}
}
/**
*
*/
DropdownFocusAreaUp() {
const scroll = this._eref.nativeElement.scrollTop;
/**
*
*/
if (this.GetElement(this.FindActive()).offsetTop < scroll && scroll > 0) {
this._eref.nativeElement.scrollTop = this.GetElement(this.FindActive()).offsetTop;
}
}
// =======================================================================//
// ! Bindings //
// =======================================================================//
/**
*
*/
@HostBinding('class.open')
get opened() {
return this._open;
}
// =======================================================================//
// ! Listeners //
// =======================================================================//
/**
*
*/
@HostListener('document:click', ['$event'])
Close(event, force: boolean = false) {
if (!this._open) {
return;
}
const close = () => {
this._open = false;
/**
* Emit NULL so listening components know what to do.
*/
this.RemoveListeners();
this.ClearActive();
this.hover.emit(null);
this.closed.emit();
this.cdr.detectChanges();
};
if (force) {
close();
return;
}
if ((this._open && (!this.element.contains(event.target)))) {
close();
}
}
/**
*
*/
private inputKeydown(event: KeyboardEvent) {
this.keyDown(event);
}
/**
*
*/
private documentKeydown(event: KeyboardEvent) {
this.keyDown(event);
}
/**
*
*/
private mouseoverListener(event: MouseEvent) {
this.OnMouseOver(event);
}
// =======================================================================//
// ! Utils //
// =======================================================================//
/**
*
*/
RegisterListeners() {
if (this.RefExists()) {
this.input.addEventListener('keydown', this.inputKeydownBind);
}
if (!this.completion) {
document.addEventListener('keydown', this.documentKeydownBind);
}
}
/**
*
*/
RemoveListeners() {
if (this.RefExists()) {
this.input.removeEventListener('keydown', this.inputKeydownBind);
}
if (!this.completion) {
document.removeEventListener('keydown', this.documentKeydownBind);
}
if (!IsMobileOrTablet()) {
this._eref.nativeElement.removeEventListener('mouseover', this.mouseoverListenerBind);
}
}
/**
*
*/
Open() {
setTimeout(() => {
if (!this._open && !this._eref.nativeElement.classList.contains('is-initial-empty')) {
this.RegisterListeners();
this._open = true;
this.PrepareList();
/**
*
*/
if (this.FindActive() < 0) {
this._eref.nativeElement.scrollTop = 0;
} else {
this._eref.nativeElement.scrollTop = this.GetElement(this.FindActive()).offsetHeight * this.FindActive();
}
this.cdr.detectChanges();
}
}, 0);
}
/**
*
*/
RefExists() {
return typeof this.input !== 'undefined';
}
/**
*
*/
FindActive(): number {
return this._list.reduce((result, item, index) => {
if (item.active) {
result = index;
}
return result;
}, -1);
}
/**
*
*/
SetActive(index: number) {
if (index > this._list.length - 1 || index < 0) {
return;
}
/**
*
*/
this.ClearActive();
this._list[index].active = true;
this.hover.emit(this._list[index].key);
/**
*
*/
this.GetElement(index).classList.add('active');
}
/**
*
*/
GetElement(index: number) {
return this._eref.nativeElement.children[index];
}
/**
*
*/
ClearActive(): void {
this._list.forEach((item, index) => {
item.active = false;
/**
*
*/
this.GetElement(index).classList.remove('active');
});
}
/**
*
*/
PrepareList() {
this._list = Object.keys(this.list).map((key) => {
return {
key,
active: this.ActiveItem(key)
};
});
/**
*
*/
this.PrepareChildrenList();
}
/**
*
*/
ActiveItem(item: any) {
return this.active !== null && item === this.active;
}
/**
*
*/
DetermineActiveClass() {
this._list.forEach((item, index) => {
if (typeof this.GetElement(index) === 'undefined') {
return;
}
/**
*
*/
this.GetElement(index).classList.remove('active');
if (item.active) {
this.GetElement(index).classList.add('active');
}
});
}
/**
*
*/
PrepareChildrenList() {
const list = this._eref.nativeElement.children;
setTimeout(() => {
for (let i = 0; i < list.length; i++) {
list[i].id = this._class + i;
}
}, 0);
/**
*
*/
this.DetermineActiveClass();
}
/**
*
*/
DeReference(object: { active: boolean, [value: string]: any }) {
const {item} = object;
/**
*
*/
return Object.assign({}, {...item});
}
/**
*
*/
ngOnDestroy() {
this.RemoveListeners();
}
} | the_stack |
import { NotionCache } from '@nishans/cache';
import { NotionDiscourse } from '@nishans/discourse';
import { NotionEndpoints } from '@nishans/endpoints';
import { NotionIdz } from '@nishans/idz';
import { NotionInit } from '@nishans/init';
import { NotionLineage } from '@nishans/lineage';
import { NotionLogger } from '@nishans/logger';
import { NotionOperations } from '@nishans/operations';
import {
ICollection,
ICollectionBlock,
ICollectionView,
ICollectionViewPage,
IColumn,
IColumnList,
IFactory,
IOperation,
IPage,
ISpace,
ISpaceView,
TBlock,
WebBookmarkProps
} from '@nishans/types';
import { NotionUtils } from '@nishans/utils';
import { INotionFabricatorOptions, TBlockCreateInput } from '../';
import { CreateData } from './';
import { executeOperationAndStoreInCache, populatePermissions } from './utils';
/**
* * Iterate through each of the content
* * Populates the block map, using the id and the optional name
* * Add the block to the cache
* * Execute the operation
* * If it contains nested contents, follow step 1
* @param contents The content create input
* @param parent_id Root parent id
* @param parent_table Root parent table
* @param options Props passed to the created block objects
*/
export async function contents(
contents: TBlockCreateInput[],
root_parent_id: string,
root_parent_table: 'collection' | 'block' | 'space',
options: Omit<INotionFabricatorOptions, 'cache_init_tracker'>,
cb?: (data: TBlock) => any
) {
// Metadata used for all blocks
const metadata = NotionInit.blockMetadata({
created_by_id: options.user_id,
last_edited_by_id: options.user_id,
space_id: options.space_id
});
const operations: IOperation[] = [];
const traverse = async (
contents: TBlockCreateInput[],
parent_id: string,
parent_table: 'collection' | 'block' | 'space'
) => {
for (let index = 0; index < contents.length; index++) {
const content = contents[index],
block_id = NotionIdz.Generate.id((content as any).id);
// Common data to be used for all blocks
const common_data = {
id: block_id,
parent_table,
parent_id,
type: content.type
} as any;
if ((content as any).properties)
common_data.properties = { ...(content as any).properties };
if ((content as any).format)
common_data.format = { ...(content as any).format };
/* else if (type === "drive") {
const {
accounts
} = await this.getGoogleDriveAccounts();
await this.initializeGoogleDriveBlock({
blockId: block_id,
fileId: (content as IDriveInput).file_id as string,
token: accounts[0].token
});
} */
if (
content.type === 'collection_view_page' ||
content.type === 'collection_view'
) {
// Construct the collection first
const collection_id = NotionIdz.Generate.id(content.collection_id),
view_ids: string[] = [];
// Construct the collection block object
const data: ICollectionBlock = {
...common_data,
...metadata,
collection_id: collection_id,
view_ids
};
if (content.type === 'collection_view_page')
(data as ICollectionViewPage).permissions = [
populatePermissions(options.user_id, content.isPrivate)
];
const [
,
views_data,
collection_operations
] = await CreateData.collection(
{ ...content, collection_id },
block_id,
options
);
views_data.forEach((view_data) => view_ids.push(view_data.id));
operations.push(
...collection_operations,
await executeOperationAndStoreInCache<ICollectionViewPage>(
data as any,
options,
cb
)
);
await traverse(content.rows, collection_id, 'collection');
} else if (content.type === 'factory') {
const factory_data: IFactory = {
content: [],
...common_data,
...metadata
};
operations.push(
await executeOperationAndStoreInCache<IFactory>(
factory_data,
options,
cb
)
);
await traverse(content.contents, block_id, 'block');
} else if (content.type === 'linked_db') {
const { collection_id, views } = content,
view_ids: string[] = [],
// fetch the referenced collection id
collection = (await NotionCache.fetchDataOrReturnCached(
'collection',
collection_id,
options
)) as ICollection,
// Create the views separately, without creating the collection, as its only referencing one
collection_view_data: ICollectionView = {
...common_data,
...metadata,
view_ids,
collection_id,
type: 'collection_view'
};
const [views_data, view_operations] = await CreateData.views(
collection,
views,
options,
block_id
);
views_data.forEach(({ id }) => view_ids.push(id));
operations.push(
...view_operations,
await executeOperationAndStoreInCache<ICollectionView>(
collection_view_data,
options,
cb
)
);
} else if (content.type === 'page') {
// Construct the default page object, with permissions data
const page_data: IPage = {
...common_data,
...metadata,
content: [],
is_template:
(content as any).is_template && parent_table === 'collection',
permissions: [populatePermissions(options.user_id, content.isPrivate)]
};
operations.push(
await executeOperationAndStoreInCache<IPage>(page_data, options, cb)
);
const space_view = NotionLineage.Space.getSpaceView(
options.space_id,
options.cache
);
if (space_view && content.isBookmarked === true)
operations.push(
...(await NotionLineage.updateChildContainer<ISpaceView>(
'space_view',
space_view.id,
true,
block_id,
'bookmarked_pages',
options
))
);
await traverse(content.contents, block_id, 'block');
} else if (content.type === 'column_list') {
const { contents } = content,
column_ids: string[] = [];
const column_list_data: IColumnList = {
content: column_ids,
...common_data,
...metadata
};
operations.push(
await executeOperationAndStoreInCache(column_list_data, options, cb)
);
// For each contents create a column
for (let index = 0; index < contents.length; index++) {
const column_id = NotionIdz.Generate.id(contents[index].id),
column_data: IColumn = {
id: column_id,
parent_id: block_id,
parent_table: 'block',
type: 'column',
format: {
column_ratio: 1 / contents.length
},
...metadata,
content: []
} as any;
operations.push(
await executeOperationAndStoreInCache<IColumn>(
column_data,
options,
cb
)
);
await traverse(contents[index].contents, column_id, 'block');
column_ids.push(column_id);
}
operations.push(
NotionOperations.Chunk.block.set(block_id, ['content'], column_ids)
);
} else if (
content.type.match(
/^(embed|gist|abstract|invision|framer|whimsical|miro|pdf|loom|codepen|typeform|tweet|maps|figma|video|audio|image)$/
)
) {
const response = await NotionEndpoints.Queries.getGenericEmbedBlockData(
{
pageWidth: 500,
source: (content as any).properties.source[0][0] as string,
type: content.type as any
},
options
);
NotionUtils.deepMerge(response, {
format: (content as any).format,
properties: (content as any).properties
});
NotionUtils.deepMerge(common_data, {
format: response.format,
properties: response.properties,
type: response.type
});
const block_data: any = {
...common_data,
...metadata
};
operations.push(
await executeOperationAndStoreInCache<any>(block_data, options, cb)
);
} else if (content.type !== 'link_to_page') {
// Block is a non parent type
const block_data: any = {
...common_data,
...metadata
};
operations.push(
await executeOperationAndStoreInCache<any>(block_data, options, cb)
);
}
if ((content as any).discussions)
operations.push(
...NotionDiscourse.Discussions.create(
block_id,
(content as any).discussions,
options
).operations
);
if (content.type === 'bookmark') {
await NotionOperations.executeOperations(operations, options);
await NotionEndpoints.Mutations.setBookmarkMetadata(
{
blockId: block_id,
url: (content.properties as WebBookmarkProps).link[0][0]
},
options
);
await NotionCache.updateCacheManually([[block_id, 'block']], options);
}
// If the type is link_to_page use the referenced page_id as the content id else use the block id
const content_id =
content.type === 'link_to_page' ? content.page_id : block_id;
// if the parent table is either a block, or a space, or a collection and page is a template, push to child append operation to the stack
if (parent_table === 'block')
operations.push(
...(await NotionLineage.updateChildContainer<IPage>(
parent_table,
parent_id,
true,
content_id,
'content',
options
))
);
else if (parent_table === 'space')
operations.push(
...(await NotionLineage.updateChildContainer<ISpace>(
parent_table,
parent_id,
true,
content_id,
'pages',
options
))
);
else if (parent_table === 'collection' && (content as any).is_template)
operations.push(
...(await NotionLineage.updateChildContainer<ICollection>(
parent_table,
parent_id,
true,
content_id,
'template_pages',
options
))
);
options.logger && NotionLogger.method.info(`CREATE block ${content_id}`);
}
};
await traverse(contents, root_parent_id, root_parent_table);
await NotionOperations.executeOperations(operations, options);
} | the_stack |
import * as DOM from 'vs/base/browser/dom';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { alert as alertFn } from 'vs/base/browser/ui/aria/aria';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import * as strings from 'vs/base/common/strings';
import { Range } from 'vs/editor/common/core/range';
import { FindMatch } from 'vs/editor/common/model';
import { MATCHES_LIMIT } from 'vs/editor/contrib/find/browser/findModel';
import { FindReplaceState } from 'vs/editor/contrib/find/browser/findState';
import { NLS_MATCHES_LOCATION, NLS_NO_RESULTS } from 'vs/editor/contrib/find/browser/findWidget';
import { localize } from 'vs/nls';
import { IMenuService } from 'vs/platform/actions/common/actions';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { NotebookFindFilters } from 'vs/workbench/contrib/notebook/browser/contrib/find/findFilters';
import { FindModel } from 'vs/workbench/contrib/notebook/browser/contrib/find/findModel';
import { SimpleFindReplaceWidget } from 'vs/workbench/contrib/notebook/browser/contrib/find/notebookFindReplaceWidget';
import { CellEditState, INotebookEditor, INotebookEditorContribution } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { KEYBINDING_CONTEXT_NOTEBOOK_FIND_WIDGET_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys';
const FIND_HIDE_TRANSITION = 'find-hide-transition';
const FIND_SHOW_TRANSITION = 'find-show-transition';
let MAX_MATCHES_COUNT_WIDTH = 69;
const PROGRESS_BAR_DELAY = 200; // show progress for at least 200ms
export interface IShowNotebookFindWidgetOptions {
isRegex?: boolean;
wholeWord?: boolean;
matchCase?: boolean;
matchIndex?: number;
focus?: boolean;
}
export class NotebookFindWidget extends SimpleFindReplaceWidget implements INotebookEditorContribution {
static id: string = 'workbench.notebook.find';
protected _findWidgetFocused: IContextKey<boolean>;
private _showTimeout: number | null = null;
private _hideTimeout: number | null = null;
private _previousFocusElement?: HTMLElement;
private _findModel: FindModel;
constructor(
private readonly _notebookEditor: INotebookEditor,
@IContextViewService contextViewService: IContextViewService,
@IContextKeyService contextKeyService: IContextKeyService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IContextMenuService contextMenuService: IContextMenuService,
@IMenuService menuService: IMenuService,
@IInstantiationService instantiationService: IInstantiationService,
) {
super(contextViewService, contextKeyService, themeService, configurationService, menuService, contextMenuService, instantiationService, new FindReplaceState<NotebookFindFilters>());
this._findModel = new FindModel(this._notebookEditor, this._state, this._configurationService);
DOM.append(this._notebookEditor.getDomNode(), this.getDomNode());
this._findWidgetFocused = KEYBINDING_CONTEXT_NOTEBOOK_FIND_WIDGET_FOCUSED.bindTo(contextKeyService);
this._register(this._findInput.onKeyDown((e) => this._onFindInputKeyDown(e)));
this.updateTheme(themeService.getColorTheme());
this._register(themeService.onDidColorThemeChange(() => {
this.updateTheme(themeService.getColorTheme());
}));
this._register(this._state.onFindReplaceStateChange((e) => {
this.onInputChanged();
if (e.isSearching) {
if (this._state.isSearching) {
this._progressBar.infinite().show(PROGRESS_BAR_DELAY);
} else {
this._progressBar.stop().hide();
}
}
if (this._findModel.currentMatch >= 0) {
const currentMatch = this._findModel.getCurrentMatch();
this._replaceBtn.setEnabled(currentMatch.isModelMatch);
}
const matches = this._findModel.findMatches;
this._replaceAllBtn.setEnabled(matches.length > 0 && matches.find(match => match.modelMatchCount < match.matches.length) === undefined);
if (e.filters) {
this._findInput.updateFilterState((this._state.filters?.markupPreview ?? false) || (this._state.filters?.codeOutput ?? false));
}
}));
this._register(DOM.addDisposableListener(this.getDomNode(), DOM.EventType.FOCUS, e => {
this._previousFocusElement = e.relatedTarget instanceof HTMLElement ? e.relatedTarget : undefined;
}, true));
}
private _onFindInputKeyDown(e: IKeyboardEvent): void {
if (e.equals(KeyCode.Enter)) {
this.find(false);
e.preventDefault();
return;
} else if (e.equals(KeyMod.Shift | KeyCode.Enter)) {
this.find(true);
e.preventDefault();
return;
}
}
protected onInputChanged(): boolean {
this._state.change({ searchString: this.inputValue }, false);
// this._findModel.research();
const findMatches = this._findModel.findMatches;
if (findMatches && findMatches.length) {
return true;
}
return false;
}
private findIndex(index: number): void {
this._findModel.find({ index });
}
protected find(previous: boolean): void {
this._findModel.find({ previous });
}
protected replaceOne() {
if (!this._notebookEditor.hasModel()) {
return;
}
if (!this._findModel.findMatches.length) {
return;
}
this._findModel.ensureFindMatches();
if (this._findModel.currentMatch < 0) {
this._findModel.find({ previous: false });
}
const currentMatch = this._findModel.getCurrentMatch();
const cell = currentMatch.cell;
if (currentMatch.isModelMatch) {
const match = currentMatch.match as FindMatch;
this._progressBar.infinite().show(PROGRESS_BAR_DELAY);
const replacePattern = this.replacePattern;
const replaceString = replacePattern.buildReplaceString(match.matches, this._state.preserveCase);
const viewModel = this._notebookEditor._getViewModel();
viewModel.replaceOne(cell, match.range, replaceString).then(() => {
this._progressBar.stop();
});
} else {
// this should not work
console.error('Replace does not work for output match');
}
}
protected replaceAll() {
if (!this._notebookEditor.hasModel()) {
return;
}
this._progressBar.infinite().show(PROGRESS_BAR_DELAY);
const replacePattern = this.replacePattern;
const cellFindMatches = this._findModel.findMatches;
const replaceStrings: string[] = [];
cellFindMatches.forEach(cellFindMatch => {
const findMatches = cellFindMatch.matches;
findMatches.forEach((findMatch, index) => {
if (index < cellFindMatch.modelMatchCount) {
const match = findMatch as FindMatch;
const matches = match.matches;
replaceStrings.push(replacePattern.buildReplaceString(matches, this._state.preserveCase));
}
});
});
const viewModel = this._notebookEditor._getViewModel();
viewModel.replaceAll(this._findModel.findMatches, replaceStrings).then(() => {
this._progressBar.stop();
});
}
protected findFirst(): void { }
protected onFocusTrackerFocus() {
this._findWidgetFocused.set(true);
}
protected onFocusTrackerBlur() {
this._previousFocusElement = undefined;
this._findWidgetFocused.reset();
}
protected onReplaceInputFocusTrackerFocus(): void {
// throw new Error('Method not implemented.');
}
protected onReplaceInputFocusTrackerBlur(): void {
// throw new Error('Method not implemented.');
}
protected onFindInputFocusTrackerFocus(): void { }
protected onFindInputFocusTrackerBlur(): void { }
override async show(initialInput?: string, options?: IShowNotebookFindWidgetOptions): Promise<void> {
super.show(initialInput, options);
this._state.change({ searchString: initialInput ?? '', isRevealed: true }, false);
if (typeof options?.matchIndex === 'number') {
if (!this._findModel.findMatches.length) {
await this._findModel.research();
}
this.findIndex(options.matchIndex);
} else {
this._findInput.select();
}
if (this._showTimeout === null) {
if (this._hideTimeout !== null) {
window.clearTimeout(this._hideTimeout);
this._hideTimeout = null;
this._notebookEditor.removeClassName(FIND_HIDE_TRANSITION);
}
this._notebookEditor.addClassName(FIND_SHOW_TRANSITION);
this._showTimeout = window.setTimeout(() => {
this._notebookEditor.removeClassName(FIND_SHOW_TRANSITION);
this._showTimeout = null;
}, 200);
} else {
// no op
}
}
replace(initialFindInput?: string, initialReplaceInput?: string) {
super.showWithReplace(initialFindInput, initialReplaceInput);
this._state.change({ searchString: initialFindInput ?? '', replaceString: initialReplaceInput ?? '', isRevealed: true }, false);
this._replaceInput.select();
if (this._showTimeout === null) {
if (this._hideTimeout !== null) {
window.clearTimeout(this._hideTimeout);
this._hideTimeout = null;
this._notebookEditor.removeClassName(FIND_HIDE_TRANSITION);
}
this._notebookEditor.addClassName(FIND_SHOW_TRANSITION);
this._showTimeout = window.setTimeout(() => {
this._notebookEditor.removeClassName(FIND_SHOW_TRANSITION);
this._showTimeout = null;
}, 200);
} else {
// no op
}
}
override hide() {
super.hide();
this._state.change({ isRevealed: false }, false);
this._findModel.clear();
this._notebookEditor.findStop();
this._progressBar.stop();
if (this._hideTimeout === null) {
if (this._showTimeout !== null) {
window.clearTimeout(this._showTimeout);
this._showTimeout = null;
this._notebookEditor.removeClassName(FIND_SHOW_TRANSITION);
}
this._notebookEditor.addClassName(FIND_HIDE_TRANSITION);
this._hideTimeout = window.setTimeout(() => {
this._notebookEditor.removeClassName(FIND_HIDE_TRANSITION);
}, 200);
} else {
// no op
}
if (this._previousFocusElement && this._previousFocusElement.offsetParent) {
this._previousFocusElement.focus();
this._previousFocusElement = undefined;
}
if (this._notebookEditor.hasModel()) {
for (let i = 0; i < this._notebookEditor.getLength(); i++) {
const cell = this._notebookEditor.cellAt(i);
if (cell.getEditState() === CellEditState.Editing && cell.editStateSource === 'find') {
cell.updateEditState(CellEditState.Preview, 'find');
}
}
}
}
override _updateMatchesCount(): void {
if (!this._findModel || !this._findModel.findMatches) {
return;
}
this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + 'px';
this._matchesCount.title = '';
// remove previous content
if (this._matchesCount.firstChild) {
this._matchesCount.removeChild(this._matchesCount.firstChild);
}
let label: string;
if (this._state.matchesCount > 0) {
let matchesCount: string = String(this._state.matchesCount);
if (this._state.matchesCount >= MATCHES_LIMIT) {
matchesCount += '+';
}
const matchesPosition: string = this._findModel.currentMatch < 0 ? '?' : String((this._findModel.currentMatch + 1));
label = strings.format(NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
} else {
label = NLS_NO_RESULTS;
}
this._matchesCount.appendChild(document.createTextNode(label));
alertFn(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString));
MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
}
private _getAriaLabel(label: string, currentMatch: Range | null, searchString: string): string {
if (label === NLS_NO_RESULTS) {
return searchString === ''
? localize('ariaSearchNoResultEmpty', "{0} found", label)
: localize('ariaSearchNoResult', "{0} found for '{1}'", label, searchString);
}
// TODO@rebornix, aria for `cell ${index}, line {line}`
return localize('ariaSearchNoResultWithLineNumNoCurrentMatch', "{0} found for '{1}'", label, searchString);
}
override dispose() {
this._notebookEditor?.removeClassName(FIND_SHOW_TRANSITION);
this._notebookEditor?.removeClassName(FIND_HIDE_TRANSITION);
this._findModel.dispose();
super.dispose();
}
} | the_stack |
module TDev.RT {
// meta in messages coming from a logger will be augmented with the following
export interface StdMeta {
contextId: string;
contextDuration: number;
contextUser: string;
}
export interface AppLogTransport {
log? : (level : number, category : string, msg: string, meta?: any) => void;
logException?: (err: any, meta?: any) => void;
logTick?: (category: string, id: string, meta: any) => void;
logMeasure?: (category: string, id: string, value: number, meta: any) => void;
id?: string;
domain?: any;
}
//? A custom logger
//@ stem("logger")
export class AppLogger extends RTValue {
public created: number;
public parent: AppLogger;
public minLevel = App.DEBUG;
constructor(public category : string) {
super();
this.category = this.category || "";
this.created = Util.perfNow()
}
//? Logs a debug message
public debug(message: string, s:IStackFrame) {
this.log("debug", message, undefined, s);
}
//? Logs an informational message
public info(message: string, s:IStackFrame) {
this.log("info", message, undefined, s);
}
//? Logs a warning message
public warning(message: string, s:IStackFrame) {
this.log("warning", message, undefined, s);
}
//? Logs an error message
public error(message: string, s:IStackFrame) {
this.log("error", message, undefined, s);
}
private stringToLevel(level:string)
{
switch (level.trim().toLowerCase()) {
case 'debug': return App.DEBUG;
case 'warning': return App.WARNING;
case 'error': return App.ERROR;
default: return App.INFO;
}
}
//? Logs a new message with optional metadata. The level follows the syslog convention.
//@ [level].deflStrings("info", "debug", "warning", "error") [meta].deflExpr('invalid->json_object')
public log(level: string, message: string, meta: JsonObject, s:IStackFrame) {
var ilevel = this.stringToLevel(level);
if (ilevel > this.minLevel) return
App.logEvent(ilevel, this.category, message, this.augmentMeta(meta ? meta.value() : undefined, s));
}
//? Set minimum logging level for this logger (defaults to "debug").
//@ [level].deflStrings("info", "debug", "warning", "error")
//@ betaOnly
public set_verbosity(level: string, s:IStackFrame) {
this.minLevel = this.stringToLevel(level)
}
//? Get the current logging level for this logger (defaults to "debug").
//@ betaOnly
public verbosity(s:IStackFrame) : string {
if (this.minLevel == App.DEBUG) return "debug";
if (this.minLevel == App.WARNING) return "warning";
if (this.minLevel == App.ERROR) return "error";
return "info";
}
static findContext(s: IStackFrame) : any
{
while (s && !s.loggerContext) {
s = s.previous
if (s && s.isDetached) {
s = null
break
}
}
if (s) return s.loggerContext
return null
}
public contextInfo(s: IStackFrame) : StdMeta
{
var c = AppLogger.findContext(s)
if (!c) {
return null
} else {
var tm = Util.perfNow() - c.created
if (c.root.pauseOffset)
tm -= c.root.pauseOffset
var r = { contextId: c.id, contextDuration: Math.round(tm), contextUser: "" }
for (var p = c; p; p = p.prev)
if (!r.contextUser) r.contextUser = p.userid || ""
return r
}
}
public setMetaFromContext(v: any, s: IStackFrame)
{
var i = this.contextInfo(s)
if (i) {
v.contextId = i.contextId
v.contextDuration = i.contextDuration
v.contextUser = i.contextUser
}
}
private augmentMeta(meta: JsonObject, s: IStackFrame) : any
{
var v = meta ? meta.value() : null
if (!AppLogger.findContext(s)) return v || {}
if (v) v = Util.jsonClone(v)
else v = {}
this.setMetaFromContext(v, s)
return v
}
//? Get the userid attached to the current context, or empty.
//@ betaOnly
public set_context_user(userid:string, s: IStackFrame)
{
var c = AppLogger.findContext(s)
if (!c) Util.userError("No current context")
if (c) c.userid = userid
}
//? Get the userid attached to the current context, or empty.
//@ betaOnly
public context_user(s: IStackFrame) : string
{
var i = this.contextInfo(s)
if (!i || !i.contextUser) return ""
return i.contextUser
}
//? The unique id of current context, or empty if in global scope.
//@ betaOnly
public context_id(s: IStackFrame) : string
{
var i = this.contextInfo(s)
if (!i) return ""
return i.contextId
}
//? Stop counting time in all current contexts
//@ betaOnly
public context_pause(s: IStackFrame)
{
var c = AppLogger.findContext(s)
if (c) {
c.root.pauseStart = Util.perfNow()
}
}
//? Start counting time again in all current contexts
//@ betaOnly
public context_resume(s: IStackFrame)
{
var c = AppLogger.findContext(s)
if (c) {
c = c.root
if (c.pauseStart) {
c.pauseOffset = Util.perfNow() - c.pauseStart
c.pauseStart = 0
}
}
}
//? How long the current logger has been executing for in milliseconds.
//@ betaOnly
public logger_duration(s: IStackFrame) : number
{
return Util.perfNow() - this.created
}
//? How long the current context has been executing for in milliseconds.
//@ betaOnly
public context_duration(s: IStackFrame) : number
{
var i = this.contextInfo(s)
if (i)
return i.contextDuration
return Util.perfNow() - this.created
}
//? Log a custom event tick in any registered performance logger.
//@ betaOnly
public tick(id: string, s: IStackFrame)
{
if (!id) return;
App.logTick(this.category, id, this.augmentMeta(null, s));
}
//? Log a custom event tick, including specified meta information, in any registered performance logger.
//@ betaOnly
public custom_tick(id: string, meta: JsonObject, s: IStackFrame)
{
if (!id) return;
App.logTick(this.category, id, this.augmentMeta(meta, s));
}
//? Log a measure in any registered performance logger.
//@ betaOnly
public measure(id: string, value: number, s: IStackFrame)
{
if (!id) return;
App.logMeasure(this.category, id, value, this.augmentMeta(null, s))
}
//? Start new logging context when you're starting a new task (eg, handling a request)
//@ betaOnly
public new_context(s:IStackFrame)
{
var prev = AppLogger.findContext(s)
var ctx:any = {
id: prev ? prev.id + "." + ++prev.numCh : Random.uniqueId(8),
prev: prev,
created: Util.perfNow(),
numCh: 0,
}
if (prev)
ctx.root = prev.root
else ctx.root = ctx
s.loggerContext = ctx
}
//? Starts a timed sub-logger. The task name is concatenated to the current logger category.
//@ betaOnly
public start(task: string): AppLogger {
var name = this.category;
if (name) name += ".";
name += task;
var logger = new AppLogger(name);
logger.parent = this;
return logger;
}
//? Ends a time sub-logger and reports the time.
//@ betaOnly
public end() {
if (this.parent) {
App.logMeasure(this.category, "LoggerStop", Util.perfNow() - this.created, null);
this.parent = undefined;
}
}
}
export class AppLogView {
private searchBox: HTMLInputElement;
private chartsEl: HTMLElement;
private logsEl: HTMLElement;
private _reversed = false;
public element: HTMLElement;
public maxItems = Browser.isMobile ? 200 : 2000;
public refreshRate = Browser.isMobile ? 500 : 100;
static current:AppLogView;
constructor() {
// search bar
AppLogView.current = this;
this.searchBox = HTML.mkTextInput("text", lf("Filter..."), "search");
this.searchBox.classList.add("logSearchInput");
Util.onInputChange(this.searchBox, v => this.update());
this.chartsEl = div(''); this.chartsEl.style.display = 'none';
this.logsEl = div('');
this.element = div('', this.searchBox, div('logView', this.chartsEl, this.logsEl));
Util.setupDragToScroll(this.element);
this.element.withClick(() => { }, true);
this.update();
}
public setFilter(filter: string) {
this.searchBox.value = filter || "";
this.update();
}
public showAsync() : Promise {
return new Promise((onSuccess, onError, onProgress) => {
var m = new ModalDialog();
m.onDismiss = () => onSuccess(undefined);
m.add(this.element);
m.setScroll();
m.fullScreen();
m.show();
});
}
private transport: AppLogTransport;
public attachLogEvents() {
if (!this.transport) {
var start = Util.now();
this.transport = {
log: (level: number, category: string, msg: string, meta?: any) => {
var lm = App.createLogMessage(level, category, msg, meta);
lm.elapsed = Util.elapsed(start, Util.now());
this.append([lm]);
}
};
App.addTransport(this.transport);
}
}
public removeLogEvents() {
if (this.transport) {
App.removeTransport(this.transport);
this.transport = undefined;
}
}
public charts(visible: boolean) {
this.chartsEl.style.display = visible ? "block" : "none";
}
public search(visible: boolean) {
this.searchBox.style.display = visible ? "block" : "none";
}
public reversed(r: boolean) {
this._reversed = r;
this.update();
}
private pendingChartUpdate = false;
private update() {
var els = Util.childNodes(this.logsEl);
var terms = this.searchBox.value.toLowerCase();
if (!terms) els.forEach(el => el.style.display = 'block');
else els.forEach(el => {
if (el.innerText.toLowerCase().indexOf(terms) > -1) {
el.style.display = 'block';
} else el.style.display = 'none';
});
if (this.chartsEl.style.display == 'block' && !this.pendingChartUpdate) {
this.pendingChartUpdate = true;
Util.setTimeout(this.refreshRate, () => {
this.generateLogCharts();
this.pendingChartUpdate = false;
});
}
}
public onMessages : (els: HTMLElement[]) => void;
private temp: HTMLElement;
public append(msgs: LogMessage[]) {
function levelToClass(level: number) {
if (level <= RT.App.ERROR) return "error";
else if (level <= RT.App.WARNING) return "warning";
else if (level <= RT.App.INFO) return "info";
else if (level <= RT.App.DEBUG) return "debug";
else return "noisy";
}
var res = [];
msgs.filter(msg => !!msg).forEach((lvl, index) => {
var msg = lvl.msg;
var txt = Util.htmlEscape(msg)
.replace(/https?:\/\/[^\s\r\n"'`]+/ig, (m) => "<a href=\"" + m + "\" target='_blank' rel='nofollow'>" + m + "</a>")
.replace(/\b(StK[A-Za-z0-9]{8,500})/g, (m) => " <a href='#cmd:search:" + m + "'>" + m + "</a>")
if (lvl.meta && lvl.meta.contextId) {
var searchTerm = Util.htmlEscape(lvl.meta.contextId.replace(/\..*/, ""))
txt += " <span class='logMeta'>[<a href='#cmd:logfilter:" + searchTerm + "'>" +
Util.htmlEscape(lvl.meta.contextId) +
"</a>: " + Math.round(lvl.meta.contextDuration) + "ms]</span>"
}
var crash: RuntimeCrash = undefined;
if (lvl.meta && lvl.meta && lvl.meta.kind === 'crash')
crash = <RuntimeCrash>lvl.meta;
res.push("<div class='logMsg' data-level='" + levelToClass(lvl.level) + "' data-timestamp='" + lvl.timestamp + "'"
+ (crash ? " data-crash='" + Util.htmlEscape(JSON.stringify(crash)) + "'" : "")
+ ">"
+ (lvl.elapsed ? (lvl.elapsed + '> ') : '')
+ (lvl.category ? (Util.htmlEscape(lvl.category) + ': ') : '')
+ txt
+ "</div>");
});
var temp = div(''); Browser.setInnerHTML(temp, res.join(""));
var nodes = Util.childNodes(temp);
if (this.onMessages) this.onMessages(nodes);
var todrop = this.logsEl.childElementCount + nodes.length - this.maxItems;
while(todrop-- > 0 && this.logsEl.firstElementChild)
this.logsEl.removeChild(this._reversed ? this.logsEl.lastElementChild : this.logsEl.firstElementChild);
var n = Math.min(nodes.length, this.maxItems);
if (this._reversed) {
for (var i = n-1; i >=0; --i)
this.logsEl.insertBefore(nodes[i], this.logsEl.firstElementChild);
} else {
for (var i = 0; i < n; ++i)
this.logsEl.appendChild(nodes[i]);
}
this.update();
}
public prependHTML(e:HTMLElement)
{
this.logsEl.insertBefore(e, this.logsEl.firstElementChild);
}
private series: TDev.StringMap<{ points: RT.Charts.Point[]; canvas?: HTMLCanvasElement; d? : HTMLElement }> = {};
private generateLogCharts() : void {
var els = Util.childNodes(this.logsEl).filter(el => el.style.display == 'block');
Object.keys(this.series).forEach(key => this.series[key].points = []);
// collect data
var timestart = 0;
els.forEach((elt, index) => {
var msg = elt.innerText; if (!msg) return;
var timestamp = parseFloat(elt.getAttribute("data-timestamp"))
if (index == 0) timestart = timestamp;
// parse out data
var f: number;
msg.replace(/\b([a-z]\w*)\b\s*[:=]\s*(-?\d+(\.\d+)?(e\d+)?)\s*$/ig, (mtch, key, v) => {
var value = parseFloat(v);
if (!this.series[key]) this.series[key] = { points: [] };
var x = (timestamp - timestart) / 1000.0;
this.series[key].points.push(new RT.Charts.Point(x, value));
return mtch;
});
});
// render series
Object.keys(this.series).forEach(key => {
var serie = this.series[key];
var points = serie.points;
if (points.length < 5) {
if (serie.d) serie.d.removeSelf();
delete this.series[key];
}
else {
if (!serie.canvas) {
serie.canvas = <HTMLCanvasElement>document.createElement("canvas");
serie.canvas.width = SizeMgr.windowWidth * 0.8;
serie.canvas.height = serie.canvas.width / 7;
serie.canvas.style.display = 'block';
serie.canvas.style.cursor = 'pointer';
serie.canvas.style.marginTop = "0.5em";
serie.canvas.style.width = "100%";
serie.canvas.withClick(() => {
var rows = serie.points.map(p => p.x + "\t" + p.y);
rows.unshift("t\t" + key);
var csv = rows.join('\n');
ShareManager.copyToClipboardAsync(csv)
.done(() => HTML.showProgressNotification(lf("time serie copied to clipboard")));
});
serie.d = div('logMsg', spanDirAuto(key), serie.canvas);
this.chartsEl.appendChild(serie.d);
}
var chart = new RT.Charts.CanvasChart();
chart.backgroundColor = "#000";
chart.gridColor = "#ccc";
chart.lineColor = "#0c0";
chart.axesColor = "#000";
chart.graphLineWidth = 3;
chart.gridCols = 11;
chart.gridRows = 5;
chart.drawChart(serie.canvas, points);
}
});
}
}
//? Various properties of application environment
export class AppEnv
{
private temporarySettings: TDev.StringMap<string> = {};
//? Retreives an in-memory editor setting
//@ flow(SourceWeb)
public temporary_setting(key: string) : string {
return this.temporarySettings[key];
}
//? Sets an in-memory editor setting. The setting is stored until the page is refreshed
//@ flow(SinkWeb)
public set_temporary_setting(key: string, value: string) {
this.temporarySettings[key] = value;
}
//? Get the browser name and version
public user_agent() : string
{
return navigator.userAgent
}
//? Indicates if the `app->run_command` action can be used to run shell commands.
//@ betaOnly
public has_shell(): boolean {
return !!Browser.localProxy;
}
//? Indicates if the `app->host_exec` action can be used to run host commands.
//@ betaOnly
public has_host(): boolean {
return Browser.isHosted;
}
//? Where are we running from: "editor", "website", "nodejs", "mobileapp", "plugin"
public runtime_kind(s:IStackFrame) : string
{
// TODO mobileapp not implemented yet
return s.rt.runtimeKind()
}
//? Get device 'size': "phone", "tablet", or "desktop"
public form_factor() : string
{
if (Browser.isCellphone) return "phone"
if (Browser.isTablet) return "tablet"
return "desktop"
}
//? Get current OS: "windows", "osx", "linux", "wp", "ios", "android", ...
public operating_system() : string
{
if (Browser.isAndroid) return "android";
if (Browser.isTrident && Browser.isCellphone) return "wp";
if (Browser.isMobileSafari) return "ios";
if (Browser.isMacOSX) return "osx";
var c = Browser.platformCaps
for (var i = 0; i < c.length; ++i)
switch (c[i]) {
case "win": return "windows"
case "x11": return "linux"
}
return "unknown"
}
//? Return URL of the cloud backend service if any.
public backend_url(s:IStackFrame) : string
{
return s.rt.compiled.azureSite
}
//? Initial URL used to launch the website; invalid when `->runtime kind` is "editor"
public initial_url() : string
{
return Runtime.initialUrl
}
}
//? Interact with the app runtime
//@ skill(3)
export module App
{
export function createInfoMessage(s: string) : LogMessage {
return createLogMessage(App.INFO, "", s, undefined);
}
export function createLogMessage(level : number, category : string, s:string, meta: any) : LogMessage
{
var m = <LogMessage>{
timestamp: Util.now(),
level: level,
category: category,
msg: s,
meta: meta
}
return m;
}
class Logger {
logIdx = -1;
logMsgs:LogMessage[] = [];
logSz = Browser.isNodeJS ? 2000 : 300;
addMsg(level : number, category : string, s:string, meta: any)
{
var m = createLogMessage(level, category, s, meta);
if (this.logIdx >= 0) {
this.logMsgs[this.logIdx++] = m;
if (this.logIdx >= this.logSz) this.logIdx = 0;
} else {
this.logMsgs.push(m);
if (this.logMsgs.length >= this.logSz)
this.logIdx = 0;
}
}
getMsgs():LogMessage[]
{
var i = this.logIdx;
var res = [];
var wrapped = false;
if (i < 0) i = 0;
var n = Date.now()
while (i < this.logMsgs.length) {
var m = this.logMsgs[i]
var diff = ("00000000" + (n - m.timestamp)).slice(-7).replace(/(\d\d\d)$/, (k) => "." + k);
res.push(<LogMessage>{
level: m.level,
category: m.category,
msg: m.msg,
elapsed: diff,
meta: m.meta,
timestamp: m.timestamp
});
if (++i == this.logMsgs.length && !wrapped) {
wrapped = true;
i = 0;
}
if (wrapped && i >= this.logIdx) break;
}
res.reverse()
return res;
}
}
var logger:Logger;
export var transports: AppLogTransport[] = [];
export function clearLogs() {
logger = null;
transports = [];
}
export function startLogger()
{
logger = new Logger();
transports = [];
}
export function rt_start(rt: Runtime): void
{
if (rt.liveMode())
logger = null
else if (!logger)
logger = new Logger();
transports = [];
}
export function rt_stop(rt: Runtime)
{
//transports = [];
}
//? Creates a specialized logger
export function create_logger(category : string) : AppLogger {
return new AppLogger(category);
}
// Adds a transport for the app log
export function addTransport(transport: AppLogTransport) {
if (transport) {
removeTransport(transport);
transports.push(transport);
}
}
export function removeTransport(transport: AppLogTransport) {
if (transport) {
var i = transports.indexOf(transport);
if (i > -1) transports.splice(i, 1);
}
}
export var ERROR = 3;
export var WARNING = 4;
export var INFO = 6;
export var DEBUG = 7;
//? Appends this message to the debug log.
//@ oldName("time->log")
export function log(message: string): void
{
logEvent(INFO, "", message, undefined);
}
export function transportFailed(t:AppLogTransport, tp:string, err:any) {
if (t.id) tp = " (" + t.id + ")"
Util.log(tp + ": transport failed. " + (err.stack || err.message || err))
}
export var runTransports = (id:string, run:(t:AppLogTransport) => void) =>
{
transports.forEach(transport => {
try {
run(transport)
} catch (err) {
transportFailed(transport, id, err)
}
});
}
export function logException(err: any, meta? : any): void {
if (err.tdSkipReporting) {
logEvent(DEBUG, "skipped-crash", err.message || err + "", null)
return
}
if (err.tdIsSecondary) {
logEvent(DEBUG, "secondary-crash", err.message || err + "", null)
return
}
try {
if (Runtime.theRuntime)
Runtime.theRuntime.augmentException(err)
} catch (e) { }
if (err.tdMeta) {
if (meta)
Object.keys(meta).forEach(k => {
err.tdMeta[k] = meta[k]
})
meta = err.tdMeta
}
runTransports("logException", t => t.logException && t.logException(err, meta))
var msg = err.stack
if (!msg) {
msg = err.message || (err + "")
if (err.tdMeta && err.tdMeta.compressedStack)
msg += " at " + err.tdMeta.compressedStack
}
logEvent(ERROR, "crash", msg, meta);
}
export function logEvent(level: number, category: string, message: string, meta: any): void {
level = Math.max(0, Math.floor(level));
category = category || "";
message = message || "";
runTransports("logEvent", t => t.log && t.log(level, category, message, meta))
if (logger) {
logger.addMsg(level, category, message, meta)
Util.log((category || "log") + ": " + message);
}
}
export function logTick(category: string, id: string, meta:any) {
runTransports("logTick", t => t.logTick && t.logTick(category, id, meta))
if (!meta || !meta.skipLog)
App.logEvent(App.INFO, category, id, meta);
}
export function logMeasure(category:string, id: string, value: number, meta: any) {
var lmeta = Util.jsonClone(meta) || {};
lmeta.measureId = id
lmeta.measureValue = value
runTransports("logMeasure", t => t.logMeasure && t.logMeasure(category, id, value, meta))
if (!meta || !meta.skipLog)
App.logEvent(App.INFO, category, id + ": " + value, lmeta);
}
export function logs() : LogMessage[]
{
if (logger)
return logger.getMsgs()
else
return [];
}
//? Gets the binding of the current handler if any. This can be used to delete a handler from itself.
export function current_handler(s:IStackFrame) : EventBinding {
return s.currentHandler;
}
//? Stops the app.
export function stop(r:ResumeCtx) : void
{
if (Browser.isCompiledApp)
App.restart("", r);
else
r.rt.stopAsync().done();
}
//? Gets the app script id if any; invalid if not available
export function script_id(s: IStackFrame): string {
return s.rt.currentScriptId || undefined;
}
//? Restarts the app and pops a restart dialog
export function restart(message: string, r: ResumeCtx): void {
var rt = r.rt;
if (Cloud.isRestricted()) {
rt.stopAsync()
.then(() => rt.rerunAsync())
.done();
return;
}
var score = Bazaar.cachedScore(rt);
var scriptId = rt.currentScriptId;
rt.stopAsync().done(() => {
var m = new ModalDialog();
m.add(div('wall-dialog-huge wall-dialog-text-center', message || lf("try again!")));
if (score > 0)
m.add(div('wall-dialog-large wall-dialog-text-center', lf("your best score: {0}", score)));
m.add(div('wall-dialog-body wall-dialog-extra-space wall-dialog-text-center',
HTML.mkButton(lf("play again"),() => {
tick(Ticks.runtimePlayAgain);
m.dismiss();
rt.rerunAsync().done();
}, 'wall-dialog-button-huge'),
Browser.notifyBackToHost ? HTML.mkButton(lf("back"),() => {
tick(Ticks.runtimeBack);
m.dismiss();
Util.externalNotify("exit");
}) : null
));
if (scriptId && score > 0) {
Bazaar.loadLeaderboardItemsAsync(scriptId)
.done((els: HTMLElement[]) => {
if (els && els.length > 0) {
m.add(div('wall-dialog-body wall-dialog-extra-space ', els));
m.setScroll();
}
}, e => { });
}
m.fullWhite();
m.show();
});
}
//? Aborts the execution if the condition is false.
//@ [condition].defl(true)
export function fail_if_not(condition:boolean) : void
{
if (!condition)
Util.userError(lf("assertion violation"));
}
//? When exported server-side, retreives the value of a setting stored on the server. If not optional, fails if missing. Returns invalid if missing.
export function server_setting(key : string, optional : boolean, s : IStackFrame) : string {
if (!optional)
Util.userError(lf("only supported on exported node.js apps"), s.pc);
return undefined;
}
//? When exported, run `script` instead of the body of the action
//@ [calling_convention].defl("local")
//@ [script].lang("js")
export function javascript(calling_convention:string, script:string) : void
{
}
//? When exported, run `script` instead of the body of the action
//@ async
//@ [calling_convention].defl("local")
//@ [script].lang("js")
export function javascript_async(calling_convention:string, script:string, r:ResumeCtx) : void
{
r.resume()
}
//? Imports a dependent package which may be versioned. Package managers may be Node.JS npm, Bower, Apache cordova, Python Pip and TouchDevelop plugins. ``bower`` and ``client`` imports are not available within the touchdevelop.com domain.
//@ name("import") [manager].deflStrings("npm", "cordova", "bower", "client", "touchdevelop", "pip") [version].defl("*")
export function import_(manager : string, module: string, version: string): void {
}
//? When compiled to ARM Thumb, inline the body.
//@ [script].lang("thumb")
export function thumb(script:string) : void
{
}
//? Get the current incomming HTTP web request
//@ betaOnly
export function server_request(s:IStackFrame) : ServerRequest
{
return s.rt.getRestRequest();
}
//? Get the response corresponding to the current incomming HTTP web request
//@ betaOnly
export function server_response(s:IStackFrame) : ServerResponse
{
var r = s.rt.getRestRequest();
if (r) return r.response()
return undefined
}
//? Get the Editor interface
//@ betaOnly
export function editor(s:IStackFrame) : Editor
{
return s.rt.editorObj
}
var _env = new AppEnv()
//? Access various properties of application environment
//@ betaOnly
export function env() : AppEnv
{
return _env
}
//? Return runtime information about functions and types defined in script and its libraries
//@ betaOnly
//@ [what].deflStrings("actions")
export function reflect(what:string, s:IStackFrame):JsonObject
{
var ri = s.rt.compiled.reflectionInfo
if (ri.hasOwnProperty(what)) return JsonObject.wrap(ri[what])
return undefined
}
//? Runs a shell command. This action is only available when the script is running from a local web server.
//@ [cmd].deflStrings("shell", "mkdir", "writeFile", "readFile", "readDir", "writeFiles", "pythonEnv", "socket", "seriallist")
//@ cap(shell) returns(JsonObject) async
export function run_command(cmd: string, data: JsonObject, r: ResumeCtx) {
var proxyAsync = r.rt.host.localProxyAsync;
if (!proxyAsync) {
r.resumeVal(JsonObject.wrap({ error: 'notsupported', reason: lf("This command requires a local proxy.") }));
return;
}
r.rt.host.askSourceAccessAsync(lf("execute shell commands or manipulate files."),
lf("the shell and/or the file system. This script may be harmful for your computer. Do not allow this if you do not trust the source of this script."), false, true)
.then((allow :boolean) => {
if (!allow) return Promise.as(JsonObject.wrap({ error: 'denied', reason: lf("The user denied access to shell execution.") }));
else return proxyAsync(cmd, data ? data.value() : undefined);
})
.done(res => r.resumeVal(JsonObject.wrap(res)),
e => r.resumeVal(JsonObject.wrap({ error: 'proxyerror', message: e.message, stack: e.stack }))
)
}
//? Shows a dialog with the logs
//@ uiAsync betaOnly
export function show_logs(filter : string, r : ResumeCtx) {
r.resume();
showAppLogAsync(undefined, filter).done(() => { }, e => { });
}
export function showAppLogAsync(msgs?: LogMessage[], filter? : string, onMessages? : (els : HTMLElement[]) => void): Promise {
var view = new AppLogView();
view.onMessages = onMessages;
view.charts(true);
//view.reversed(true);
view.append(App.logs());
view.setFilter(filter);
if (msgs) view.append(msgs);
view.attachLogEvents();
return view.showAsync().then(() => view.removeLogEvents(), () => view.removeLogEvents());
}
export function showLog(msgs: LogMessage[], onMessages?: (els: HTMLElement[]) => void) {
var view = new AppLogView();
view.onMessages = onMessages;
view.append(msgs);
view.showAsync().done(() => { }, e => { });
}
//? Get HTML-rendered content of all comments 'executed' since last call
//@ dbgOnly
export function consume_rendered_comments(s:IStackFrame):string
{
var r = s.rt.renderedComments
s.rt.renderedComments = ""
return r
}
export function hostExecAsync(message: string): Promise {
return new Promise((onSuccess, onError, onProgress) => {
if (message == "td_access_token") {
if (!Cloud.hasPermission("post-raw"))
onSuccess(undefined)
Runtime.theRuntime.host.askSourceAccessAsync(lf("your private access token"),
lf("your Touch Develop access token. The script will be able to upload web content as you."), false, true)
.done((allow :boolean) => {
if (!allow) onSuccess(undefined)
else onSuccess(Cloud.getServiceUrl() + "/?access_token=" + Cloud.getAccessToken())
})
return;
}
// minecraft support
var mcefQuery = (<any>window).mcefQuery;
if (mcefQuery) {
mcefQuery({
request: message,
persistent: false,
onSuccess: function (response) {
onSuccess(response);
},
onFailure: function (error_code, error_message) {
App.logEvent(App.DEBUG, "app", "mcefQuery failed", undefined);
onSuccess(JSON.stringify({ error: error_code, message: error_message }));
}
});
return;
}
// cordova support
var cordova = (<any>window).cordova;
if (cordova && cordova.exec) {
try {
var payload = JSON.parse(message);
cordova.exec(function (result) {
onSuccess(JSON.stringify(result));
},
function (error) {
onSuccess(JSON.stringify({ error: error }));
},
payload.service,
payload.action,
payload.arguments);
}
catch (e) {
App.logEvent(App.DEBUG, "app", "window.cordova.exec failed", undefined);
onSuccess(undefined);
}
return;
}
// generic callback support
var exec = (<any>window).touchDevelopExec;
if (exec) {
try {
exec(message,(result) => { onSuccess(result); });
}
catch (e) {
App.logEvent(App.DEBUG, "app", "touchDevelopExec failed", undefined);
onSuccess(undefined);
}
return;
}
App.log("no host found");
onSuccess(undefined);
});
}
export function hostSubscribeAsync(rt : Runtime, message: string, handler : TextAction): Promise {
return new Promise((onSuccess, onError, onProgress) => {
var ev = new Event_();
var binding = ev.addHandler(handler);
// minecraft support
var mcefQuery = (<any>window).mcefQuery;
if (mcefQuery) {
try {
mcefQuery({
request: message,
persistent: true,
onSuccess: function (response) {
rt.queueLocalEvent(ev, [response], false, false);
},
onFailure: function (error_code, error_message) {
App.logEvent(App.DEBUG, "app", "mcefQuery failed: " + error_code, undefined);
}
});
} catch (e) {
onSuccess(undefined);
return;
}
onSuccess(binding);
return;
}
// cordova support
var cordova = (<any>window).cordova;
if (cordova && cordova.exec) {
try {
var payload = JSON.parse(message);
cordova.exec(function (result) {
rt.queueLocalEvent(ev, [JSON.stringify(result)], false, false);
},
function (error) {
App.logEvent(App.DEBUG, "app", "cordova.exec failed: " + error, undefined);
},
payload.service,
payload.action,
payload.arguments);
}
catch (e) {
App.logEvent(App.DEBUG, "app", "cordova.exec failed: " + e, undefined);
onSuccess(undefined);
return;
}
onSuccess(binding);
return;
}
// generic callback support
var exec = (<any>window).touchDevelopExec;
if (exec) {
try {
exec(message,(result) => {
rt.queueLocalEvent(ev, [JSON.stringify(result)], false, false);
});
}
catch (e) {
App.logEvent(App.DEBUG, "app", "touchDevelopExec failed", undefined);
onSuccess(undefined);
return;
}
onSuccess(binding);
return;
}
App.log("no host found");
onSuccess(undefined);
});
}
//? Invokes the host to execute a command described in the message and returns the response. There is no restriction on the format of the request and response. If not available or errored, returns invalid.
//@ async readsMutable returns(string) betaOnly
export function host_exec(message: string, r: ResumeCtx) {
return hostExecAsync(message).done(resp => r.resumeVal(resp));
}
//? Invokes the host to register an event listener described in the message.
//@ async readsMutable returns(EventBinding) betaOnly ignoreReturnValue
export function host_subscribe(message: string, handler: TextAction, r: ResumeCtx) {
return hostSubscribeAsync(r.rt, message, handler).done(resp => r.resumeVal(resp));
}
//? Allow execution of other events, before the current event finishes.
export function allow_other_events(s:IStackFrame) {
s.rt.eventExecuting = false;
}
}
} | the_stack |
import { AST_NODE_TYPES } from '@typescript-eslint/experimental-utils';
import rule from '../../src/rules/no-loop-func';
import { RuleTester } from '../RuleTester';
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});
ruleTester.run('no-loop-func', rule, {
valid: [
`
let someArray: MyType[] = [];
for (let i = 0; i < 10; i += 1) {
someArray = someArray.filter((item: MyType) => !!item);
}
`,
{
code: `
let someArray: MyType[] = [];
for (let i = 0; i < 10; i += 1) {
someArray = someArray.filter((item: MyType) => !!item);
}
`,
globals: {
MyType: 'readonly',
},
},
{
code: `
let someArray: MyType[] = [];
for (let i = 0; i < 10; i += 1) {
someArray = someArray.filter((item: MyType) => !!item);
}
`,
globals: {
MyType: 'writable',
},
},
`
type MyType = 1;
let someArray: MyType[] = [];
for (let i = 0; i < 10; i += 1) {
someArray = someArray.filter((item: MyType) => !!item);
}
`,
],
invalid: [],
});
// Forked from https://github.com/eslint/eslint/blob/bf2e367bf4f6fde9930af9de8b8d8bc3d8b5782f/tests/lib/rules/no-loop-func.js
ruleTester.run('no-loop-func ESLint tests', rule, {
valid: [
"string = 'function a() {}';",
`
for (var i = 0; i < l; i++) {}
var a = function () {
i;
};
`,
`
for (
var i = 0,
a = function () {
i;
};
i < l;
i++
) {}
`,
`
for (var x in xs.filter(function (x) {
return x != upper;
})) {
}
`,
{
code: `
for (var x of xs.filter(function (x) {
return x != upper;
})) {
}
`,
parserOptions: { ecmaVersion: 6 },
},
// no refers to variables that declared on upper scope.
`
for (var i = 0; i < l; i++) {
(function () {});
}
`,
`
for (var i in {}) {
(function () {});
}
`,
{
code: `
for (var i of {}) {
(function () {});
}
`,
parserOptions: { ecmaVersion: 6 },
},
// functions which are using unmodified variables are OK.
{
code: `
for (let i = 0; i < l; i++) {
(function () {
i;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
for (let i in {}) {
i = 7;
(function () {
i;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
for (const i of {}) {
(function () {
i;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
for (let i = 0; i < 10; ++i) {
for (let x in xs.filter(x => x != i)) {
}
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i = 0; i < l; i++) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i in {}) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i of {}) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i = 0; i < l; i++) {
(function () {
(function () {
a;
});
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i in {}) {
function foo() {
(function () {
a;
});
}
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
let a = 0;
for (let i of {}) {
() => {
(function () {
a;
});
};
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
var a = 0;
for (let i = 0; i < l; i++) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
var a = 0;
for (let i in {}) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: `
var a = 0;
for (let i of {}) {
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
},
{
code: [
'let result = {};',
'for (const score in scores) {',
' const letters = scores[score];',
" letters.split('').forEach(letter => {",
' result[letter] = score;',
' });',
'}',
'result.__default = 6;',
].join('\n'),
parserOptions: { ecmaVersion: 6 },
},
{
code: ['while (true) {', ' (function() { a; });', '}', 'let a;'].join(
'\n',
),
parserOptions: { ecmaVersion: 6 },
},
],
invalid: [
{
code: `
for (var i = 0; i < l; i++) {
(function () {
i;
});
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var i = 0; i < l; i++) {
for (var j = 0; j < m; j++) {
(function () {
i + j;
});
}
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i', 'j'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var i in {}) {
(function () {
i;
});
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var i of {}) {
(function () {
i;
});
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var i = 0; i < l; i++) {
() => {
i;
};
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
{
code: `
for (var i = 0; i < l; i++) {
var a = function () {
i;
};
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var i = 0; i < l; i++) {
function a() {
i;
}
a();
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionDeclaration,
},
],
},
{
code: `
for (
var i = 0;
(function () {
i;
})(),
i < l;
i++
) {}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (
var i = 0;
i < l;
(function () {
i;
})(),
i++
) {}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
while (i) {
(function () {
i;
});
}
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
do {
(function () {
i;
});
} while (i);
`,
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
// Warns functions which are using modified variables.
{
code: `
let a;
for (let i = 0; i < l; i++) {
a = 1;
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
for (let i in {}) {
(function () {
a;
});
a = 1;
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
for (let i of {}) {
(function () {
a;
});
}
a = 1;
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
for (let i = 0; i < l; i++) {
(function () {
(function () {
a;
});
});
a = 1;
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
for (let i in {}) {
a = 1;
function foo() {
(function () {
a;
});
}
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionDeclaration,
},
],
},
{
code: `
let a;
for (let i of {}) {
() => {
(function () {
a;
});
};
}
a = 1;
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
{
code: `
for (var i = 0; i < 10; ++i) {
for (let x in xs.filter(x => x != i)) {
}
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'i'" },
type: AST_NODE_TYPES.ArrowFunctionExpression,
},
],
},
{
code: `
for (let x of xs) {
let a;
for (let y of ys) {
a = 1;
(function () {
a;
});
}
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var x of xs) {
for (let y of ys) {
(function () {
x;
});
}
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'x'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
for (var x of xs) {
(function () {
x;
});
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'x'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
var a;
for (let x of xs) {
a = 1;
(function () {
a;
});
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
var a;
for (let x of xs) {
(function () {
a;
});
a = 1;
}
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
function foo() {
a = 10;
}
for (let x of xs) {
(function () {
a;
});
}
foo();
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
{
code: `
let a;
function foo() {
a = 10;
for (let x of xs) {
(function () {
a;
});
}
}
foo();
`,
parserOptions: { ecmaVersion: 6 },
errors: [
{
messageId: 'unsafeRefs',
data: { varNames: "'a'" },
type: AST_NODE_TYPES.FunctionExpression,
},
],
},
],
}); | the_stack |
import {ethers} from 'hardhat';
import {setupPermit} from './fixtures';
import {BigNumber, constants} from 'ethers';
import {_TypedDataEncoder, splitSignature} from 'ethers/lib/utils';
import {
expectEventWithArgs,
expectReceiptEventWithArgs,
waitFor,
} from '../utils';
import {expect} from '../chai-setup';
import {data712} from './data712';
const zeroAddress = constants.AddressZero;
const TEST_AMOUNT = BigNumber.from(10).mul('1000000000000000000');
describe('Permit', function () {
// Note: on test network, others[1] is sandAdmin, others[2] is sandBeneficiary
it('ERC20 Approval event is emitted when msg signer == owner', async function () {
const setUp = await setupPermit();
const {permitContract, sandContract, others, nonce, deadline} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
const receipt = await waitFor(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
);
const approvalEvent = await expectEventWithArgs(
sandContract,
receipt,
'Approval'
);
expect(approvalEvent.args[0]).to.equal(others[5]); // owner
expect(approvalEvent.args[1]).to.equal(others[3]); // spender
expect(approvalEvent.args[2]).to.equal(TEST_AMOUNT); // amount
});
it('Nonce is incremented for each Approval', async function () {
const setUp = await setupPermit();
const {permitContract, others, nonce, deadline} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
const checkNonce = await permitContract.nonces(others[5]);
expect(checkNonce).to.equal(0);
await waitFor(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
);
const nonceAfterApproval = await permitContract.nonces(others[5]);
expect(nonceAfterApproval).to.equal(1);
});
it('Permit function reverts if deadline has passed', async function () {
const setUp = await setupPermit();
const deadline = BigNumber.from(1382718400);
const {permitContract, others, nonce} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
await expect(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
).to.be.revertedWith('PAST_DEADLINE');
});
it('Permit function reverts if owner is zeroAddress', async function () {
const setUp = await setupPermit();
const {permitContract, others, nonce, deadline} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
await expect(
permitContract.permit(
zeroAddress,
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
).to.be.revertedWith('INVALID_SIGNATURE');
});
it('Permit function reverts if owner != msg signer', async function () {
const setUp = await setupPermit();
const {permitContract, others, nonce, deadline} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
await expect(
permitContract.permit(
others[4],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
).to.be.revertedWith('INVALID_SIGNATURE');
});
it('Permit function reverts if spender is not the approved spender', async function () {
const setUp = await setupPermit();
const {permitContract, others, nonce, deadline} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
await expect(
permitContract.permit(
others[5],
others[4],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
).to.be.revertedWith('INVALID_SIGNATURE');
});
it('Domain separator is public', async function () {
const setUp = await setupPermit();
const {permitContract, others, nonce, deadline} = setUp;
const domainSeparator = await permitContract.DOMAIN_SEPARATOR();
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const expectedDomainSeparator = _TypedDataEncoder.hashDomain(
permitData712.domain
);
expect(domainSeparator).to.equal(expectedDomainSeparator);
});
it('Non-approved operators cannot transfer ERC20 until approved', async function () {
const setUp = await setupPermit();
const {
permitContract,
sandContract,
sandAdmin,
sandBeneficiary,
others,
nonce,
deadline,
} = setUp;
const receiverOriginalBalance = await sandContract.balanceOf(others[4]);
expect(receiverOriginalBalance).to.equal(0);
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
// Give wallet some SAND
const sandContractAsAdmin = await sandContract.connect(
ethers.provider.getSigner(sandAdmin)
);
await waitFor(
sandContractAsAdmin.transferFrom(sandBeneficiary, others[5], TEST_AMOUNT)
);
const sandContractAsSpender = await sandContract.connect(
ethers.provider.getSigner(others[3])
);
await expect(
sandContractAsSpender.transferFrom(others[5], others[4], TEST_AMOUNT)
).to.be.revertedWith('Not enough funds allowed');
await waitFor(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
);
const receipt = await waitFor(
sandContractAsSpender.transferFrom(others[5], others[4], TEST_AMOUNT)
);
const receiverNewBalance = await sandContract.balanceOf(others[4]);
const firstTransferEvent = await expectReceiptEventWithArgs(
receipt,
'Transfer'
);
expect(firstTransferEvent.args[0]).to.equal(others[5]);
expect(firstTransferEvent.args[1]).to.equal(others[4]);
expect(firstTransferEvent.args[2]).to.equal(TEST_AMOUNT);
expect(receiverNewBalance).to.equal(
TEST_AMOUNT.add(receiverOriginalBalance)
);
});
it('Approved operators cannot transfer more ERC20 than their allowance', async function () {
const setUp = await setupPermit();
const {
permitContract,
sandContract,
sandAdmin,
sandBeneficiary,
others,
nonce,
deadline,
} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
// Give wallet lots of SAND
const sandContractAsAdmin = await sandContract.connect(
ethers.provider.getSigner(sandAdmin)
);
await waitFor(
sandContractAsAdmin.transferFrom(
sandBeneficiary,
others[5],
TEST_AMOUNT.mul(2)
)
);
const sandContractAsSpender = await sandContract.connect(
ethers.provider.getSigner(others[3])
);
await waitFor(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
);
await expect(
sandContractAsSpender.transferFrom(
others[5],
others[4],
TEST_AMOUNT.mul(2)
)
).to.be.revertedWith('Not enough funds allowed');
});
it('Approved operators cannot transfer more ERC20 than there is', async function () {
const setUp = await setupPermit();
const {
permitContract,
sandContract,
sandAdmin,
sandBeneficiary,
others,
nonce,
deadline,
} = setUp;
const approve = {
owner: others[5],
spender: others[3],
value: TEST_AMOUNT._hex,
nonce: nonce._hex,
deadline: deadline._hex,
};
const permitData712 = data712(permitContract, approve);
const flatSig = await ethers.provider.send('eth_signTypedData_v4', [
others[5],
permitData712,
]);
const sig = splitSignature(flatSig);
// Give wallet small amount of SAND
const sandContractAsAdmin = await sandContract.connect(
ethers.provider.getSigner(sandAdmin)
);
await waitFor(
sandContractAsAdmin.transferFrom(
sandBeneficiary,
others[5],
TEST_AMOUNT.div(2)
)
);
const sandContractAsSpender = await sandContract.connect(
ethers.provider.getSigner(others[3])
);
await waitFor(
permitContract.permit(
others[5],
others[3],
TEST_AMOUNT,
deadline,
sig.v,
sig.r,
sig.s
)
);
await expect(
sandContractAsSpender.transferFrom(others[5], others[4], TEST_AMOUNT)
).to.be.revertedWith('not enough fund');
});
}); | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class CognitoSync extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: CognitoSync.Types.ClientConfiguration)
config: Config & CognitoSync.Types.ClientConfiguration;
/**
* Initiates a bulk publish of all existing datasets for an Identity Pool to the configured stream. Customers are limited to one successful bulk publish per 24 hours. Bulk publish is an asynchronous request, customers can see the status of the request via the GetBulkPublishDetails operation.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
bulkPublish(params: CognitoSync.Types.BulkPublishRequest, callback?: (err: AWSError, data: CognitoSync.Types.BulkPublishResponse) => void): Request<CognitoSync.Types.BulkPublishResponse, AWSError>;
/**
* Initiates a bulk publish of all existing datasets for an Identity Pool to the configured stream. Customers are limited to one successful bulk publish per 24 hours. Bulk publish is an asynchronous request, customers can see the status of the request via the GetBulkPublishDetails operation.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
bulkPublish(callback?: (err: AWSError, data: CognitoSync.Types.BulkPublishResponse) => void): Request<CognitoSync.Types.BulkPublishResponse, AWSError>;
/**
* Deletes the specific dataset. The dataset will be deleted permanently, and the action can't be undone. Datasets that this dataset was merged with will no longer report the merge. Any subsequent operation on this dataset will result in a ResourceNotFoundException. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
deleteDataset(params: CognitoSync.Types.DeleteDatasetRequest, callback?: (err: AWSError, data: CognitoSync.Types.DeleteDatasetResponse) => void): Request<CognitoSync.Types.DeleteDatasetResponse, AWSError>;
/**
* Deletes the specific dataset. The dataset will be deleted permanently, and the action can't be undone. Datasets that this dataset was merged with will no longer report the merge. Any subsequent operation on this dataset will result in a ResourceNotFoundException. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
deleteDataset(callback?: (err: AWSError, data: CognitoSync.Types.DeleteDatasetResponse) => void): Request<CognitoSync.Types.DeleteDatasetResponse, AWSError>;
/**
* Gets meta data about a dataset by identity and dataset name. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.
*/
describeDataset(params: CognitoSync.Types.DescribeDatasetRequest, callback?: (err: AWSError, data: CognitoSync.Types.DescribeDatasetResponse) => void): Request<CognitoSync.Types.DescribeDatasetResponse, AWSError>;
/**
* Gets meta data about a dataset by identity and dataset name. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.
*/
describeDataset(callback?: (err: AWSError, data: CognitoSync.Types.DescribeDatasetResponse) => void): Request<CognitoSync.Types.DescribeDatasetResponse, AWSError>;
/**
* Gets usage details (for example, data storage) about a particular identity pool. This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
describeIdentityPoolUsage(params: CognitoSync.Types.DescribeIdentityPoolUsageRequest, callback?: (err: AWSError, data: CognitoSync.Types.DescribeIdentityPoolUsageResponse) => void): Request<CognitoSync.Types.DescribeIdentityPoolUsageResponse, AWSError>;
/**
* Gets usage details (for example, data storage) about a particular identity pool. This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
describeIdentityPoolUsage(callback?: (err: AWSError, data: CognitoSync.Types.DescribeIdentityPoolUsageResponse) => void): Request<CognitoSync.Types.DescribeIdentityPoolUsageResponse, AWSError>;
/**
* Gets usage information for an identity, including number of datasets and data usage. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
describeIdentityUsage(params: CognitoSync.Types.DescribeIdentityUsageRequest, callback?: (err: AWSError, data: CognitoSync.Types.DescribeIdentityUsageResponse) => void): Request<CognitoSync.Types.DescribeIdentityUsageResponse, AWSError>;
/**
* Gets usage information for an identity, including number of datasets and data usage. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
describeIdentityUsage(callback?: (err: AWSError, data: CognitoSync.Types.DescribeIdentityUsageResponse) => void): Request<CognitoSync.Types.DescribeIdentityUsageResponse, AWSError>;
/**
* Get the status of the last BulkPublish operation for an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getBulkPublishDetails(params: CognitoSync.Types.GetBulkPublishDetailsRequest, callback?: (err: AWSError, data: CognitoSync.Types.GetBulkPublishDetailsResponse) => void): Request<CognitoSync.Types.GetBulkPublishDetailsResponse, AWSError>;
/**
* Get the status of the last BulkPublish operation for an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getBulkPublishDetails(callback?: (err: AWSError, data: CognitoSync.Types.GetBulkPublishDetailsResponse) => void): Request<CognitoSync.Types.GetBulkPublishDetailsResponse, AWSError>;
/**
* Gets the events and the corresponding Lambda functions associated with an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getCognitoEvents(params: CognitoSync.Types.GetCognitoEventsRequest, callback?: (err: AWSError, data: CognitoSync.Types.GetCognitoEventsResponse) => void): Request<CognitoSync.Types.GetCognitoEventsResponse, AWSError>;
/**
* Gets the events and the corresponding Lambda functions associated with an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getCognitoEvents(callback?: (err: AWSError, data: CognitoSync.Types.GetCognitoEventsResponse) => void): Request<CognitoSync.Types.GetCognitoEventsResponse, AWSError>;
/**
* Gets the configuration settings of an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getIdentityPoolConfiguration(params: CognitoSync.Types.GetIdentityPoolConfigurationRequest, callback?: (err: AWSError, data: CognitoSync.Types.GetIdentityPoolConfigurationResponse) => void): Request<CognitoSync.Types.GetIdentityPoolConfigurationResponse, AWSError>;
/**
* Gets the configuration settings of an identity pool.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
getIdentityPoolConfiguration(callback?: (err: AWSError, data: CognitoSync.Types.GetIdentityPoolConfigurationResponse) => void): Request<CognitoSync.Types.GetIdentityPoolConfigurationResponse, AWSError>;
/**
* Lists datasets for an identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. ListDatasets can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use the Cognito Identity credentials to make this API call.
*/
listDatasets(params: CognitoSync.Types.ListDatasetsRequest, callback?: (err: AWSError, data: CognitoSync.Types.ListDatasetsResponse) => void): Request<CognitoSync.Types.ListDatasetsResponse, AWSError>;
/**
* Lists datasets for an identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. ListDatasets can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use the Cognito Identity credentials to make this API call.
*/
listDatasets(callback?: (err: AWSError, data: CognitoSync.Types.ListDatasetsResponse) => void): Request<CognitoSync.Types.ListDatasetsResponse, AWSError>;
/**
* Gets a list of identity pools registered with Cognito. ListIdentityPoolUsage can only be called with developer credentials. You cannot make this API call with the temporary user credentials provided by Cognito Identity.
*/
listIdentityPoolUsage(params: CognitoSync.Types.ListIdentityPoolUsageRequest, callback?: (err: AWSError, data: CognitoSync.Types.ListIdentityPoolUsageResponse) => void): Request<CognitoSync.Types.ListIdentityPoolUsageResponse, AWSError>;
/**
* Gets a list of identity pools registered with Cognito. ListIdentityPoolUsage can only be called with developer credentials. You cannot make this API call with the temporary user credentials provided by Cognito Identity.
*/
listIdentityPoolUsage(callback?: (err: AWSError, data: CognitoSync.Types.ListIdentityPoolUsageResponse) => void): Request<CognitoSync.Types.ListIdentityPoolUsageResponse, AWSError>;
/**
* Gets paginated records, optionally changed after a particular sync count for a dataset and identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. ListRecords can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.
*/
listRecords(params: CognitoSync.Types.ListRecordsRequest, callback?: (err: AWSError, data: CognitoSync.Types.ListRecordsResponse) => void): Request<CognitoSync.Types.ListRecordsResponse, AWSError>;
/**
* Gets paginated records, optionally changed after a particular sync count for a dataset and identity. With Amazon Cognito Sync, each identity has access only to its own data. Thus, the credentials used to make this API call need to have access to the identity data. ListRecords can be called with temporary user credentials provided by Cognito Identity or with developer credentials. You should use Cognito Identity credentials to make this API call.
*/
listRecords(callback?: (err: AWSError, data: CognitoSync.Types.ListRecordsResponse) => void): Request<CognitoSync.Types.ListRecordsResponse, AWSError>;
/**
* Registers a device to receive push sync notifications.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
registerDevice(params: CognitoSync.Types.RegisterDeviceRequest, callback?: (err: AWSError, data: CognitoSync.Types.RegisterDeviceResponse) => void): Request<CognitoSync.Types.RegisterDeviceResponse, AWSError>;
/**
* Registers a device to receive push sync notifications.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
registerDevice(callback?: (err: AWSError, data: CognitoSync.Types.RegisterDeviceResponse) => void): Request<CognitoSync.Types.RegisterDeviceResponse, AWSError>;
/**
* Sets the AWS Lambda function for a given event type for an identity pool. This request only updates the key/value pair specified. Other key/values pairs are not updated. To remove a key value pair, pass a empty value for the particular key.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
setCognitoEvents(params: CognitoSync.Types.SetCognitoEventsRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Sets the AWS Lambda function for a given event type for an identity pool. This request only updates the key/value pair specified. Other key/values pairs are not updated. To remove a key value pair, pass a empty value for the particular key.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
setCognitoEvents(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Sets the necessary configuration for push sync.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
setIdentityPoolConfiguration(params: CognitoSync.Types.SetIdentityPoolConfigurationRequest, callback?: (err: AWSError, data: CognitoSync.Types.SetIdentityPoolConfigurationResponse) => void): Request<CognitoSync.Types.SetIdentityPoolConfigurationResponse, AWSError>;
/**
* Sets the necessary configuration for push sync.This API can only be called with developer credentials. You cannot call this API with the temporary user credentials provided by Cognito Identity.
*/
setIdentityPoolConfiguration(callback?: (err: AWSError, data: CognitoSync.Types.SetIdentityPoolConfigurationResponse) => void): Request<CognitoSync.Types.SetIdentityPoolConfigurationResponse, AWSError>;
/**
* Subscribes to receive notifications when a dataset is modified by another device.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
subscribeToDataset(params: CognitoSync.Types.SubscribeToDatasetRequest, callback?: (err: AWSError, data: CognitoSync.Types.SubscribeToDatasetResponse) => void): Request<CognitoSync.Types.SubscribeToDatasetResponse, AWSError>;
/**
* Subscribes to receive notifications when a dataset is modified by another device.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
subscribeToDataset(callback?: (err: AWSError, data: CognitoSync.Types.SubscribeToDatasetResponse) => void): Request<CognitoSync.Types.SubscribeToDatasetResponse, AWSError>;
/**
* Unsubscribes from receiving notifications when a dataset is modified by another device.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
unsubscribeFromDataset(params: CognitoSync.Types.UnsubscribeFromDatasetRequest, callback?: (err: AWSError, data: CognitoSync.Types.UnsubscribeFromDatasetResponse) => void): Request<CognitoSync.Types.UnsubscribeFromDatasetResponse, AWSError>;
/**
* Unsubscribes from receiving notifications when a dataset is modified by another device.This API can only be called with temporary credentials provided by Cognito Identity. You cannot call this API with developer credentials.
*/
unsubscribeFromDataset(callback?: (err: AWSError, data: CognitoSync.Types.UnsubscribeFromDatasetResponse) => void): Request<CognitoSync.Types.UnsubscribeFromDatasetResponse, AWSError>;
/**
* Posts updates to records and adds and deletes records for a dataset and user. The sync count in the record patch is your last known sync count for that record. The server will reject an UpdateRecords request with a ResourceConflictException if you try to patch a record with a new value but a stale sync count.For example, if the sync count on the server is 5 for a key called highScore and you try and submit a new highScore with sync count of 4, the request will be rejected. To obtain the current sync count for a record, call ListRecords. On a successful update of the record, the response returns the new sync count for that record. You should present that sync count the next time you try to update that same record. When the record does not exist, specify the sync count as 0. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
updateRecords(params: CognitoSync.Types.UpdateRecordsRequest, callback?: (err: AWSError, data: CognitoSync.Types.UpdateRecordsResponse) => void): Request<CognitoSync.Types.UpdateRecordsResponse, AWSError>;
/**
* Posts updates to records and adds and deletes records for a dataset and user. The sync count in the record patch is your last known sync count for that record. The server will reject an UpdateRecords request with a ResourceConflictException if you try to patch a record with a new value but a stale sync count.For example, if the sync count on the server is 5 for a key called highScore and you try and submit a new highScore with sync count of 4, the request will be rejected. To obtain the current sync count for a record, call ListRecords. On a successful update of the record, the response returns the new sync count for that record. You should present that sync count the next time you try to update that same record. When the record does not exist, specify the sync count as 0. This API can be called with temporary user credentials provided by Cognito Identity or with developer credentials.
*/
updateRecords(callback?: (err: AWSError, data: CognitoSync.Types.UpdateRecordsResponse) => void): Request<CognitoSync.Types.UpdateRecordsResponse, AWSError>;
}
declare namespace CognitoSync {
export type ApplicationArn = string;
export type ApplicationArnList = ApplicationArn[];
export type AssumeRoleArn = string;
export type Boolean = boolean;
export interface BulkPublishRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
}
export interface BulkPublishResponse {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId?: IdentityPoolId;
}
export type BulkPublishStatus = "NOT_STARTED"|"IN_PROGRESS"|"FAILED"|"SUCCEEDED"|string;
export type ClientContext = string;
export type CognitoEventType = string;
export interface CognitoStreams {
/**
* The name of the Cognito stream to receive updates. This stream must be in the developers account and in the same region as the identity pool.
*/
StreamName?: StreamName;
/**
* The ARN of the role Amazon Cognito can assume in order to publish to the stream. This role must grant access to Amazon Cognito (cognito-sync) to invoke PutRecord on your Cognito stream.
*/
RoleArn?: AssumeRoleArn;
/**
* Status of the Cognito streams. Valid values are: ENABLED - Streaming of updates to identity pool is enabled. DISABLED - Streaming of updates to identity pool is disabled. Bulk publish will also fail if StreamingStatus is DISABLED.
*/
StreamingStatus?: StreamingStatus;
}
export interface Dataset {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId?: IdentityId;
/**
* A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName?: DatasetName;
/**
* Date on which the dataset was created.
*/
CreationDate?: _Date;
/**
* Date when the dataset was last modified.
*/
LastModifiedDate?: _Date;
/**
* The device that made the last change to this dataset.
*/
LastModifiedBy?: String;
/**
* Total size in bytes of the records in this dataset.
*/
DataStorage?: Long;
/**
* Number of records in this dataset.
*/
NumRecords?: Long;
}
export type DatasetList = Dataset[];
export type DatasetName = string;
export type _Date = Date;
export interface DeleteDatasetRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
/**
* A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName: DatasetName;
}
export interface DeleteDatasetResponse {
/**
* A collection of data for an identity pool. An identity pool can have multiple datasets. A dataset is per identity and can be general or associated with a particular entity in an application (like a saved game). Datasets are automatically created if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value pairs.
*/
Dataset?: Dataset;
}
export interface DescribeDatasetRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
/**
* A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName: DatasetName;
}
export interface DescribeDatasetResponse {
/**
* Meta data for a collection of data for an identity. An identity can have multiple datasets. A dataset can be general or associated with a particular entity in an application (like a saved game). Datasets are automatically created if they don't exist. Data is synced by dataset, and a dataset can hold up to 1MB of key-value pairs.
*/
Dataset?: Dataset;
}
export interface DescribeIdentityPoolUsageRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
}
export interface DescribeIdentityPoolUsageResponse {
/**
* Information about the usage of the identity pool.
*/
IdentityPoolUsage?: IdentityPoolUsage;
}
export interface DescribeIdentityUsageRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
}
export interface DescribeIdentityUsageResponse {
/**
* Usage information for the identity.
*/
IdentityUsage?: IdentityUsage;
}
export type DeviceId = string;
export type Events = {[key: string]: LambdaFunctionArn};
export interface GetBulkPublishDetailsRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
}
export interface GetBulkPublishDetailsResponse {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId?: IdentityPoolId;
/**
* The date/time at which the last bulk publish was initiated.
*/
BulkPublishStartTime?: _Date;
/**
* If BulkPublishStatus is SUCCEEDED, the time the last bulk publish operation completed.
*/
BulkPublishCompleteTime?: _Date;
/**
* Status of the last bulk publish operation, valid values are: NOT_STARTED - No bulk publish has been requested for this identity pool IN_PROGRESS - Data is being published to the configured stream SUCCEEDED - All data for the identity pool has been published to the configured stream FAILED - Some portion of the data has failed to publish, check FailureMessage for the cause.
*/
BulkPublishStatus?: BulkPublishStatus;
/**
* If BulkPublishStatus is FAILED this field will contain the error message that caused the bulk publish to fail.
*/
FailureMessage?: String;
}
export interface GetCognitoEventsRequest {
/**
* The Cognito Identity Pool ID for the request
*/
IdentityPoolId: IdentityPoolId;
}
export interface GetCognitoEventsResponse {
/**
* The Cognito Events returned from the GetCognitoEvents request
*/
Events?: Events;
}
export interface GetIdentityPoolConfigurationRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool for which to return a configuration.
*/
IdentityPoolId: IdentityPoolId;
}
export interface GetIdentityPoolConfigurationResponse {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito.
*/
IdentityPoolId?: IdentityPoolId;
/**
* Options to apply to this identity pool for push synchronization.
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export type IdentityId = string;
export type IdentityPoolId = string;
export interface IdentityPoolUsage {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId?: IdentityPoolId;
/**
* Number of sync sessions for the identity pool.
*/
SyncSessionsCount?: Long;
/**
* Data storage information for the identity pool.
*/
DataStorage?: Long;
/**
* Date on which the identity pool was last modified.
*/
LastModifiedDate?: _Date;
}
export type IdentityPoolUsageList = IdentityPoolUsage[];
export interface IdentityUsage {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId?: IdentityId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId?: IdentityPoolId;
/**
* Date on which the identity was last modified.
*/
LastModifiedDate?: _Date;
/**
* Number of datasets for the identity.
*/
DatasetCount?: Integer;
/**
* Total data storage for this identity.
*/
DataStorage?: Long;
}
export type Integer = number;
export type IntegerString = number;
export type LambdaFunctionArn = string;
export interface ListDatasetsRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
/**
* The maximum number of results to be returned.
*/
MaxResults?: IntegerString;
}
export interface ListDatasetsResponse {
/**
* A set of datasets.
*/
Datasets?: DatasetList;
/**
* Number of datasets returned.
*/
Count?: Integer;
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
}
export interface ListIdentityPoolUsageRequest {
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
/**
* The maximum number of results to be returned.
*/
MaxResults?: IntegerString;
}
export interface ListIdentityPoolUsageResponse {
/**
* Usage information for the identity pools.
*/
IdentityPoolUsages?: IdentityPoolUsageList;
/**
* The maximum number of results to be returned.
*/
MaxResults?: Integer;
/**
* Total number of identities for the identity pool.
*/
Count?: Integer;
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
}
export interface ListRecordsRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
/**
* A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName: DatasetName;
/**
* The last server sync count for this record.
*/
LastSyncCount?: Long;
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
/**
* The maximum number of results to be returned.
*/
MaxResults?: IntegerString;
/**
* A token containing a session ID, identity ID, and expiration.
*/
SyncSessionToken?: SyncSessionToken;
}
export interface ListRecordsResponse {
/**
* A list of all records.
*/
Records?: RecordList;
/**
* A pagination token for obtaining the next page of results.
*/
NextToken?: String;
/**
* Total number of records.
*/
Count?: Integer;
/**
* Server sync count for this dataset.
*/
DatasetSyncCount?: Long;
/**
* The user/device that made the last change to this record.
*/
LastModifiedBy?: String;
/**
* Names of merged datasets.
*/
MergedDatasetNames?: MergedDatasetNameList;
/**
* Indicates whether the dataset exists.
*/
DatasetExists?: Boolean;
/**
* A boolean value specifying whether to delete the dataset locally.
*/
DatasetDeletedAfterRequestedSyncCount?: Boolean;
/**
* A token containing a session ID, identity ID, and expiration.
*/
SyncSessionToken?: String;
}
export type Long = number;
export type MergedDatasetNameList = String[];
export type Operation = "replace"|"remove"|string;
export type Platform = "APNS"|"APNS_SANDBOX"|"GCM"|"ADM"|string;
export interface PushSync {
/**
* List of SNS platform application ARNs that could be used by clients.
*/
ApplicationArns?: ApplicationArnList;
/**
* A role configured to allow Cognito to call SNS on behalf of the developer.
*/
RoleArn?: AssumeRoleArn;
}
export type PushToken = string;
export interface Record {
/**
* The key for the record.
*/
Key?: RecordKey;
/**
* The value for the record.
*/
Value?: RecordValue;
/**
* The server sync count for this record.
*/
SyncCount?: Long;
/**
* The date on which the record was last modified.
*/
LastModifiedDate?: _Date;
/**
* The user/device that made the last change to this record.
*/
LastModifiedBy?: String;
/**
* The last modified date of the client device.
*/
DeviceLastModifiedDate?: _Date;
}
export type RecordKey = string;
export type RecordList = Record[];
export interface RecordPatch {
/**
* An operation, either replace or remove.
*/
Op: Operation;
/**
* The key associated with the record patch.
*/
Key: RecordKey;
/**
* The value associated with the record patch.
*/
Value?: RecordValue;
/**
* Last known server sync count for this record. Set to 0 if unknown.
*/
SyncCount: Long;
/**
* The last modified date of the client device.
*/
DeviceLastModifiedDate?: _Date;
}
export type RecordPatchList = RecordPatch[];
export type RecordValue = string;
export interface RegisterDeviceRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. Here, the ID of the pool that the identity belongs to.
*/
IdentityPoolId: IdentityPoolId;
/**
* The unique ID for this identity.
*/
IdentityId: IdentityId;
/**
* The SNS platform type (e.g. GCM, SDM, APNS, APNS_SANDBOX).
*/
Platform: Platform;
/**
* The push token.
*/
Token: PushToken;
}
export interface RegisterDeviceResponse {
/**
* The unique ID generated for this device by Cognito.
*/
DeviceId?: DeviceId;
}
export interface SetCognitoEventsRequest {
/**
* The Cognito Identity Pool to use when configuring Cognito Events
*/
IdentityPoolId: IdentityPoolId;
/**
* The events to configure
*/
Events: Events;
}
export interface SetIdentityPoolConfigurationRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. This is the ID of the pool to modify.
*/
IdentityPoolId: IdentityPoolId;
/**
* Options to apply to this identity pool for push synchronization.
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export interface SetIdentityPoolConfigurationResponse {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito.
*/
IdentityPoolId?: IdentityPoolId;
/**
* Options to apply to this identity pool for push synchronization.
*/
PushSync?: PushSync;
/**
* Options to apply to this identity pool for Amazon Cognito streams.
*/
CognitoStreams?: CognitoStreams;
}
export type StreamName = string;
export type StreamingStatus = "ENABLED"|"DISABLED"|string;
export type String = string;
export interface SubscribeToDatasetRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which the identity belongs.
*/
IdentityPoolId: IdentityPoolId;
/**
* Unique ID for this identity.
*/
IdentityId: IdentityId;
/**
* The name of the dataset to subcribe to.
*/
DatasetName: DatasetName;
/**
* The unique ID generated for this device by Cognito.
*/
DeviceId: DeviceId;
}
export interface SubscribeToDatasetResponse {
}
export type SyncSessionToken = string;
export interface UnsubscribeFromDatasetRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. The ID of the pool to which this identity belongs.
*/
IdentityPoolId: IdentityPoolId;
/**
* Unique ID for this identity.
*/
IdentityId: IdentityId;
/**
* The name of the dataset from which to unsubcribe.
*/
DatasetName: DatasetName;
/**
* The unique ID generated for this device by Cognito.
*/
DeviceId: DeviceId;
}
export interface UnsubscribeFromDatasetResponse {
}
export interface UpdateRecordsRequest {
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityPoolId: IdentityPoolId;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE) created by Amazon Cognito. GUID generation is unique within a region.
*/
IdentityId: IdentityId;
/**
* A string of up to 128 characters. Allowed characters are a-z, A-Z, 0-9, '_' (underscore), '-' (dash), and '.' (dot).
*/
DatasetName: DatasetName;
/**
* The unique ID generated for this device by Cognito.
*/
DeviceId?: DeviceId;
/**
* A list of patch operations.
*/
RecordPatches?: RecordPatchList;
/**
* The SyncSessionToken returned by a previous call to ListRecords for this dataset and identity.
*/
SyncSessionToken: SyncSessionToken;
/**
* Intended to supply a device ID that will populate the lastModifiedBy field referenced in other methods. The ClientContext field is not yet implemented.
*/
ClientContext?: ClientContext;
}
export interface UpdateRecordsResponse {
/**
* A list of records that have been updated.
*/
Records?: RecordList;
}
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2014-06-30"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the CognitoSync client.
*/
export import Types = CognitoSync;
}
export = CognitoSync; | the_stack |
import {
Section,
Container,
Heading,
Link,
Avatar,
Flex,
Button,
Paragraph,
Separator,
Box,
Grid,
Text,
styled,
AspectRatio,
} from '@modulz/design-system';
import React from 'react';
import { MarketingCaption } from './MarketingCaption';
import { CheckIcon, ChevronDownIcon } from '@radix-ui/react-icons';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
const InlineDropdownTrigger = styled(DropdownMenuPrimitive.Trigger, {
all: 'unset',
alignItems: 'center',
boxSizing: 'border-box',
display: 'inline-flex',
WebkitTapHighlightColor: 'transparent',
px: 7,
pt: 0,
pb: 2,
mr: 2,
bc: '$slate3',
border: '1px solid $slateA5',
borderRadius: '$3',
outline: 0,
'@hover': {
'&:hover': {
borderColor: '$slateA8',
},
'&:focus': {
borderColor: '$slateA8',
boxShadow: '0 0 0 1px $colors$slateA8',
},
},
});
const ThickCaretDown = (props: React.ComponentProps<'svg'>) => {
return (
<svg
width="15"
height="15"
viewBox="0 0 15 15"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path
d="M3.5 6.5L7.5 10.25L11.5 6.5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
};
const InlineDropdownArrow = styled(DropdownMenuPrimitive.Arrow, {
fill: '$panel',
});
const InlineDropdownContent = styled(DropdownMenuPrimitive.Content, {
bc: '$panel',
boxShadow: '0px 5px 30px -5px $colors$shadowDark',
p: '$1',
br: '$3',
});
const InlineDropdownRadioItem = styled(DropdownMenuPrimitive.RadioItem, {
display: 'flex',
ai: 'center',
fontFamily: '$untitled',
fontSize: '$5',
letterSpacing: '-0.01em',
height: '$6',
px: '$2',
br: '$2',
cursor: 'default',
'@hover': {
'&:hover': {
bc: '$slateA3',
outline: 0,
},
},
'&:focus': {
bc: '$slateA3',
outline: 0,
},
'&[data-state="checked"]': {
display: 'none',
},
});
type Components =
| 'dropdown'
| 'dialog'
| 'popover'
| 'slider'
| 'scroll area'
| 'hover card'
| 'tooltip';
export const ComponentHighlightsSection = () => {
const [component, setComponent] = React.useState<Components>('dropdown');
return (
<Section
css={{
position: 'relative',
backgroundImage: 'linear-gradient(to bottom, $slate2, $loContrast)',
overflow: 'hidden',
}}
>
<Container size="3">
<Flex
direction="column"
align="center"
css={{
textAlign: 'center',
position: 'relative',
zIndex: 1,
mb: '$6',
'@bp3': { mb: 100 },
}}
>
<MarketingCaption css={{ mb: '$1' }}>Case in point</MarketingCaption>
<Heading as="h2" size="3" css={{ mb: '$3' }}>
So, you think you can <span style={{ whiteSpace: 'nowrap' }}>build a dropdown?</span>
</Heading>
{/* <DropdownMenuPrimitive.Root>
<Heading as="h2" size="3" css={{ mb: '$3' }}>
So, you think you can{' '}
<span style={{ whiteSpace: 'nowrap' }}>
build a{' '}
<InlineDropdownTrigger>
{component}
<ThickCaretDown style={{ marginTop: 2, marginLeft: 5, marginRight: -1 }} />
</InlineDropdownTrigger>
?
</span>
</Heading>
<InlineDropdownContent sideOffset={5}>
<InlineDropdownArrow />
<DropdownMenuPrimitive.RadioGroup
value={component}
onValueChange={(newValue) => setComponent(newValue as Components)}
>
<InlineDropdownRadioItem value="dropdown">dropdown</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="dialog">dialog</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="popover">popover</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="slider">slider</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="scroll area">scroll area</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="hover card">hover card</InlineDropdownRadioItem>
<InlineDropdownRadioItem value="tooltip">tooltip</InlineDropdownRadioItem>
</DropdownMenuPrimitive.RadioGroup>
</InlineDropdownContent>
</DropdownMenuPrimitive.Root> */}
<Box css={{ maxWidth: 480 }}>
{component === 'dropdown' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'dialog' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'popover' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'slider' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'scroll area' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'hover card' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
{component === 'tooltip' && (
<Paragraph>
We agonise over API design, performance, and accessibility so you don't need to.
</Paragraph>
)}
</Box>
</Flex>
<Box css={{ position: 'relative' }}>
{/* Use guides to position things sanely */}
{/* <Guides7 /> */}
{/* <Guides8 /> */}
<Box css={{ position: 'relative', mb: '$4' }}>
<Box
css={{
position: 'absolute',
height: '100%',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
}}
>
<Circle
size={180}
angle={-45}
color1="var(--colors-slateA4)"
color2="var(--colors-indigoA6)"
/>
<Circle
size={300}
angle={20}
color1="var(--colors-slateA3)"
color2="var(--colors-indigoA5)"
/>
<Circle
size={420}
angle={35}
color1="var(--colors-slateA2)"
color2="var(--colors-indigoA4)"
/>
<Circle
size={540}
angle={-50}
color1="var(--colors-slateA2)"
color2="var(--colors-indigoA3)"
/>
{[660, 780, 900, 1020, 1140, 1260, 1380, 1500, 1620, 1740, 1860, 1980, 2100].map(
(size, i) => (
<Circle
key={i}
size={size + i * i * 5}
angle={-45 + i * 15}
color1="var(--colors-slateA2)"
color2="var(--colors-indigoA3)"
opacity={1 - i * 0.1}
/>
)
)}
</Box>
<Flex
align="center"
justify="center"
css={{ position: 'relative', '@bp3': { height: 850 } }}
>
<img
src="/marketing/dropdown-menu.svg"
alt="A dropdown menu example with a checked item and a submenu"
/>
</Flex>
</Box>
<Box
css={{
mx: '-$5',
pl: '$5',
pt: '$1',
position: 'relative',
overflowX: 'scroll',
overflowY: 'hidden',
WebkitOverflowScrolling: 'touch',
MsOverflowStyle: 'none',
scrollbarWidth: 'none',
'&::-webkit-scrollbar': {
display: 'none',
},
'@bp1': {
all: 'unset',
},
}}
>
<Grid
gap={{ '@initial': 5, '@bp2': 7 }}
flow={{ '@initial': 'column', '@bp1': 'row' }}
justify={{ '@initial': 'start', '@bp1': 'center' }}
css={{
gridAutoColumns: 'calc(100vw - 100px)',
'@bp1': { gridTemplateColumns: '1fr 1fr' },
'@bp2': { gridTemplateColumns: '315px 315px', ml: '$5' },
'@bp3': { mb: '$8', '& > *': { position: 'absolute', width: 315 } },
}}
>
{component === 'dropdown' && (
<>
<Box css={{ '@bp3': { top: '-1%', left: '27%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Full keyboard navigation
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Navigate the menu using arrow keys, Escape, and Enter hotkeys, or even via
typeahead.
</Text>
</Box>
<Box css={{ '@bp3': { top: '14%', left: '60%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Modal and non-modal modes
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Configure whether the dropdown menu allows or blocks outside interactions.
</Text>
</Box>
<Box css={{ '@bp3': { top: '40%', left: '74%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Supports submenus
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Nest another level of fully functional submenus inside the dropdown menu.
</Text>
</Box>
<Box css={{ '@bp3': { top: '67%', left: '69%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Supports assistive technology
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Implements correct semantics and behaviors, so it's accessible to people using
assistive technology.
</Text>
</Box>
<Box css={{ '@bp3': { top: '94%', left: '39%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Collision and origin-aware animations
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Create open and close animations that take the dropdown menu’s actual position
into account.
</Text>
</Box>
<Box css={{ '@bp3': { top: '76%', left: '8%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Control alignment and collisions
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Position the menu anywhere relative to the trigger, taking collisions with the
screen into account.
</Text>
</Box>
<Box css={{ '@bp3': { top: '49%', left: '-1%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Fully managed focus
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Granularly control focus behavior when user closes the dropdown menu or
focuses an outside element.
</Text>
</Box>
<Box css={{ '@bp3': { top: '19%', left: '4%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Supports checkable items
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Items can be used to perform actions, as well as act as checkbox or
radiobutton controls.
</Text>
</Box>
</>
)}
{component === 'dialog' && (
<>
<Box css={{ '@bp3': { top: '-1%', left: '29%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Full keyboard navigation
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
The dialog traps focus so you can navigate it with Tab key. Close the dialog
with Escape key.
</Text>
</Box>
<Box css={{ '@bp3': { top: '14%', left: '62%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Modal and non-modal modes
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Configure whether the dialog allows or blocks outside interactions.
</Text>
</Box>
<Box css={{ '@bp3': { top: '40%', left: '76%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
No janky scroll bugs
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Content behind the dialog stays put while document scroll is disabled.
</Text>
</Box>
<Box css={{ '@bp3': { top: '67%', left: '69%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Supports assistive technology
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Implements correct semantics and behaviors, so it's accessible to people using
assistive technology.
</Text>
</Box>
<Box css={{ '@bp3': { top: '94%', left: '41%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Easy to animate
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Provides control over mounting behavior for managing animations with CSS or
animation libraries.
</Text>
</Box>
<Box css={{ '@bp3': { top: '76%', left: '10%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Nesting just works
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
No gotchas if you need to nest another dialog or a component that manages
focus behavior.
</Text>
</Box>
<Box css={{ '@bp3': { top: '49%', left: '1%' } }}>
<Flex gap="2" align="start" css={{ mb: '$1' }}>
<FancyCheckMark />
<Text
as="h3"
size="4"
css={{ lineHeight: 1.35, fontWeight: 500, letterSpacing: '-0.01em' }}
>
Fully managed focus
</Text>
</Flex>
<Text size="3" variant="gray" css={{ lineHeight: 1.5, ml: '$6' }}>
Granularly control focus behavior when user opens or closes the dialog.
</Text>
</Box>
</>
)}
</Grid>
</Box>
</Box>
</Container>
</Section>
);
};
const FancyCheckMark = styled(CheckIcon, {
color: '$teal11',
backgroundColor: '$cyan4',
padding: '$1',
mt: -2,
width: '$5',
height: '$5',
borderRadius: '$round',
flex: 'none',
});
const Circle = ({
size,
color1,
color2,
angle = 90,
opacity = 1,
}: {
size: number;
angle?: number;
color1: string;
color2: string;
opacity?: number;
}) => {
return (
<Box
css={{
position: 'absolute',
left: '50%',
top: '50%',
width: size,
height: size,
transform: `translate(-50%, -50%) rotate(${angle}deg)`,
opacity: opacity,
}}
>
<svg
viewBox="0 0 100 100"
fill="none"
xmlns="http://www.w3.org/2000/svg"
style={{ width: '100%', height: '100%' }}
>
<circle
cx="50"
cy="50"
r="49"
stroke={`url(#circle-${size})`}
strokeWidth="1"
vectorEffect="non-scaling-stroke"
/>
<defs>
<linearGradient
id={`circle-${size}`}
gradientUnits="userSpaceOnUse"
x1="50"
y1="0"
x2="50"
y2="100"
>
<stop style={{ stopColor: color1 }} />
<stop style={{ stopColor: color2 }} offset="1" />
</linearGradient>
</defs>
</svg>
</Box>
);
};
const Guides8 = () => (
<svg
width="1100"
height="1100"
viewBox="0 0 1100 1100"
fill="none"
xmlns="http://www.w3.org/2000/svg"
style={{
position: 'absolute',
pointerEvents: 'none',
top: '50%',
left: '50%',
opacity: 0.5,
transform: 'translate(-50%, -50%) rotate(15deg)',
}}
>
<line x1="25" y1="549.5" x2="1075" y2="549.5" stroke="black" />
<line x1="549.5" y1="1075" x2="549.5" y2="25" stroke="black" />
<line x1="921.584" y1="179.122" x2="179.122" y2="921.585" stroke="black" />
<line x1="920.877" y1="921.585" x2="178.415" y2="179.123" stroke="black" />
<g opacity="0.1">
<line x1="42.7612" y1="685.397" x2="1056.98" y2="413.637" stroke="black" />
<line x1="685.398" y1="1057.24" x2="413.638" y2="43.0184" stroke="black" />
<line x1="812.933" y1="95.5868" x2="287.933" y2="1004.91" stroke="black" />
<line x1="1004.41" y1="812.933" x2="95.0873" y2="287.933" stroke="black" />
</g>
<g opacity="0.1">
<line x1="43.0181" y1="413.637" x2="1057.24" y2="685.397" stroke="black" />
<line x1="413.638" y1="1056.98" x2="685.398" y2="42.7596" stroke="black" />
<line x1="1004.91" y1="287.933" x2="95.5875" y2="812.933" stroke="black" />
<line x1="812.067" y1="1004.91" x2="287.067" y2="95.5866" stroke="black" />
</g>
<circle cx="550" cy="549" r="424.5" stroke="black" />
<circle cx="550" cy="549" r="424.5" stroke="black" />
<circle cx="550" cy="549" r="474.5" stroke="black" />
<circle cx="550" cy="549" r="524.5" stroke="black" />
</svg>
);
const Guides7 = () => (
<svg
width="1486"
height="1486"
viewBox="0 0 1486 1486"
fill="none"
xmlns="http://www.w3.org/2000/svg"
style={{
position: 'absolute',
pointerEvents: 'none',
top: '50%',
left: '50%',
opacity: 0.5,
transform: 'translate(-50%, -50%) rotate(15deg)',
}}
>
<line x1="480.068" y1="288.587" x2="742.568" y2="743.25" stroke="black" />
<line x1="934.403" y1="254.974" x2="742.884" y2="742.955" stroke="black" />
<line x1="1243.96" y1="589.232" x2="743.213" y2="743.69" stroke="black" />
<line x1="1175.63" y1="1039.66" x2="741.852" y2="743.913" stroke="black" />
<line x1="780.869" y1="1267.07" x2="742.502" y2="743.036" stroke="black" />
<line x1="356.941" y1="1100.22" x2="741.793" y2="743.133" stroke="black" />
<line x1="223.073" y1="664.758" x2="742.209" y2="743.006" stroke="black" />
<g opacity="0.1">
<line x1="371.416" y1="372.123" x2="742.647" y2="743.354" stroke="black" />
<line x1="801.571" y1="222.065" x2="742.877" y2="742.987" stroke="black" />
<line x1="1187.09" y1="464.814" x2="743.385" y2="743.612" stroke="black" />
<line x1="1237.66" y1="917.575" x2="742.127" y2="744.18" stroke="black" />
<line x1="915.217" y1="1239.41" x2="742.528" y2="743.165" stroke="black" />
<line x1="462.553" y1="1187.97" x2="741.87" y2="743.442" stroke="black" />
<line x1="220.538" y1="801.992" x2="742.237" y2="743.211" stroke="black" />
</g>
<g opacity="0.1">
<line x1="606.637" y1="236.019" x2="742.517" y2="743.13" stroke="black" />
<line x1="1054.19" y1="321.143" x2="742.9" y2="742.928" stroke="black" />
<line x1="1266.69" y1="724.13" x2="743.028" y2="743.723" stroke="black" />
<line x1="1084.11" y1="1141.52" x2="741.655" y2="743.586" stroke="black" />
<line x1="643.939" y1="1259.01" x2="742.508" y2="742.907" stroke="black" />
<line x1="277.639" y1="988.134" x2="741.8" y2="742.817" stroke="black" />
<line x1="261.04" y1="532.858" x2="742.235" y2="742.801" stroke="black" />
</g>
<circle cx="743" cy="743" r="424.5" transform="rotate(60 743 743)" stroke="black" />
<circle cx="743" cy="743" r="424.5" transform="rotate(60 743 743)" stroke="black" />
<circle cx="742.999" cy="743" r="474.5" transform="rotate(60 742.999 743)" stroke="black" />
<circle cx="743" cy="743" r="524.5" transform="rotate(45 743 743)" stroke="black" />
</svg>
); | the_stack |
import { AppiumDriver, SearchOptions } from "nativescript-dev-appium";
import { assert } from "chai";
const home = "Home Component"
const first = "First"
const modal = "Modal";
const modalFirst = "Modal First";
const dialogConfirm = "Dialog";
const modalSecond = "Modal Second";
const modalNested = "Modal Nested";
const modalFrame = "Show Modal Page With Frame";
const modalNoFrame = "Show Modal Without Frame";
const modalLayout = "Show Modal Layout";
const modalTabView = "Show Modal TabView";
const navToSecondPage = "Navigate To Second Page";
const showDialog = "Show Dialog";
const resetFrameRootView = "Reset Frame Root View";
const resetFrameRootViewModal = "Reset Frame Root View Modal";
const resetNamedFrameRootView = "Reset Named Frame Root View";
const resetNamedFrameRootViewModal = "Reset Named Frame Root View Modal";
const resetTabRootView = "Reset Tab Root View";
const resetTabRootViewModal = "Reset Tab Root View Modal";
const resetLayoutRootView = "Reset Layout Root View";
const resetLayoutRootViewModal = "Reset Layout Root View Modal";
const showNestedModalFrame = "Show Nested Modal Page With Frame";
const showNestedModalPage = "Show Nested Modal Page";
const confirmDialog = "Yes";
const confirmDialogMessage = "Message";
const closeModalNested = "Close Modal Nested";
const closeModal = "Close Modal";
const goBack = "Go Back(activatedRoute)";
export const sharedModalView = "SHARED MODAL VIEW";
export const homeComponent = "Home Component";
export class Screen {
private _driver: AppiumDriver
constructor(driver: AppiumDriver) {
this._driver = driver;
}
loadedHome = async () => {
const lblHome = await this._driver.waitForElement(home);
assert.isTrue(await lblHome.isDisplayed());
console.log(home + " loaded!");
}
resetFrameRootView = async () => {
console.log("Setting frame root ...");
const btnResetFrameRootView = await this._driver.findElementByAutomationText(resetFrameRootView);
await btnResetFrameRootView.tap();
}
resetNamedFrameRootView = async () => {
console.log("Setting named frame root ...");
const btnResetFrameRootView = await this._driver.findElementByAutomationText(resetNamedFrameRootView);
await btnResetFrameRootView.tap();
}
resetLayoutRootView = async () => {
console.log("Setting layout root ...");
const btnResetLayoutRootView = await this._driver.waitForElement(resetLayoutRootView);
await btnResetLayoutRootView.click();
}
resetTabRootView = async () => {
const btnResetTabRootView = await this._driver.findElementByAutomationText(resetTabRootView);
await btnResetTabRootView.tap();
}
resetTabRootViewModal = async () => {
const btnResetTabRootViewModal = await this._driver.findElementByAutomationText(resetTabRootViewModal);
await btnResetTabRootViewModal.click();
}
resetFrameRootViewModal = async () => {
const btnResetTabRootViewModal = await this._driver.findElementByAutomationText(resetFrameRootViewModal);
await btnResetTabRootViewModal.click();
}
resetNamedFrameRootViewModal = async () => {
const btnResetTabRootViewModal = await this._driver.findElementByAutomationText(resetNamedFrameRootViewModal);
await btnResetTabRootViewModal.click();
}
resetLayoutRootViewModal = async () => {
const btnResetTabRootViewModal = await this._driver.findElementByAutomationText(resetLayoutRootViewModal);
await btnResetTabRootViewModal.click();
}
loadedTabRootView = async () => {
const tabFirst = await this._driver.findElementByAutomationText(first);
assert.isTrue(await tabFirst.isDisplayed());
console.log("Tab root view loaded!");
}
setFrameRootView = async () => {
// should load frame root, no need to verify it is loaded
await this.loadedHome();
await this.resetFrameRootView();
}
setNamedFrameRootView = async () => {
// should load named frame root, no need to verify it is loaded
await this.loadedHome();
await this.resetNamedFrameRootView();
}
setTabRootView = async () => {
// should load tab root
await this.loadedHome();
await this.resetTabRootView();
await this.loadedTabRootView();
}
setLayoutRootView = async () => {
// should load layout root, no need to verify it is loaded
await this.loadedHome();
await this.resetLayoutRootView();
}
setTabRootViewModal = async () => {
await this.loadedHome();
await this.resetTabRootViewModal();
}
setFrameRootViewModal = async () => {
await this.loadedHome();
await this.resetFrameRootViewModal();
}
setNamedFrameRootViewModal = async () => {
await this.loadedHome();
await this.resetNamedFrameRootViewModal();
}
setLayoutRootViewModal = async () => {
await this.loadedHome();
await this.resetLayoutRootViewModal();
}
showModalFrame = async () => {
const btnModalFrame = await this._driver.findElementByAutomationText(modalFrame);
await btnModalFrame.tap();
}
loadedModalFrame = async () => {
const lblModal = await this._driver.waitForElement(modal, 5000);
assert.isTrue(await lblModal.isDisplayed(), `${modal} is not displayed!`);
console.log(modal + " loaded!");
}
showModalNoFrame = async () => {
const btnModalPage = await this._driver.findElementByAutomationText(modalNoFrame);
await btnModalPage.tap();
}
private showSharedModal = async () => {
const btnTap = await this._driver.waitForElement("Show Shared Modal");
await btnTap.click();
}
private showSharedModalPresentationStyle = async () => {
const btnTap = await this._driver.findElementByText("popover", SearchOptions.contains);
await btnTap.click();
}
loadedModalPage = async () => {
const btnShowNestedModalPage = await this._driver.findElementByAutomationText(showNestedModalPage);
assert.isTrue(await btnShowNestedModalPage.isDisplayed(), `${showNestedModalPage} is not displayed`);
console.log("Modal Page loaded!");
}
showModalLayout = async () => {
const btnModalLayout = await this._driver.findElementByAutomationText(modalLayout);
await btnModalLayout.tap();
}
loadedModalLayout = async () => {
await this.loadedModalFrame();
}
showModalTabView = async () => {
const btnModalTabView = await this._driver.findElementByAutomationText(modalTabView);
await btnModalTabView.tap();
}
loadedModalTabView = async () => {
const itemModalFirst = await this._driver.findElementByAutomationText(modalFirst);
assert.isTrue(await itemModalFirst.isDisplayed());
console.log("Modal TabView loaded!");
}
navigateToSecondPage = async () => {
const btnNavToSecondPage = await this._driver.findElementByAutomationText(navToSecondPage);
await btnNavToSecondPage.tap();
}
showDialogConfirm = async () => {
const btnShowDialogConfirm = await this._driver.findElementByAutomationText(showDialog);
await btnShowDialogConfirm.tap();
}
navigateToFirstItem = async () => {
const itemModalFirst = await this._driver.findElementByAutomationText(modalFirst);
await itemModalFirst.tap();
}
navigateToSecondItem = async () => {
const itemModalSecond = await this._driver.findElementByAutomationText(modalSecond);
await itemModalSecond.tap();
}
loadedModalNoFrame = async () => {
await this._driver.wait(2000);
const btnShowDialogConfirm = await this._driver.waitForElement(showDialog);
const btnCloseModal = await this._driver.waitForElement(closeModal);
assert.isTrue(await btnShowDialogConfirm.isDisplayed());
assert.isTrue(await btnCloseModal.isDisplayed());
console.log("Modal Without Frame shown!");
}
loadedConfirmDialog = async () => {
const lblDialogMessage = await this._driver.findElementByAutomationText(confirmDialogMessage);
assert.isTrue(await lblDialogMessage.isDisplayed());
console.log(dialogConfirm + " shown!");
}
loadedSecondPage = async () => {
const lblModalSecond = await this._driver.waitForElement(modalSecond, 5000);
assert.isTrue(await lblModalSecond.isDisplayed());
console.log(modalSecond + " loaded!");
}
loadedFirstItem = async () => {
const lblModal = await this._driver.findElementByAutomationText(modal);
assert.isTrue(await lblModal.isDisplayed());
console.log("First Item loaded!");
}
loadedSecondItem = async () => {
const btnGoBack = await this._driver.findElementByAutomationText(goBack);
assert.isTrue(await btnGoBack.isDisplayed());
console.log("Second Item loaded!");
}
closeDialog = async () => {
const btnYesDialog = await this._driver.findElementByAutomationText(confirmDialog);
await btnYesDialog.tap();
}
goBackFromSecondPage = async () => {
const btnGoBackFromSecondPage = await this._driver.findElementByAutomationText(goBack);
await btnGoBackFromSecondPage.tap();
}
showNestedModalFrame = async () => {
const btnShowNestedModalFrame = await this._driver.findElementByAutomationText(showNestedModalFrame);
await btnShowNestedModalFrame.tap();
}
loadedNestedModalFrame = async () => {
const lblModalNested = await this._driver.waitForElement(modalNested, 5000);
assert.isTrue(await lblModalNested.isDisplayed());
console.log(modalNested + " loaded!");
}
closeModalNested = async () => {
const btnCloseNestedModal = await this._driver.findElementByAutomationText(closeModalNested);
await btnCloseNestedModal.tap();
}
showNestedModalPage = async () => {
const btnShowNestedModalPage = await this._driver.findElementByAutomationText(showNestedModalPage);
await btnShowNestedModalPage.tap();
}
loadedNestedModalPage = async () => {
const btnCloseModalNested = await this._driver.findElementByAutomationText(closeModalNested);
assert.isTrue(await btnCloseModalNested.isDisplayed(), `${closeModalNested} is not shown`);
console.log(closeModalNested + " loaded!");
}
closeModal = async () => {
const btnCloseModal = await this._driver.waitForElement(closeModal, 10000);
await btnCloseModal.click();
}
loadModalNoFrame = async (loadShowModalPageWithFrame: boolean) => {
if (loadShowModalPageWithFrame) {
await this.showModalNoFrame();
}
await this.loadedModalNoFrame();
}
loadModalFrame = async (loadShowModalPageWithFrame: boolean) => {
if (loadShowModalPageWithFrame) {
await this.showModalFrame();
}
await this.loadedModalFrame();
}
loadSharedModal = async (loadShowModalPageWithFrame: boolean) => {
if (loadShowModalPageWithFrame) {
await this.showSharedModal();
}
const lbl = await this._driver.waitForElement(sharedModalView, 5000);
assert.isTrue(await lbl.isDisplayed());
}
loadSharedModalWithPresentationStyle = async (loadShowModalPageWithFrame: boolean) => {
if (loadShowModalPageWithFrame) {
await this.showSharedModalPresentationStyle();
}
const lbl = await this._driver.waitForElement(sharedModalView, 5000);
assert.isTrue(await lbl.isDisplayed());
}
} | the_stack |
import {
Access,
Characteristic,
CharacteristicChange,
CharacteristicEventTypes,
CharacteristicProps,
Formats,
HAPStatus,
Perms,
SerializedCharacteristic,
Units,
uuid
} from '..';
import { SelectedRTPStreamConfiguration } from "./definitions";
import { HapStatusError } from './util/hapStatusError';
function createCharacteristic(type: Formats, customUUID?: string): Characteristic {
return new Characteristic('Test', customUUID || uuid.generate('Foo'), { format: type, perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE] });
}
function createCharacteristicWithProps(props: CharacteristicProps, customUUID?: string): Characteristic {
return new Characteristic('Test', customUUID || uuid.generate('Foo'), props);
}
describe('Characteristic', () => {
beforeEach(() => {
jest.resetAllMocks();
})
describe('#setProps()', () => {
it('should overwrite existing properties', () => {
const characteristic = createCharacteristic(Formats.BOOL);
const NEW_PROPS = {format: Formats.STRING, perms: [Perms.NOTIFY]};
characteristic.setProps(NEW_PROPS);
expect(characteristic.props).toEqual(NEW_PROPS);
});
it('should fail when setting invalid value range', function () {
const characteristic = createCharacteristic(Formats.INT);
const setProps = (min: number, max: number) => characteristic.setProps({
minValue: min,
maxValue: max,
})
expect(() => setProps(-256, -512)).toThrow(Error);
expect(() => setProps(0, -3)).toThrow(Error);
expect(() => setProps(6, 0)).toThrow(Error);
expect(() => setProps(678, 234)).toThrow(Error);
// should allow setting equal values
setProps(0, 0);
setProps(3, 3);
});
it('should reject update to minValue and maxValue when they are out of range for format type', function () {
const characteristic = createCharacteristicWithProps({
format: Formats.UINT8,
perms: [Perms.NOTIFY, Perms.PAIRED_READ],
minValue: 0,
maxValue: 255,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setProps({
minValue: 700,
maxValue: 1000
});
expect(characteristic.props.minValue).toEqual(0); // min for UINT8
expect(characteristic.props.maxValue).toEqual(255); // max for UINT8
expect(mock).toBeCalledTimes(2);
mock.mockReset();
characteristic.setProps({
minValue: -1000,
maxValue: -500
});
expect(characteristic.props.minValue).toEqual(0); // min for UINT8
expect(characteristic.props.maxValue).toEqual(255); // max for UINT8
expect(mock).toBeCalledTimes(2);
mock.mockReset();
characteristic.setProps({
minValue: 10,
maxValue: 1000
});
expect(characteristic.props.minValue).toEqual(10);
expect(characteristic.props.maxValue).toEqual(255); // max for UINT8
expect(mock).toBeCalledTimes(1);
});
it('should reject update to minValue and maxValue when minValue is greater than maxValue', function () {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.NOTIFY, Perms.PAIRED_READ],
});
expect(function() {
characteristic.setProps({
minValue: 1000,
maxValue: 500,
})
}).toThrowError()
expect(characteristic.props.minValue).toBeUndefined();
expect(characteristic.props.maxValue).toBeUndefined();
});
it('should accept update to minValue and maxValue when they are in range for format type', function () {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.NOTIFY, Perms.PAIRED_READ],
minValue: 0,
maxValue: 255,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setProps({
minValue: 10,
maxValue: 240
})
expect(characteristic.props.minValue).toEqual(10);
expect(characteristic.props.maxValue).toEqual(240);
expect(mock).toBeCalledTimes(0);
mock.mockReset();
characteristic.setProps({
minValue: -2147483648,
maxValue: 2147483647
})
expect(characteristic.props.minValue).toEqual(-2147483648);
expect(characteristic.props.maxValue).toEqual(2147483647);
expect(mock).toBeCalledTimes(0);
});
it('should reject non-finite numbers for minValue and maxValue for numeric characteristics', function () {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.NOTIFY, Perms.PAIRED_READ],
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setProps({
minValue: Number.NEGATIVE_INFINITY,
});
expect(characteristic.props.minValue).toEqual(undefined);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining("Property 'minValue' must be a finite number"), expect.anything());
mock.mockReset();
characteristic.setProps({
maxValue: Number.POSITIVE_INFINITY,
});
expect(characteristic.props.maxValue).toEqual(undefined);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining("Property 'maxValue' must be a finite number"), expect.anything());
});
it('should reject NaN numbers for minValue and maxValue for numeric characteristics', function () {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.NOTIFY, Perms.PAIRED_READ],
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setProps({
minValue: NaN,
});
expect(characteristic.props.minValue).toEqual(undefined);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining("Property 'minValue' must be a finite number"), expect.anything());
mock.mockReset();
characteristic.setProps({
maxValue: NaN,
});
expect(characteristic.props.maxValue).toEqual(undefined);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining("Property 'maxValue' must be a finite number"), expect.anything());
});
});
describe("validValuesIterator", () => {
it ("should iterate over min/max value definition", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.PAIRED_READ],
minValue: 2,
maxValue: 5,
});
const result = Array.from(characteristic.validValuesIterator());
expect(result).toEqual([2, 3, 4, 5]);
});
it ("should iterate over min/max value definition with minStep defined", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.PAIRED_READ],
minValue: 2,
maxValue: 10,
minStep: 2, // can't really test with .x precision as of floating point precision
});
const result = Array.from(characteristic.validValuesIterator());
expect(result).toEqual([2, 4, 6, 8, 10]);
});
it ("should iterate over validValues array definition", () => {
const validValues = [1, 3, 4, 5, 8];
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.PAIRED_READ],
validValues: validValues
});
const result = Array.from(characteristic.validValuesIterator());
expect(result).toEqual(validValues);
});
it ("should iterate over validValueRanges definition", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.PAIRED_READ],
validValueRanges: [2, 5],
});
const result = Array.from(characteristic.validValuesIterator());
expect(result).toEqual([2, 3, 4, 5]);
});
it("should iterate over UINT8 definition", () => {
const characteristic = createCharacteristic(Formats.UINT8);
const result = Array.from(characteristic.validValuesIterator());
expect(result).toEqual(Array.from(new Uint8Array(256).map((value, i) => i)))
});
// we could do the same for UINT16, UINT32 and UINT64 but i think thats kind of pointless and takes to long
});
describe('#subscribe()', () => {
it('correctly adds a single subscription', () => {
const characteristic = createCharacteristic(Formats.BOOL);
const subscribeSpy = jest.fn();
characteristic.on(CharacteristicEventTypes.SUBSCRIBE, subscribeSpy);
characteristic.subscribe();
expect(subscribeSpy).toHaveBeenCalledTimes(1);
// @ts-expect-error
expect(characteristic.subscriptions).toEqual(1);
});
it('correctly adds multiple subscriptions', () => {
const characteristic = createCharacteristic(Formats.BOOL);
const subscribeSpy = jest.fn();
characteristic.on(CharacteristicEventTypes.SUBSCRIBE, subscribeSpy);
characteristic.subscribe();
characteristic.subscribe();
characteristic.subscribe();
expect(subscribeSpy).toHaveBeenCalledTimes(1);
// @ts-expect-error
expect(characteristic.subscriptions).toEqual(3);
});
});
describe('#unsubscribe()', () => {
it('correctly removes a single subscription', () => {
const characteristic = createCharacteristic(Formats.BOOL);
const subscribeSpy = jest.fn();
const unsubscribeSpy = jest.fn();
characteristic.on(CharacteristicEventTypes.SUBSCRIBE, subscribeSpy);
characteristic.on(CharacteristicEventTypes.UNSUBSCRIBE, unsubscribeSpy);
characteristic.subscribe();
characteristic.unsubscribe();
expect(subscribeSpy).toHaveBeenCalledTimes(1);
expect(unsubscribeSpy).toHaveBeenCalledTimes(1);
// @ts-expect-error
expect(characteristic.subscriptions).toEqual(0);
});
it('correctly removes multiple subscriptions', () => {
const characteristic = createCharacteristic(Formats.BOOL);
const subscribeSpy = jest.fn();
const unsubscribeSpy = jest.fn();
characteristic.on(CharacteristicEventTypes.SUBSCRIBE, subscribeSpy);
characteristic.on(CharacteristicEventTypes.UNSUBSCRIBE, unsubscribeSpy);
characteristic.subscribe();
characteristic.subscribe();
characteristic.subscribe();
characteristic.unsubscribe();
characteristic.unsubscribe();
characteristic.unsubscribe();
expect(subscribeSpy).toHaveBeenCalledTimes(1);
expect(unsubscribeSpy).toHaveBeenCalledTimes(1);
// @ts-expect-error
expect(characteristic.subscriptions).toEqual(0);
});
});
describe('#handleGetRequest()', () => {
it('should handle special event only characteristics', (callback) => {
const characteristic = createCharacteristic(Formats.BOOL, Characteristic.ProgrammableSwitchEvent.UUID);
characteristic.handleGetRequest().then(() => {
expect(characteristic.statusCode).toEqual(HAPStatus.SUCCESS);
expect(characteristic.value).toEqual(null);
callback();
});
});
it('should return cached values if no listeners are registered', (callback) => {
const characteristic = createCharacteristic(Formats.BOOL);
characteristic.handleGetRequest().then(() => {
expect(characteristic.statusCode).toEqual(HAPStatus.SUCCESS);
expect(characteristic.value).toEqual(null);
callback();
});
});
});
describe('#validateClientSuppliedValue()', () => {
it('rejects undefined values from client', async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.UINT8,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest(undefined as unknown as boolean, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// the existing valid value should remain
expect(characteristic.value).toEqual(1);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalled();
});
it('rejects invalid values for the boolean format type', async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.BOOL,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(true);
// numbers other than 1 or 0 should throw an error
await expect(characteristic.handleSetRequest(20, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// strings should throw an error
await expect(characteristic.handleSetRequest("true", null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// the existing valid value should remain
expect(characteristic.value).toEqual(true);
// 0 should set the value to false
await expect(characteristic.handleSetRequest(0, null as unknown as undefined))
.resolves.toEqual(undefined);
expect(characteristic.value).toEqual(false);
// 1 should set the value to true
await expect(characteristic.handleSetRequest(1, null as unknown as undefined))
.resolves.toEqual(undefined);
expect(characteristic.value).toEqual(true);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(4);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"boolean types sent for %p types should be transformed from false to 0", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
await characteristic.handleSetRequest(false, null as unknown as undefined);
expect(characteristic.value).toEqual(0);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalled();
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"boolean types sent for %p types should be transformed from true to 1", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
await characteristic.handleSetRequest(true, null as unknown as undefined);
expect(characteristic.value).toEqual(1);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalled();
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"rejects string values sent for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest("what is this!", null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// the existing valid value should remain
expect(characteristic.value).toEqual(1);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalled();
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"ensure maxValue is not exceeded for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest(100, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// this should throw an error
await expect(characteristic.handleSetRequest(-100, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// value should revert to
expect(characteristic.value).toEqual(1);
// this should pass
await expect(characteristic.handleSetRequest(0, null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be 3
expect(characteristic.value).toEqual(0);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(3);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"ensure NaN is rejected for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1,
minValue: 0,
minStep: 1,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest(NaN, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// value should revert to
expect(characteristic.value).toEqual(1);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(1);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"ensure non-finite values are rejected for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest(Infinity, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// value should revert to
expect(characteristic.value).toEqual(1);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(1);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"ensure value is rejected if outside valid values for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 10,
minValue: 0,
minStep: 1,
validValues: [1, 3, 5, 10],
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(1);
// this should throw an error
await expect(characteristic.handleSetRequest(6, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST)
// value should revert to
expect(characteristic.value).toEqual(1);
// this should pass
await expect(characteristic.handleSetRequest(3, null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be 3
expect(characteristic.value).toEqual(3);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(2);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"ensure value is rejected if outside valid value ranges for %p types sent from client", async (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
maxValue: 1000,
minValue: 0,
minStep: 1,
validValueRanges: [50, 55],
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(50);
// this should throw an error
await expect(characteristic.handleSetRequest(100, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// this should throw an error
await expect(characteristic.handleSetRequest(20, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// value should still be 50
expect(characteristic.value).toEqual(50);
// this should pass
await expect(characteristic.handleSetRequest(52, null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be 52
expect(characteristic.value).toEqual(52);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(3);
});
test.each([Formats.STRING, Formats.TLV8, Formats.DATA])(
"rejects non-string values for the %p format type from the client", async (stringType) => {
const characteristic = createCharacteristicWithProps({
format: stringType,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue('some string');
// numbers should throw an error
await expect(characteristic.handleSetRequest(1234, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// booleans should throw an error
await expect(characteristic.handleSetRequest(false, null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// the existing valid value should remain
expect(characteristic.value).toEqual('some string');
// strings should pass
await expect(characteristic.handleSetRequest('some other test string', null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be updated
expect(characteristic.value).toEqual('some other test string');
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(3);
});
it('should accept Formats.FLOAT with precision provided by client', async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue(0.0005);
// the existing valid value should remain
expect(characteristic.value).toEqual(0.0005);
// should allow float
await expect(characteristic.handleSetRequest(0.0001005, null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be updated
expect(characteristic.value).toEqual(0.0001005);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(1);
});
it("should accept negative floats in range for Formats.FLOAT provided by the client", async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: -1000,
maxValue: 1000,
});
// @ts-expect-error - spying on private property
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// should allow negative float
await expect(characteristic.handleSetRequest(-0.013, null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be updated
expect(characteristic.value).toEqual(-0.013);
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(1);
});
it('rejects string values exceeding the max length from the client', async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.STRING,
maxLen: 5,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue('abcde');
// should reject strings that are to long
await expect(characteristic.handleSetRequest('this is to long', null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// the existing valid value should remain
expect(characteristic.value).toEqual('abcde');
// strings should pass
await expect(characteristic.handleSetRequest('abc', null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be updated
expect(characteristic.value).toEqual('abc');
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(2);
});
it('rejects data values exceeding the max length from the client', async () => {
const characteristic = createCharacteristicWithProps({
format: Formats.DATA,
maxDataLen: 5,
perms: [Perms.EVENTS, Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error
const validateClientSuppliedValueMock = jest.spyOn(characteristic, 'validateClientSuppliedValue');
// set initial known good value
characteristic.setValue('abcde');
// should reject strings that are to long
await expect(characteristic.handleSetRequest('this is to long', null as unknown as undefined))
.rejects.toEqual(HAPStatus.INVALID_VALUE_IN_REQUEST);
// the existing valid value should remain
expect(characteristic.value).toEqual('abcde');
// strings should pass
await expect(characteristic.handleSetRequest('abc', null as unknown as undefined))
.resolves.toEqual(undefined);
// value should now be updated
expect(characteristic.value).toEqual('abc');
// ensure validator was actually called
expect(validateClientSuppliedValueMock).toBeCalledTimes(2);
});
});
describe('#validateUserInput()', () => {
it('should validate an integer property', () => {
const VALUE = 1024;
const characteristic = createCharacteristic(Formats.INT);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a float property', () => {
const VALUE = 1.024;
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
minStep: 0.001,
perms: [Perms.NOTIFY],
});
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a UINT8 property', () => {
const VALUE = 10;
const characteristic = createCharacteristic(Formats.UINT8);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a UINT16 property', () => {
const VALUE = 10;
const characteristic = createCharacteristic(Formats.UINT16);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a UINT32 property', () => {
const VALUE = 10;
const characteristic = createCharacteristic(Formats.UINT32);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a UINT64 property', () => {
const VALUE = 10;
const characteristic = createCharacteristic(Formats.UINT64);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a boolean property', () => {
const VALUE = true;
const characteristic = createCharacteristic(Formats.BOOL);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a string property', () => {
const VALUE = 'Test';
const characteristic = createCharacteristic(Formats.STRING);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a data property', () => {
const VALUE = Buffer.from("Hello my good friend. Have a nice day!", "ascii").toString("base64");
const characteristic = createCharacteristic(Formats.DATA);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a TLV8 property', () => {
const VALUE = '';
const characteristic = createCharacteristic(Formats.TLV8);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate a dictionary property', () => {
const VALUE = {};
const characteristic = createCharacteristic(Formats.DICTIONARY);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it('should validate an array property', () => {
const VALUE = ['asd'];
const characteristic = createCharacteristic(Formats.ARRAY);
// @ts-expect-error
expect(characteristic.validateUserInput(VALUE)).toEqual(VALUE);
});
it("should validate boolean inputs", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.BOOL,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
characteristic.setValue(true);
expect(characteristic.value).toEqual(true);
characteristic.setValue(false);
expect(characteristic.value).toEqual(false);
characteristic.setValue(1);
expect(characteristic.value).toEqual(true);
characteristic.setValue(0);
expect(characteristic.value).toEqual(false);
characteristic.setValue("1");
expect(characteristic.value).toEqual(true);
characteristic.setValue("true");
expect(characteristic.value).toEqual(true);
characteristic.setValue("0");
expect(characteristic.value).toEqual(false);
characteristic.setValue("false");
expect(characteristic.value).toEqual(false);
characteristic.setValue({ some: 'object' });
expect(characteristic.value).toEqual(false);
expect(mock).toBeCalledTimes(1);
});
it("should validate boolean inputs when value is undefined", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.BOOL,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
characteristic.setValue(undefined as unknown as boolean);
expect(characteristic.value).toEqual(false);
expect(mock).toBeCalledTimes(1);
});
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"should validate %p inputs", (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: 0,
maxValue: 100,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
characteristic.setValue(1);
expect(characteristic.value).toEqual(1);
// round to nearest valid value, trigger warning
mock.mockReset();
characteristic.setValue(-100);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(1);
// round to nearest valid value, trigger warning
mock.mockReset();
characteristic.setValue(200);
expect(characteristic.value).toEqual(100);
expect(mock).toBeCalledTimes(1);
// parse string
mock.mockReset();
characteristic.setValue('50');
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(0);
// handle NaN from non-numeric string, restore last known value, trigger warning
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue('SOME STRING');
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining('NaN'))
// handle NaN: number from number value
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue(NaN);
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(1);
expect(mock).toBeCalledWith(expect.stringContaining('NaN'))
// handle object, restore last known value, trigger warning
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue({ some: 'object' });
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(1);
// handle boolean - true -> 1
mock.mockReset();
characteristic.setValue(true);
expect(characteristic.value).toEqual(1);
expect(mock).toBeCalledTimes(0);
// handle boolean - false -> 0
mock.mockReset();
characteristic.setValue(false);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(0);
}
);
test.each([Formats.INT, Formats.FLOAT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"should validate %p inputs when value is undefined", (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: 0,
maxValue: 100,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// undefined values should be set to the minValue if not yet set
mock.mockReset();
characteristic.setValue(undefined as unknown as boolean);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(1);
// undefined values should be set to the existing value if set
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue(undefined as unknown as boolean);
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(1);
}
);
test.each([Formats.INT, Formats.UINT8, Formats.UINT16, Formats.UINT32, Formats.UINT64])(
"should round when a float is provided for %p inputs", (intType) => {
const characteristic = createCharacteristicWithProps({
format: intType,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: 0,
maxValue: 100,
});
characteristic.setValue(99.5);
expect(characteristic.value).toEqual(100);
characteristic.setValue(0.1);
expect(characteristic.value).toEqual(0);
}
);
it("should not round floats for Formats.FLOAT", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: 0,
maxValue: 100,
});
characteristic.setValue(99.5);
expect(characteristic.value).toEqual(99.5);
characteristic.setValue(0.1);
expect(characteristic.value).toEqual(0.1);
});
it("should validate Formats.FLOAT with precision", () => {
const characteristic = new Characteristic.CurrentAmbientLightLevel();
// @ts-expect-error - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setValue(0);
expect(characteristic.value).toEqual(0.0001);
expect(mock).toBeCalledTimes(1);
mock.mockReset();
characteristic.setValue(0.0001);
expect(characteristic.value).toEqual(0.0001);
expect(mock).toBeCalledTimes(0);
mock.mockReset();
characteristic.setValue('0.0001');
expect(characteristic.value).toEqual(0.0001);
expect(mock).toBeCalledTimes(0);
mock.mockReset();
characteristic.setValue(100000.00000001);
expect(characteristic.value).toEqual(100000);
expect(mock).toBeCalledTimes(1);
mock.mockReset();
characteristic.setValue(100000);
expect(characteristic.value).toEqual(100000);
expect(mock).toBeCalledTimes(0);
});
it("should allow negative floats in range for Formats.FLOAT", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: -1000,
maxValue: 1000,
});
// @ts-expect-error - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setValue(-0.013);
expect(characteristic.value).toEqual(-0.013);
expect(mock).toBeCalledTimes(0);
});
it("should not allow non-finite floats in range for Formats.FLOAT", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-expect-error - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
mock.mockReset();
characteristic.setValue(Infinity);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(1);
mock.mockReset();
characteristic.setValue(Number.POSITIVE_INFINITY);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(1);
mock.mockReset();
characteristic.setValue(Number.NEGATIVE_INFINITY);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(1);
});
it("should validate string inputs", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.STRING,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
maxLen: 15,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// valid string
mock.mockReset();
characteristic.setValue("ok string");
expect(characteristic.value).toEqual("ok string");
expect(mock).toBeCalledTimes(0);
// number - convert to string - trigger warning
mock.mockReset();
characteristic.setValue(12345);
expect(characteristic.value).toEqual("12345");
expect(mock).toBeCalledTimes(1);
// not a string or number, use last known good value and trigger warning
mock.mockReset();
characteristic.setValue("ok string");
characteristic.setValue({ ok: 'an object' });
expect(characteristic.value).toEqual("ok string");
expect(mock).toBeCalledTimes(1);
// max length exceeded
mock.mockReset();
characteristic.setValue("this string exceeds the max length allowed");
expect(characteristic.value).toEqual("this string exc");
expect(mock).toBeCalledTimes(1);
});
it("should validate string inputs when undefined", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.STRING,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
maxLen: 15,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// undefined values should be set to "undefined" of no valid value is set yet
mock.mockReset();
characteristic.setValue(undefined as unknown as boolean);
expect(characteristic.value).toEqual("undefined");
expect(mock).toBeCalledTimes(1);
// undefined values should revert back to last known good value if set
mock.mockReset();
characteristic.setValue("ok string");
characteristic.setValue(undefined as unknown as boolean);
expect(characteristic.value).toEqual("ok string");
expect(mock).toBeCalledTimes(1);
});
it("should validate data type intputs", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.DATA,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
maxDataLen: 15,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// valid data
mock.mockReset();
characteristic.setValue("some data");
expect(characteristic.value).toEqual("some data");
expect(mock).toBeCalledTimes(0);
// not valid data
mock.mockReset();
characteristic.setValue({ some: 'data' });
expect(mock).toBeCalledTimes(1);
// max length exceeded
mock.mockReset();
characteristic.setValue("this string exceeds the max length allowed");
expect(mock).toBeCalledTimes(1);
});
it("should handle null inputs correctly for scalar Apple characteristics", () => {
const characteristic = new Characteristic('CurrentTemperature', Characteristic.CurrentTemperature.UUID, {
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
format: Formats.FLOAT,
minValue: 0,
maxValue: 100,
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// if the initial value is null, validation should set a valid default
mock.mockReset();
characteristic.setValue(null as unknown as boolean);
expect(characteristic.value).toEqual(0);
expect(mock).toBeCalledTimes(2);
// if the value has been previously set, and null is received, the previous value should be returned,
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue(null as unknown as boolean);
expect(characteristic.value).toEqual(50);
expect(mock).toBeCalledTimes(1);
});
it("should handle null inputs correctly for scalar non-scalar Apple characteristics", () => {
const characteristicTLV = new SelectedRTPStreamConfiguration();
const characteristicData = new Characteristic("Data characteristic", Characteristic.SupportedRTPConfiguration.UUID, {
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
format: Formats.DATA,
});
const exampleString = "Example String"; // data and tlv8 are both string based
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristicTLV, 'characteristicWarning');
// null is a valid value for tlv8 format
mock.mockReset();
characteristicTLV.setValue(exampleString);
expect(characteristicTLV.value).toEqual(exampleString);
characteristicTLV.setValue(null as unknown as string);
expect(characteristicTLV.value).toEqual(null);
expect(mock).toBeCalledTimes(0);
// null is a valid value for data format
mock.mockReset();
characteristicData.setValue(exampleString);
expect(characteristicData.value).toEqual(exampleString);
characteristicData.setValue(null as unknown as string);
expect(characteristicData.value).toEqual(null);
expect(mock).toBeCalledTimes(0);
});
it("should handle null inputs correctly for non-Apple characteristics", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE]
});
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// if the initial value is null, still allow null for non-Apple characteristics
mock.mockReset();
characteristic.setValue(null as unknown as boolean);
expect(characteristic.value).toEqual(null);
expect(mock).toBeCalledTimes(0);
// if the value has been previously set, and null is received, still allow null for non-Apple characteristics
mock.mockReset();
characteristic.setValue(50);
characteristic.setValue(null as unknown as boolean);
expect(characteristic.value).toEqual(null);
expect(mock).toBeCalledTimes(0);
});
});
describe('#getDefaultValue()', () => {
it('should get the correct default value for a boolean property', () => {
const characteristic = createCharacteristic(Formats.BOOL);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(false);
});
it('should get the correct default value for a string property', () => {
const characteristic = createCharacteristic(Formats.STRING);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual('');
});
it('should get the correct default value for a data property', () => {
const characteristic = createCharacteristic(Formats.DATA);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(null);
});
it('should get the correct default value for a TLV8 property', () => {
const characteristic = createCharacteristic(Formats.TLV8);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(null);
});
it('should get the correct default value for a dictionary property', () => {
const characteristic = createCharacteristic(Formats.DICTIONARY);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual({});
});
it('should get the correct default value for an array property', () => {
const characteristic = createCharacteristic(Formats.ARRAY);
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual([]);
});
it('should get the correct default value a UINT8 property without minValue', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.UINT8,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(0);
expect(characteristic.value).toEqual(null); // null if never set
});
it('should get the correct default value a UINT8 property with minValue', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.UINT8,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
minValue: 50,
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(50);
expect(characteristic.value).toEqual(null); // null if never set
});
it('should get the correct default value a INT property without minValue', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(0);
expect(characteristic.value).toEqual(null); // null if never set
});
it('should get the correct default value a INT property with minValue', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
minValue: 50,
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(50);
expect(characteristic.value).toEqual(null); // null if never set
});
it('should get the correct default value for the current temperature characteristic', () => {
const characteristic = new Characteristic.CurrentTemperature();
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(0);
expect(characteristic.value).toEqual(0);
});
it('should get the default value from the first item in the validValues prop', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
validValues: [5, 4, 3, 2]
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(5);
expect(characteristic.value).toEqual(null); // null if never set
});
it('should get the default value from minValue prop if set', () => {
const characteristic = createCharacteristicWithProps({
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
minValue: 100,
maxValue: 255,
});
// @ts-expect-error
expect(characteristic.getDefaultValue()).toEqual(100);
expect(characteristic.value).toEqual(null); // null if never set
});
});
describe('#toHAP()', () => {
});
describe(`@${CharacteristicEventTypes.GET}`, () => {
it('should call any listeners for the event', (callback) => {
const characteristic = createCharacteristic(Formats.STRING);
const listenerCallback = jest.fn();
characteristic.handleGetRequest().then(() => {
characteristic.on(CharacteristicEventTypes.GET, listenerCallback);
characteristic.handleGetRequest();
expect(listenerCallback).toHaveBeenCalledTimes(1);
callback();
})
});
it("should handle GET event errors gracefully when using on('get')", async () => {
const characteristic = createCharacteristic(Formats.STRING);
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// throw HapStatusError - should not trigger characteristic warning
mock.mockReset();
characteristic.removeAllListeners('get');
characteristic.on('get', (callback) => {
callback(new HapStatusError(HAPStatus.RESOURCE_BUSY));
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw number - should not trigger characteristic warning
mock.mockReset();
characteristic.removeAllListeners('get');
characteristic.on('get', (callback) => {
callback(HAPStatus.RESOURCE_BUSY);
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw out of range number - should convert status code to SERVICE_COMMUNICATION_FAILURE
mock.mockReset();
characteristic.removeAllListeners('get');
characteristic.on('get', (callback) => {
callback(234234234234);
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw other error - callback style getters should still not trigger warning when error is passed in
mock.mockReset();
characteristic.removeAllListeners('get');
characteristic.on('get', (callback) => {
callback(new Error('Something else'));
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
});
});
describe("onGet handler", () => {
it("should ignore GET event handler when onGet was specified", async () => {
const characteristic = createCharacteristic(Formats.STRING);
const listenerCallback = jest.fn().mockImplementation((callback) => {
callback(undefined, "OddValue");
});
const handlerMock = jest.fn();
characteristic.onGet(() => {
handlerMock();
return "CurrentValue";
});
characteristic.on(CharacteristicEventTypes.GET, listenerCallback);
const value = await characteristic.handleGetRequest();
expect(value).toEqual("CurrentValue");
expect(handlerMock).toHaveBeenCalledTimes(1);
expect(listenerCallback).toHaveBeenCalledTimes(0);
});
it("should handle GET event errors gracefully when using the onGet handler", async () => {
const characteristic = createCharacteristic(Formats.STRING);
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// throw HapStatusError - should not trigger characteristic warning
mock.mockReset();
characteristic.onGet(() => {
throw new HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw number - should not trigger characteristic warning
mock.mockReset();
characteristic.onGet(() => {
throw HAPStatus.SERVICE_COMMUNICATION_FAILURE;
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw out of range number - should convert status code to SERVICE_COMMUNICATION_FAILURE
mock.mockReset();
characteristic.onGet(() => {
throw 234234234234;
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw other error - should trigger characteristic warning
mock.mockReset();
characteristic.onGet(() => {
throw new Error('A Random Error');
});
await expect(characteristic.handleGetRequest()).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(1);
});
});
describe(`@${CharacteristicEventTypes.SET}`, () => {
it('should call any listeners for the event', () => {
const characteristic = createCharacteristic(Formats.STRING);
const VALUE = 'NewValue';
const listenerCallback = jest.fn();
characteristic.handleSetRequest(VALUE);
characteristic.on(CharacteristicEventTypes.SET, listenerCallback);
characteristic.handleSetRequest(VALUE);
expect(listenerCallback).toHaveBeenCalledTimes(1);
});
it("should handle SET event errors gracefully when using on('set')", async () => {
const characteristic = createCharacteristic(Formats.STRING);
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// throw HapStatusError - should not trigger characteristic warning
mock.mockReset();
characteristic.removeAllListeners('set');
characteristic.on('set', (value, callback) => {
callback(new HapStatusError(HAPStatus.RESOURCE_BUSY));
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw number - should not trigger characteristic warning
mock.mockReset();
characteristic.removeAllListeners('set');
characteristic.on('set', (value, callback) => {
callback(HAPStatus.RESOURCE_BUSY);
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw out of range number - should convert status code to SERVICE_COMMUNICATION_FAILURE
mock.mockReset();
characteristic.removeAllListeners('set');
characteristic.on('set', (value, callback) => {
callback(234234234234);
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw other error - callback style setters should still not trigger warning when error is passed in
mock.mockReset();
characteristic.removeAllListeners('set');
characteristic.on('set', (value, callback) => {
callback(new Error('Something else'));
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
});
});
describe("onSet handler", () => {
it("should ignore SET event handler when onSet was specified", () => {
const characteristic = createCharacteristic(Formats.STRING);
const listenerCallback = jest.fn();
const handlerMock = jest.fn();
characteristic.onSet(value => {
handlerMock(value);
expect(value).toEqual("NewValue");
return;
});
characteristic.on(CharacteristicEventTypes.SET, listenerCallback);
characteristic.handleSetRequest("NewValue");
expect(handlerMock).toHaveBeenCalledTimes(1);
expect(listenerCallback).toHaveBeenCalledTimes(0);
});
it("should handle SET event errors gracefully when using onSet handler", async () => {
const characteristic = createCharacteristic(Formats.STRING);
// @ts-ignore - spying on private property
const mock = jest.spyOn(characteristic, 'characteristicWarning');
// throw HapStatusError - should not trigger characteristic warning
mock.mockReset();
characteristic.onSet(() => {
throw new HapStatusError(HAPStatus.RESOURCE_BUSY);
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw number - should not trigger characteristic warning
mock.mockReset();
characteristic.onSet(() => {
throw HAPStatus.RESOURCE_BUSY;
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.RESOURCE_BUSY)
expect(characteristic.statusCode).toEqual(HAPStatus.RESOURCE_BUSY);
expect(mock).toBeCalledTimes(0);
// throw out of range number - should convert status code to SERVICE_COMMUNICATION_FAILURE
mock.mockReset();
characteristic.onSet(() => {
throw 234234234234;
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(0);
// throw other error - should trigger characteristic warning
mock.mockReset();
characteristic.onSet(() => {
throw new Error('A Random Error');
});
await expect(characteristic.handleSetRequest('hello')).rejects.toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE)
expect(characteristic.statusCode).toEqual(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
expect(mock).toBeCalledTimes(1);
});
});
describe(`@${CharacteristicEventTypes.CHANGE}`, () => {
it('should call listeners for the event when the characteristic is event-only, and the value is set', (callback) => {
const characteristic = createCharacteristic(Formats.STRING, Characteristic.ProgrammableSwitchEvent.UUID);
const VALUE = 'NewValue';
const listenerCallback = jest.fn();
const setValueCallback = jest.fn();
characteristic.setValue(VALUE, () => {
setValueCallback();
characteristic.on(CharacteristicEventTypes.CHANGE, listenerCallback);
characteristic.setValue(VALUE, () => {
setValueCallback();
expect(listenerCallback).toHaveBeenCalledTimes(1);
expect(setValueCallback).toHaveBeenCalledTimes(2);
callback();
});
})
});
it('should call any listeners for the event when the characteristic is event-only, and the value is updated', () => {
const characteristic = createCharacteristic(Formats.STRING);
// characteristic.eventOnlyCharacteristic = true;
const VALUE = 'NewValue';
const listenerCallback = jest.fn();
const updateValueCallback = jest.fn();
characteristic.on(CharacteristicEventTypes.CHANGE, listenerCallback);
// noinspection JSDeprecatedSymbols
characteristic.updateValue(VALUE, updateValueCallback)
expect(listenerCallback).toHaveBeenCalledTimes(1);
expect(updateValueCallback).toHaveBeenCalledTimes(1);
});
it("should call the change listener with proper context when supplied as second argument to updateValue", () => {
const characteristic = createCharacteristic(Formats.STRING);
const VALUE = "NewValue";
const CONTEXT = "Context";
const listener = jest.fn().mockImplementation((change: CharacteristicChange) => {
expect(change.newValue).toEqual(VALUE);
expect(change.context).toEqual(CONTEXT);
});
characteristic.on(CharacteristicEventTypes.CHANGE, listener);
characteristic.updateValue(VALUE, CONTEXT);
expect(listener).toHaveBeenCalledTimes(1);
});
it("should call the change listener with proper context when supplied as second argument to setValue", () => {
const characteristic = createCharacteristic(Formats.STRING);
const VALUE = "NewValue";
const CONTEXT = "Context";
const listener = jest.fn().mockImplementation((change: CharacteristicChange) => {
expect(change.newValue).toEqual(VALUE);
expect(change.context).toEqual(CONTEXT);
});
characteristic.on(CharacteristicEventTypes.CHANGE, listener);
characteristic.setValue(VALUE, CONTEXT);
expect(listener).toHaveBeenCalledTimes(1);
});
});
describe(`@${CharacteristicEventTypes.SUBSCRIBE}`, () => {
it('should call any listeners for the event', () => {
const characteristic = createCharacteristic(Formats.STRING);
const cb = jest.fn();
characteristic.on(CharacteristicEventTypes.SUBSCRIBE, cb);
characteristic.subscribe();
expect(cb).toHaveBeenCalledTimes(1);
});
});
describe(`@${CharacteristicEventTypes.UNSUBSCRIBE}`, () => {
it('should call any listeners for the event', () => {
const characteristic = createCharacteristic(Formats.STRING);
const cb = jest.fn();
characteristic.subscribe();
characteristic.on(CharacteristicEventTypes.UNSUBSCRIBE, cb);
characteristic.unsubscribe();
expect(cb).toHaveBeenCalledTimes(1);
});
it('should not call any listeners for the event if none are registered', () => {
const characteristic = createCharacteristic(Formats.STRING);
const cb = jest.fn();
characteristic.on(CharacteristicEventTypes.UNSUBSCRIBE, cb);
characteristic.unsubscribe();
expect(cb).not.toHaveBeenCalled();
});
});
describe('#serialize', () => {
it('should serialize characteristic', () => {
const props: CharacteristicProps = {
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
unit: Units.LUX,
maxValue: 1234,
minValue: 123,
validValueRanges: [123, 1234],
adminOnlyAccess: [Access.WRITE],
};
const characteristic = createCharacteristicWithProps(props, Characteristic.ProgrammableSwitchEvent.UUID);
characteristic.value = "TestValue";
const json = Characteristic.serialize(characteristic);
expect(json).toEqual({
displayName: characteristic.displayName,
UUID: characteristic.UUID,
props: props,
value: "TestValue",
eventOnlyCharacteristic: true,
})
});
it("should serialize characteristic with proper constructor name", () => {
const characteristic = new Characteristic.Name();
characteristic.updateValue("New Name!");
const json = Characteristic.serialize(characteristic);
expect(json).toEqual({
displayName: 'Name',
UUID: '00000023-0000-1000-8000-0026BB765291',
eventOnlyCharacteristic: false,
constructorName: 'Name',
value: 'New Name!',
props: { format: 'string', perms: [ 'pr' ], maxLen: 64 }
});
});
});
describe('#deserialize', () => {
it('should deserialize legacy json from homebridge', () => {
const json = JSON.parse('{"displayName": "On", "UUID": "00000025-0000-1000-8000-0026BB765291", ' +
'"props": {"format": "int", "unit": "seconds", "minValue": 4, "maxValue": 6, "minStep": 0.1, "perms": ["pr", "pw", "ev"]}, ' +
'"value": false, "eventOnlyCharacteristic": false}');
const characteristic = Characteristic.deserialize(json);
expect(characteristic.displayName).toEqual(json.displayName);
expect(characteristic.UUID).toEqual(json.UUID);
expect(characteristic.props).toEqual(json.props);
expect(characteristic.value).toEqual(json.value);
});
it('should deserialize complete json', () => {
const json: SerializedCharacteristic = {
displayName: "MyName",
UUID: "00000001-0000-1000-8000-0026BB765291",
props: {
format: Formats.INT,
perms: [Perms.TIMED_WRITE, Perms.PAIRED_READ],
unit: Units.LUX,
maxValue: 1234,
minValue: 123,
validValueRanges: [123, 1234],
adminOnlyAccess: [Access.NOTIFY, Access.READ],
},
value: "testValue",
eventOnlyCharacteristic: false,
};
const characteristic = Characteristic.deserialize(json);
expect(characteristic.displayName).toEqual(json.displayName);
expect(characteristic.UUID).toEqual(json.UUID);
expect(characteristic.props).toEqual(json.props);
expect(characteristic.value).toEqual(json.value);
});
it("should deserialize from json with constructor name", () => {
const json: SerializedCharacteristic = {
displayName: 'Name',
UUID: '00000023-0000-1000-8000-0026BB765291',
eventOnlyCharacteristic: false,
constructorName: 'Name',
value: 'New Name!',
props: { format: 'string', perms: [ Perms.PAIRED_READ ], maxLen: 64 }
};
const characteristic = Characteristic.deserialize(json);
expect(characteristic instanceof Characteristic.Name).toBeTruthy();
});
});
}); | the_stack |
'use strict'; // necessary for es6 output in node
import { browser, element, by } from 'protractor';
function finalDemoAddressForm(element: any, index: number) {
let form = {
street: element.all(by.css('input[formcontrolname=street]')).get(index).getAttribute('value'),
city: element.all(by.css('input[formcontrolname=city]')).get(index).getAttribute('value'),
state: element.all(by.css('select[formcontrolname=state]')).get(index).getAttribute('value'),
zip: element.all(by.css('input[formcontrolname=zip]')).get(index).getAttribute('value')
};
return form;
}
describe('Reactive forms', function() {
let select: any;
beforeEach(function() {
browser.get('');
select = element(by.css('.container > h4 > select'));
});
describe('navigation', function() {
it('should display the title', function() {
let title = element(by.css('.container > h1'));
expect(title.getText()).toBe('Reactive Forms');
});
it('should contain a dropdown with each example', function() {
expect(select.isDisplayed()).toBe(true);
});
it('should have 9 options for different demos', function() {
let options = select.all(by.tagName('option'));
expect(options.count()).toBe(9);
});
it('should start with Final Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('Final Demo');
});
});
});
// *************Begin Final Demo test*******************************
describe('final demo', function() {
it('does not select any hero by default', function() {
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
it('refreshes the page upon button click', function() {
// We move to another page...
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
let refresh = element(by.css('button'));
refresh.click();
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
describe('Whirlwind form', function() {
beforeEach(function() {
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwind');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Whirlwind');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('123 Main');
expect(address1.state).toBe('CA');
expect(address1.zip).toBe('94801');
expect(address1.city).toBe('Anywhere');
let address2 = finalDemoAddressForm(element, 1);
expect(address2.street).toBe('456 Maple');
expect(address2.state).toBe('VA');
expect(address2.zip).toBe('23226');
expect(address2.city).toBe('Somewhere');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail > p'));
expect(json.getText()).toContain('Whirlwind');
expect(json.getText()).toContain('Anywhere');
expect(json.getText()).toContain('Somewhere');
expect(json.getText()).toContain('VA');
});
it('has two disabled buttons by default', function() {
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBe('true');
expect(buttons.get(1).getAttribute('disabled')).toBe('true');
});
it('enables the buttons after we edit the form', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBeNull();
expect(buttons.get(1).getAttribute('disabled')).toBeNull();
});
it('saves the changes when the save button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let save = element.all(by.css('hero-detail > form > div > button')).get(0);
save.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwinda');
});
it('reverts the changes when the revert button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let revert = element.all(by.css('hero-detail > form > div > button')).get(1);
revert.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwind');
expect(nameInput.getAttribute('value')).toBe('Whirlwind');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(3);
newLairButton.click();
let address3 = finalDemoAddressForm(element, 2);
expect(address3.street).toBe('');
expect(address3.state).toBe('');
expect(address3.zip).toBe('');
expect(address3.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
});
describe('Bombastic form', function() {
beforeEach(function() {
let bombastaButton = element.all(by.css('nav a')).get(1);
bombastaButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Bombastic');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Bombastic');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('789 Elm');
// expect(address1.state).toBe('OH');
expect(address1.zip).toBe('04501');
expect(address1.city).toBe('Smallville');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail > p'));
expect(json.getText()).toContain('Bombastic');
expect(json.getText()).toContain('Smallville');
expect(json.getText()).toContain('OH');
expect(json.getText()).toContain('04501');
});
it('has two disabled buttons by default', function() {
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBe('true');
expect(buttons.get(1).getAttribute('disabled')).toBe('true');
});
it('enables the buttons after we edit the form', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBeNull();
expect(buttons.get(1).getAttribute('disabled')).toBeNull();
});
it('saves the changes when the save button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let save = element.all(by.css('hero-detail > form > div > button')).get(0);
save.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Bombastica');
});
it('reverts the changes when the revert button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let revert = element.all(by.css('hero-detail > form > div > button')).get(1);
revert.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Bombastic');
expect(nameInput.getAttribute('value')).toBe('Bombastic');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(3);
newLairButton.click();
let address2 = finalDemoAddressForm(element, 1);
expect(address2.street).toBe('');
expect(address2.state).toBe('');
expect(address2.zip).toBe('');
expect(address2.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
});
describe('Magneta form', function() {
beforeEach(function() {
let magnetaButton = element.all(by.css('nav a')).get(2);
magnetaButton.click();
});
it('should show hero information when the button is clicked', function() {
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Magneta');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Magneta');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail > p'));
expect(json.getText()).toContain('Magneta');
});
it('has two disabled buttons by default', function() {
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBe('true');
expect(buttons.get(1).getAttribute('disabled')).toBe('true');
});
it('enables the buttons after we edit the form', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let buttons = element.all(by.css('hero-detail > form > div > button'));
expect(buttons.get(0).getAttribute('disabled')).toBeNull();
expect(buttons.get(1).getAttribute('disabled')).toBeNull();
});
it('saves the changes when the save button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let save = element.all(by.css('hero-detail > form > div > button')).get(0);
save.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Magnetaa');
});
it('reverts the changes when the revert button is clicked', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
nameInput.sendKeys('a');
let revert = element.all(by.css('hero-detail > form > div > button')).get(1);
revert.click();
let editMessage = element(by.css('hero-list > div > h3'));
expect(editMessage.getText()).toBe('Editing: Magneta');
expect(nameInput.getAttribute('value')).toBe('Magneta');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(3);
newLairButton.click();
let address = finalDemoAddressForm(element, 0);
expect(address.street).toBe('');
expect(address.state).toBe('');
expect(address.zip).toBe('');
expect(address.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
});
}); // final demo
// *************Begin FormArray Demo test*******************************
describe('formArray demo', function() {
beforeEach(function() {
let FormArrayOption = element.all(by.css('select option')).get(7);
FormArrayOption.click();
});
it('should show FormArray Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('FormArray Demo');
});
});
it('does not select any hero by default', function() {
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
it('refreshes the page upon button click', function() {
// We move to another page...
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
let refresh = element(by.css('button'));
refresh.click();
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
describe('Whirlwind form', function() {
beforeEach(function() {
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
});
it('should show hero information when the button is clicked', function() {
let editMessage = element(by.css('div.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwind');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Whirlwind');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('123 Main');
expect(address1.state).toBe('CA');
expect(address1.zip).toBe('94801');
expect(address1.city).toBe('Anywhere');
let address2 = finalDemoAddressForm(element, 1);
expect(address2.street).toBe('456 Maple');
expect(address2.state).toBe('VA');
expect(address2.zip).toBe('23226');
expect(address2.city).toBe('Somewhere');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-8 > p'));
expect(json.getText()).toContain('Whirlwind');
expect(json.getText()).toContain('Anywhere');
expect(json.getText()).toContain('Somewhere');
expect(json.getText()).toContain('VA');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(1);
newLairButton.click();
let address2 = finalDemoAddressForm(element, 2);
expect(address2.street).toBe('');
expect(address2.state).toBe('');
expect(address2.zip).toBe('');
expect(address2.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
}); // Whirlwind form
describe('Bombastic FormArray form', function() {
beforeEach(function() {
let bombasticButton = element.all(by.css('nav a')).get(1);
bombasticButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('div.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Bombastic');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
// nameInput.getAttribute('value').then(function(name: string) {
// expect(name).toBe('Whirlwind');
// });
expect(nameInput.getAttribute('value')).toBe('Bombastic');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('789 Elm');
// expect(address1.state).toBe('OH');
// This select should be OH not CA, which it shows in the UI, the JSON shows OH.
expect(address1.zip).toBe('04501');
expect(address1.city).toBe('Smallville');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-8 > p'));
expect(json.getText()).toContain('Bombastic');
expect(json.getText()).toContain('Smallville');
expect(json.getText()).toContain('04501');
expect(json.getText()).toContain('789 Elm');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(1);
newLairButton.click();
let address1 = finalDemoAddressForm(element, 1);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
}); // Bombastic FormArray form
describe('Magneta FormArray form', function() {
beforeEach(function() {
let magnetaButton = element.all(by.css('nav a')).get(2);
magnetaButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('div.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Magneta');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Magneta');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-8 > p'));
expect(json.getText()).toContain('Magneta');
});
it('is able to add a new empty address', function() {
let newLairButton = element.all(by.css('button')).get(1);
newLairButton.click();
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
}); // Magneta FormArray form
}); // formArray demo
// *************Begin SetValue Demo test*******************************
describe('SetValue demo', function() {
beforeEach(function() {
let SetValueOption = element.all(by.css('select option')).get(6);
SetValueOption.click();
});
it('should show SetValue Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('SetValue Demo');
});
});
it('does not select any hero by default', function() {
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
it('refreshes the page upon button click', function() {
// We move to another page...
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
let refresh = element(by.css('button'));
refresh.click();
let heroSection = element(by.css('hero-list > div'));
expect(heroSection.isPresent()).toBe(false);
});
describe('Whirlwind setValue form', function() {
beforeEach(function() {
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwind');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Whirlwind');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('123 Main');
expect(address1.state).toBe('CA');
expect(address1.zip).toBe('94801');
expect(address1.city).toBe('Anywhere');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-7 > p'));
expect(json.getText()).toContain('Whirlwind');
expect(json.getText()).toContain('Anywhere');
let nameOutput = element(by.css('hero-detail-7 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Whirlwind');
let streetOutput = element(by.css('hero-detail-7 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value: 123 Main');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
}); // Whirlwind setValue form
describe('Bombastic setValue form', function() {
beforeEach(function() {
let bombasticButton = element.all(by.css('nav a')).get(1);
bombasticButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Bombastic');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Bombastic');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('789 Elm');
expect(address1.state).toBe('OH');
expect(address1.zip).toBe('04501');
expect(address1.city).toBe('Smallville');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-7 > p'));
expect(json.getText()).toContain('Bombastic');
expect(json.getText()).toContain('Smallville');
expect(json.getText()).toContain('04501');
expect(json.getText()).toContain('789 Elm');
let nameOutput = element(by.css('hero-detail-7 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Bombastic');
let streetOutput = element(by.css('hero-detail-7 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value: 789 Elm');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
}); // Bombastic setValue form
describe('Magneta setValue form', function() {
beforeEach(function() {
let magnetaButton = element.all(by.css('nav a')).get(2);
magnetaButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('.demo > div > div > h3'));
expect(editMessage.getText()).toBe('Editing: Magneta');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Magneta');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-7 > p'));
expect(json.getText()).toContain('Magneta');
let nameOutput = element(by.css('hero-detail-7 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Magneta');
let streetOutput = element(by.css('hero-detail-7 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value:');
});
}); // Magneta setValue form
}); // SetValue demo
// *************Begin patchValue Demo test*******************************
describe('patchValue demo', function() {
beforeEach(function() {
let SetValueOption = element.all(by.css('select option')).get(5);
SetValueOption.click();
});
it('should show patchValue Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('PatchValue Demo');
});
});
it('does not select any hero by default', function() {
let heroSection = element(by.css('.demo > div > div'));
expect(heroSection.isPresent()).toBe(false);
});
it('refreshes the page upon button click', function() {
// We move to another page...
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
let refresh = element(by.css('button'));
refresh.click();
let heroSection = element(by.css('.demo > div > div'));
expect(heroSection.isPresent()).toBe(false);
});
describe('Whirlwind patchValue form', function() {
beforeEach(function() {
let whirlwindButton = element.all(by.css('nav a')).get(0);
whirlwindButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('h2 ~ h3'));
expect(editMessage.getText()).toBe('Editing: Whirlwind');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Whirlwind');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-6 > p'));
expect(json.getText()).toContain('Whirlwind');
let nameOutput = element(by.css('hero-detail-6 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Whirlwind');
let streetOutput = element(by.css('hero-detail-6 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value:');
});
}); // Bombastic patchValue form
describe('Bombastic patchValue form', function() {
beforeEach(function() {
let bombasticButton = element.all(by.css('nav a')).get(1);
bombasticButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('h2 ~ h3'));
expect(editMessage.getText()).toBe('Editing: Bombastic');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Bombastic');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-6 > p'));
expect(json.getText()).toContain('Bombastic');
let nameOutput = element(by.css('hero-detail-6 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Bombastic');
let streetOutput = element(by.css('hero-detail-6 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value:');
});
}); // Bombastic patchValue form
describe('Magneta patchValue form', function() {
beforeEach(function() {
let magnetaButton = element.all(by.css('nav a')).get(2);
magnetaButton.click();
});
it('should show a hero information when the button is clicked', function() {
let editMessage = element(by.css('h2 ~ h3'));
expect(editMessage.getText()).toBe('Editing: Magneta');
});
it('should show a form with the selected hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('Magneta');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-6 > p'));
expect(json.getText()).toContain('Magneta');
let nameOutput = element(by.css('hero-detail-6 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value: Magneta');
let streetOutput = element(by.css('hero-detail-6 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value:');
});
}); // Magneta patchValue form
}); // PatchValue demo
// *************Begin Nested FormBuilder Demo test*******************************
describe('Nested FormBuilder demo', function() {
beforeEach(function() {
let NestedFormBuilderOption = element.all(by.css('select option')).get(4);
NestedFormBuilderOption.click();
});
it('should show Nested FormBuilder Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('Nested FormBuilder group Demo');
});
});
it('should show a form for hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-5 > p'));
expect(json.getText()).toContain('address');
let nameOutput = element(by.css('hero-detail-5 > p ~ p'));
expect(nameOutput.getText()).toContain('Name value:');
let streetOutput = element(by.css('hero-detail-5 > p ~ p ~ p'));
expect(streetOutput.getText()).toContain('Street value:');
});
}); // Nested FormBuilder demo
// *************Begin Group with multiple controls Demo test*******************************
describe('Group with multiple controls demo', function() {
beforeEach(function() {
let NestedFormBuilderOption = element.all(by.css('select option')).get(3);
NestedFormBuilderOption.click();
});
it('should show Group with multiple controls Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('Group with multiple controls Demo');
});
});
it('should show header', function() {
let header = element(by.css('hero-detail-4 > h3'));
expect(header.getText()).toBe('A FormGroup with multiple FormControls');
});
it('should show a form for hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('');
let address1 = finalDemoAddressForm(element, 0);
expect(address1.street).toBe('');
expect(address1.state).toBe('');
expect(address1.zip).toBe('');
expect(address1.city).toBe('');
});
it('should show three radio buttons', function() {
let radioButtons = element.all(by.css('input[formcontrolname=power]'));
expect(radioButtons.get(0).getAttribute('value')).toBe('flight');
expect(radioButtons.get(1).getAttribute('value')).toBe('x-ray vision');
expect(radioButtons.get(2).getAttribute('value')).toBe('strength');
});
it('should show a checkbox', function() {
let checkbox = element(by.css('input[formcontrolname=sidekick]'));
expect(checkbox.getAttribute('checked')).toBe(null);
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-4 > p'));
expect(json.getText()).toContain('power');
});
}); // Group with multiple controls demo
// *************Begin Group with multiple controls Demo test*******************************
describe('Simple FormBuilder Group demo', function() {
beforeEach(function() {
let SimpleFormBuilderOption = element.all(by.css('select option')).get(2);
SimpleFormBuilderOption.click();
});
it('should show Simple FormBuilder group Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('Simple FormBuilder group Demo');
});
});
it('should show header', function() {
let header = element(by.css('hero-detail-3 > h3'));
expect(header.getText()).toBe('A FormGroup with a single FormControl using FormBuilder');
});
it('should show a form for hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-3 > p'));
expect(json.getText()).toContain('name');
let validStatus = element(by.css('hero-detail-3 > p ~ p'));
expect(validStatus.getText()).toContain('INVALID');
});
}); // Group with multiple controls demo
// *************Begin FormControl in a FormGroup Demo test*******************************
describe('FormControl in a FormGroup demo', function() {
beforeEach(function() {
let SimpleFormBuilderOption = element.all(by.css('select option')).get(1);
SimpleFormBuilderOption.click();
});
it('should show FormControl in a FormGroup Demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('FormControl in a FormGroup Demo');
});
});
it('should show header', function() {
let header = element(by.css('hero-detail-2 > h3'));
expect(header.getText()).toBe('FormControl in a FormGroup');
});
it('should show a form for hero information', function() {
let nameInput = element(by.css('input[formcontrolname=name]'));
expect(nameInput.getAttribute('value')).toBe('');
});
it('shows a json output from the form', function() {
let json = element(by.css('hero-detail-2 > p'));
expect(json.getText()).toContain('name');
});
}); // Group with multiple controls demo
// *************Begin Just A FormControl Demo test*******************************
describe('Just a FormControl demo', function() {
beforeEach(function() {
let FormControlOption = element.all(by.css('select option')).get(0);
FormControlOption.click();
});
it('should show Just a FormControl demo', function() {
select.getAttribute('value').then(function(demo: string) {
expect(demo).toBe('Just a FormControl Demo');
});
});
it('should show header', function() {
let header = element(by.css('hero-detail-1 > h3'));
expect(header.getText()).toBe('Just a FormControl');
});
it('should show a form for hero information', function() {
let nameInput = element(by.css('input'));
expect(nameInput.getAttribute('value')).toBe('');
});
}); // Just a FormControl demo test
}); // reactive forms | the_stack |
import { JsonTypeInfoAs, JsonTypeInfoId, JsonIncludeType, JsonFormatShape, JsonPropertyAccess, ObjectIdGenerator, JsonFilterType, PropertyNamingStrategy, JsonCreatorMode, JsonSetterNulls } from '../decorators';
import { DeserializationFeature, SerializationFeature } from '../databind';
/**
* https://stackoverflow.com/a/55032655/4637638
*/
export declare type Modify<T, R> = Omit<T, keyof R> & R;
/**
* Helper type that represents a general JavaScript type.
*/
export declare type ClassType<T> = (new () => T) | (new (...args: any[]) => T) | ((...args: any[]) => T) | ((...args: any[]) => ((cls: any) => T));
export declare type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift';
export declare type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> = Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>> & {
[I: number]: T;
readonly length: L;
[Symbol.iterator]: () => IterableIterator<T>;
};
/**
* Helper interface used to declare a List of ClassType recursively.
*/
export interface ClassList<T> extends Array<any> {
[index: number]: T | ClassList<T>;
0: T;
}
/**
* Decorator type with at least one required option.
*/
export declare type JacksonDecoratorWithOptions<T extends JsonDecoratorOptions, TDecorator> = (options: T) => TDecorator;
/**
* Decorator type with optional options.
*/
export declare type JacksonDecoratorWithOptionalOptions<T extends JsonDecoratorOptions, TDecorator> = (options?: T) => TDecorator;
/**
* Decorator type.
*/
export declare type JacksonDecorator<T extends JsonDecoratorOptions, TDecorator> = JacksonDecoratorWithOptions<T, TDecorator> | JacksonDecoratorWithOptionalOptions<T, TDecorator>;
/**
* Decorator type for {@link JsonAlias}.
*/
export declare type JsonAliasDecorator = JacksonDecoratorWithOptions<JsonAliasOptions, PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonAppend}.
*/
export declare type JsonAppendDecorator = JacksonDecoratorWithOptions<JsonAppendOptions, ClassDecorator>;
/**
* Decorator type for {@link JsonClassType}.
*/
export declare type JsonClassTypeDecorator = JacksonDecoratorWithOptions<JsonClassTypeOptions, PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonDeserialize}.
*/
export declare type JsonDeserializeDecorator = JacksonDecoratorWithOptions<JsonDeserializeOptions, ClassDecorator & PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonFilter}.
*/
export declare type JsonFilterDecorator = JacksonDecoratorWithOptions<JsonFilterOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonIdentityInfo}.
*/
export declare type JsonIdentityInfoDecorator = JacksonDecoratorWithOptions<JsonIdentityInfoOptions, ClassDecorator & PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonIdentityReference}.
*/
export declare type JsonIdentityReferenceDecorator = JacksonDecoratorWithOptions<JsonIdentityReferenceOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonNaming}.
*/
export declare type JsonNamingDecorator = JacksonDecoratorWithOptions<JsonNamingOptions, ClassDecorator>;
/**
* Decorator type for {@link JsonSerialize}.
*/
export declare type JsonSerializeDecorator = JacksonDecoratorWithOptions<JsonSerializeOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonSubTypes}.
*/
export declare type JsonSubTypesDecorator = JacksonDecoratorWithOptions<JsonSubTypesOptions, ClassDecorator & MethodDecorator & PropertyDecorator & ParameterDecorator>;
/**
* Decorator type for {@link JsonTypeInfo}.
*/
export declare type JsonTypeInfoDecorator = JacksonDecoratorWithOptions<JsonTypeInfoOptions, ClassDecorator & MethodDecorator & PropertyDecorator & ParameterDecorator>;
/**
* Decorator type for {@link JsonIgnoreProperties}.
*/
export declare type JsonIgnorePropertiesDecorator = JacksonDecoratorWithOptions<JsonIgnorePropertiesOptions, ClassDecorator & PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonPropertyOrder}.
*/
export declare type JsonPropertyOrderDecorator = JacksonDecoratorWithOptions<JsonPropertyOrderOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonTypeIdResolver}.
*/
export declare type JsonTypeIdResolverDecorator = JacksonDecoratorWithOptions<JsonTypeIdResolverOptions, ClassDecorator & MethodDecorator & PropertyDecorator & ParameterDecorator>;
/**
* Decorator type for {@link JsonView}.
*/
export declare type JsonViewDecorator = JacksonDecoratorWithOptions<JsonViewOptions, ClassDecorator & MethodDecorator & PropertyDecorator & ParameterDecorator>;
/**
* Decorator type for {@link JsonAnyGetter}.
*/
export declare type JsonAnyGetterDecorator = JacksonDecoratorWithOptionalOptions<JsonAnyGetterOptions, MethodDecorator>;
/**
* Decorator type for {@link JsonAnySetter}.
*/
export declare type JsonAnySetterDecorator = JacksonDecoratorWithOptionalOptions<JsonAnySetterOptions, MethodDecorator>;
/**
* Decorator type for {@link JsonBackReference}.
*/
export declare type JsonBackReferenceDecorator = JacksonDecoratorWithOptionalOptions<JsonBackReferenceOptions, PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonCreator}.
*/
export declare type JsonCreatorDecorator = JacksonDecoratorWithOptionalOptions<JsonCreatorOptions, ClassDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonFormat}.
*/
export declare type JsonFormatDecorator = JacksonDecoratorWithOptionalOptions<JsonFormatOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonGetter}.
*/
export declare type JsonGetterDecorator = JacksonDecoratorWithOptionalOptions<JsonGetterOptions, MethodDecorator & PropertyDecorator>;
/**
* Decorator type for {@link JsonSetter}.
*/
export declare type JsonSetterDecorator = JacksonDecoratorWithOptionalOptions<JsonSetterOptions, MethodDecorator & PropertyDecorator>;
/**
* Decorator type for {@link JsonIgnore}.
*/
export declare type JsonIgnoreDecorator = JacksonDecoratorWithOptionalOptions<JsonIgnoreOptions, PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonIgnoreType}.
*/
export declare type JsonIgnoreTypeDecorator = JacksonDecoratorWithOptionalOptions<JsonIgnoreTypeOptions, ClassDecorator>;
/**
* Decorator type for {@link JsonInclude}.
*/
export declare type JsonIncludeDecorator = JacksonDecoratorWithOptionalOptions<JsonIncludeOptions, ClassDecorator & PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonInject}.
*/
export declare type JsonInjectDecorator = JacksonDecoratorWithOptionalOptions<JsonInjectOptions, PropertyDecorator & ParameterDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonManagedReference}.
*/
export declare type JsonManagedReferenceDecorator = JacksonDecoratorWithOptionalOptions<JsonManagedReferenceOptions, PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonProperty}.
*/
export declare type JsonPropertyDecorator = JacksonDecoratorWithOptionalOptions<JsonPropertyOptions, PropertyDecorator & MethodDecorator & ParameterDecorator>;
/**
* Decorator type for {@link JsonRawValue}.
*/
export declare type JsonRawValueDecorator = JacksonDecoratorWithOptionalOptions<JsonRawValueOptions, PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonRootName}.
*/
export declare type JsonRootNameDecorator = JacksonDecoratorWithOptionalOptions<JsonRootNameOptions, ClassDecorator>;
/**
* Decorator type for {@link JsonTypeName}.
*/
export declare type JsonTypeNameDecorator = JacksonDecoratorWithOptionalOptions<JsonTypeNameOptions, ClassDecorator>;
/**
* Decorator type for {@link JsonUnwrapped}.
*/
export declare type JsonUnwrappedDecorator = JacksonDecoratorWithOptionalOptions<JsonUnwrappedOptions, PropertyDecorator & MethodDecorator>;
/**
* Decorator type for {@link JsonValue}.
*/
export declare type JsonValueDecorator = JacksonDecoratorWithOptionalOptions<JsonValueOptions, MethodDecorator & PropertyDecorator>;
/**
* Decorator type for {@link JsonTypeId}.
*/
export declare type JsonTypeIdDecorator = JacksonDecoratorWithOptionalOptions<JsonTypeIdOptions, PropertyDecorator & MethodDecorator>;
/**
* Common context properties used during serialization and deserialization.
*/
export interface JsonStringifierParserCommonContext<T> {
/**
* List of views (see {@link JsonView}) used to serialize/deserialize JSON objects.
*/
withViews?: () => ClassType<any>[];
/**
* List of context groups used to serialize/deserialize JSON objects.
*/
withContextGroups?: string[];
/**
* Property that defines features to set for {@link ObjectMapper}, {@link JsonStringifier} and {@link JsonParser}.
*/
features?: {};
/**
* Property whose keys are the decorators name that will be enabled/disabled during serialization/deserialization.
*/
decoratorsEnabled?: {
[key: string]: boolean;
};
/**
* Property whose keys are JavaScript Classes and its values are contexts to be used only for that JavaScript Classes.
*
* More specific contexts can be nested one inside the other. In this way, specific contexts can be applied to a
* JavaScript Class only if the nested JavaScript Class is found as one of the values of the parent JavaScript Class properties.
*/
forType?: Map<ClassType<any>, T>;
}
/**
* Filter options used during serialization.
*/
export interface JsonStringifierFilterOptions {
/**
* Type used to determine whether to serialize property as is, or to filter it out.
*/
type: JsonFilterType;
/**
* The list of the properties that are affected by the filter type.
*/
values?: string[];
}
/**
* Context properties used during serialization without {@link JsonStringifierContext.mainCreator}.
*/
export interface JsonStringifierForTypeContext extends JsonStringifierParserCommonContext<JsonStringifierForTypeContext> {
/**
* An Object Literal containing attributes values to be assigned during serialization for {@link JsonAppend} attributes.
*/
attributes?: {
[key: string]: any;
};
/**
* Property that defines features to set for {@link ObjectMapper} and {@link JsonStringifier}.
*/
features?: {
/**
* Property that defines features to set for {@link ObjectMapper} and {@link JsonStringifier}.
*/
serialization: SerializationFeature;
};
/**
* An Object Literal containing filter options used by {@link JsonFilter} during serialization.
* Object keys are simple string that refers to the name of the corresponding {@link JsonFilterOptions.value}.
*/
filters?: {
[key: string]: JsonStringifierFilterOptions;
};
/**
* A `String` or `Number` object that's used to insert white space into the output JSON string for readability purposes.
*
* If this is a Number, it indicates the number of space characters to use as white space;
* this number is capped at 10 (if it is greater, the value is just 10).
* Values less than 1 indicate that no space should be used.
*
* If this is a String, the string (or the first 10 characters of the string, if it's longer than that)
* is used as white space. If this parameter is not provided (or is null), no white space is used.
*/
format?: string | number;
/**
* Array of custom user-defined serializers.
*/
serializers?: CustomMapper<Serializer>[];
/**
* To be able to use {@link JsonFormat} on class properties of type `Date`
* with {@link JsonFormatShape.STRING}, a date library needs to be set.
* Date libraries supported: {@link https://github.com/moment/moment}, {@link https://github.com/iamkun/dayjs/}.
*/
dateLibrary?: any;
/**
* To be able to use {@link JsonIdentityInfo} with any UUID {@link ObjectIdGenerator}, an UUID library needs to be set.
* UUID libraries supported: {@link https://github.com/uuidjs/uuid}.
*/
uuidLibrary?: any;
}
/**
* Context properties used by {@link JsonStringifier.stringify} during serialization.
*/
export interface JsonStringifierContext extends JsonStringifierForTypeContext {
/**
* Function that returns a list of JavaScript Classes.
*
* @returns ClassList<ClassType<any>>
*/
mainCreator?: () => ClassList<ClassType<any>>;
}
/**
* Context properties used by {@link JsonStringifier.transform} during serialization.
*/
export declare type JsonStringifierTransformerContext = Modify<JsonStringifierContext, {
/**
* List of the current JavaScript Class that is being serialized.
* So, `mainCreator[0]` will return the current JavaScript Class.
*/
mainCreator?: ClassList<ClassType<any>>;
}>;
/**
* Context properties used during deserialization without {@link JsonParserContext.mainCreator}.
*/
export interface JsonParserForTypeContext extends JsonStringifierParserCommonContext<JsonParserForTypeContext> {
/**
* Property that defines features to set for {@link ObjectMapper} and {@link JsonParser}.
*/
features?: {
/**
* Property that defines features to set for {@link ObjectMapper} and {@link JsonParser}.
*/
deserialization: DeserializationFeature;
};
/**
* Define which {@link JsonCreator} should be used during deserialization through its name.
*/
withCreatorName?: string;
/**
* Array of custom user-defined deserializers.
*/
deserializers?: CustomMapper<Deserializer>[];
/**
* An Object Literal that stores the values to inject during deserialization, identified by simple String keys.
*/
injectableValues?: {
[key: string]: any;
};
}
/**
* Context properties used by {@link JsonParser.parse} during deserialization.
*/
export interface JsonParserContext extends JsonParserForTypeContext {
/**
* Function that returns a list of JavaScript Classes.
*
* @returns ClassList<ClassType<any>>
*/
mainCreator?: () => ClassList<ClassType<any>>;
}
/**
* Context properties used by {@link JsonParser.transform} during deserialization.
*/
export declare type JsonParserTransformerContext = Modify<JsonParserContext, {
/**
* List of the current JavaScript Class that is being deserialized.
* So, `mainCreator[0]` will return the current JavaScript Class.
*/
mainCreator?: ClassList<ClassType<any>>;
}>;
/**
* Serializer type.
*/
export declare type Serializer = (key: string, value: any, context?: JsonStringifierTransformerContext) => any;
/**
* Deserializer type.
*/
export declare type Deserializer = (key: string, value: any, context?: JsonParserTransformerContext) => any;
/**
* Interface that represents a serializer/deserializer used by {@link ObjectMapper}.
*/
export interface CustomMapper<T> {
/**
* The serializer/deserializer.
*/
mapper: T;
/**
* A JavaScript type, that could be:
* - a class;
* - a string such as "string" or "number" as if you were using the "typeof" operator.
*/
type?: () => any;
/**
* The order in which the serializer/deserializer should be executed.
* `0` has the highest precedence.
*/
order?: number;
}
/**
* Basic decorator options.
*/
export interface JsonDecoratorOptions {
/**
* Property that defines whether this decorator is active or not.
*
* @default `true`
*/
enabled?: boolean;
/**
* Property that defines whether this decorator is part of a context group
* or multiple groups.
*/
contextGroups?: string[];
}
/**
* General decorator type.
*/
export declare type JsonDecorator = <T>(
/**
* Decorator options.
*/
options: JsonDecoratorOptions, target: Record<string, any>, propertyKey: string | symbol, descriptorOrParamIndex: number | TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
/**
* Decorator options for {@link JsonAnyGetter}.
*/
export interface JsonAnyGetterOptions extends JsonDecoratorOptions {
/**
* Specify the name of the class property that contains the set of key/value pairs
* that should be added along with regular property values tha class has.
*/
value?: string;
}
/**
* Decorator options for {@link JsonAnySetter}.
*/
export declare type JsonAnySetterOptions = JsonDecoratorOptions;
/**
* Decorator options for {@link JsonBackReference}.
*/
export interface JsonBackReferenceOptions extends JsonDecoratorOptions {
/**
* Logical name for the reference property pair; used to link managed and back references.
* Default name can be used if there is just single reference pair
* (for example, node class that just has parent/child linkage, consisting of one managed reference and matching back reference).
*
* @default `'defaultReference'`
*/
value?: string;
}
/**
* Decorator options for {@link JsonCreator}.
*/
export interface JsonCreatorOptions extends JsonDecoratorOptions {
/**
* Creator name.
*/
name?: string;
/**
* Property that is used to indicate how argument(s) is/are bound for creator.
*
* @default {@link JsonCreatorMode.PROPERTIES}
*/
mode?: JsonCreatorMode;
}
/**
* Decorator options for {@link JsonDeserialize}.
*/
export interface JsonDeserializeOptions extends JsonDecoratorOptions {
/**
* Deserializer function to use for deserializing associated value.
*
* @param obj
* @param context
*/
using?: (obj: any, context?: JsonParserTransformerContext) => any;
/**
* Deserializer function to use for deserializing contents
* (elements of a Iterables and values of Maps) of decorated property.
*
* @param obj
* @param context
*/
contentUsing?: (obj: any, context?: JsonParserTransformerContext) => any;
/**
* Deserializer function to use for deserializing `Map` of `Object Literal`
* keys of decorated property.
*
* @param key
* @param context
*/
keyUsing?: (key: any, context?: JsonParserTransformerContext) => any;
}
/**
* Decorator base options for {@link JsonFormat}.
*/
export interface JsonFormatBaseOptions extends JsonDecoratorOptions {
/**
* Shape to be used by {@link JsonFormat}.
*/
shape?: JsonFormatShape;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.ANY}.
*/
export interface JsonFormatAny extends JsonFormatBaseOptions {
shape: JsonFormatShape.ANY;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.ARRAY}.
*/
export interface JsonFormatArray extends JsonFormatBaseOptions {
/**
* Value that indicates that (JSON) Array type should be used.
*/
shape: JsonFormatShape.ARRAY;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.BOOLEAN}.
*/
export interface JsonFormatBoolean extends JsonFormatBaseOptions {
/**
* Value that indicates that (JSON) boolean type (true, false) should be used.
*/
shape: JsonFormatShape.BOOLEAN;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.NUMBER_FLOAT}.
*/
export interface JsonFormatNumberFloat extends JsonFormatBaseOptions {
/**
* Value that indicates that floating-point numeric type should be used.
*/
shape: JsonFormatShape.NUMBER_FLOAT;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.NUMBER_INT}.
*/
export interface JsonFormatNumberInt extends JsonFormatBaseOptions {
/**
* Value that indicates that integer number type should be used.
*/
shape: JsonFormatShape.NUMBER_INT;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.OBJECT}.
*/
export interface JsonFormatObject extends JsonFormatBaseOptions {
/**
* Value that indicates that (JSON) Object type should be used.
*/
shape: JsonFormatShape.OBJECT;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.SCALAR}.
*/
export interface JsonFormatScalar extends JsonFormatBaseOptions {
/**
* Value that indicates shape should not be structural.
*/
shape: JsonFormatShape.SCALAR;
}
/**
* Decorator specific options for {@link JsonFormat} with {@link JsonFormatBaseOptions.shape} value {@link JsonFormatShape.STRING}.
*
* **IMPORTANT NOTE**: When formatting a `Date`, a date library needs to be set using the {@link dateLibrary} option.
* Date libraries supported: {@link https://github.com/moment/moment}, {@link https://github.com/iamkun/dayjs/}.
*/
export interface JsonFormatString extends JsonFormatBaseOptions {
/**
* Value that indicates that (JSON) String type should be used.
*/
shape: JsonFormatShape.STRING;
/**
* Pattern to be used to format a `Date` during serialization.
*/
pattern?: string;
/**
* Locale to be used to format a `Date` during serialization.
*
* @default `'en'`
*/
locale?: string;
/**
* Timezone to be used to format a `Date` during serialization.
*/
timezone?: string;
/**
* To be able to use {@link JsonFormat} on class properties of type `Date`
* with {@link JsonFormatShape.STRING}, a date library needs to be set.
* Date libraries supported: {@link https://github.com/moment/moment}, {@link https://github.com/iamkun/dayjs/}.
*/
dateLibrary?: any;
/**
* Radix to be used to format an integer `Number` during serialization and using `parseInt()`.
*/
radix?: number;
/**
* An integer specifying the number of digits after the decimal point
* to be used to format an integer `Number` during serialization and using `toExponential()`.
*/
toExponential?: number;
/**
* The number of digits to appear after the decimal point to be used to format a `Number`
* during serialization and using `toFixed()`.
*/
toFixed?: number;
/**
* An integer specifying the number of significant digits to be used to format a `Number`
* during serialization and using `toPrecision()`.
*/
toPrecision?: number;
}
/**
* Decorator options for {@link JsonFormat}.
*
* @default {@link JsonFormatAny}
*/
export declare type JsonFormatOptions = JsonFormatAny | JsonFormatArray | JsonFormatBoolean | JsonFormatNumberFloat | JsonFormatNumberInt | JsonFormatObject | JsonFormatScalar | JsonFormatString;
/**
* Decorator options for {@link JsonIgnore}.
*/
export declare type JsonIgnoreOptions = JsonDecoratorOptions;
/**
* Decorator options for {@link JsonIgnoreProperties}.
*/
export interface JsonIgnorePropertiesOptions extends JsonDecoratorOptions {
/**
* Names of properties to ignore.
*/
value?: string[];
/**
* Property that can be enabled to allow "getters" to be used
* (that is, prevent ignoral of getters for properties listed in {@link value}).
*
* @default `false`
*/
allowGetters?: boolean;
/**
* Property that can be enabled to allow "setters" to be used
* (that is, prevent ignoral of setters for properties listed in {@link value}).
*
* @default `false`
*/
allowSetters?: boolean;
/**
* Property that defines whether it is ok to just ignore
* any unrecognized properties during deserialization.
*
* @default `false`
*/
ignoreUnknown?: boolean;
}
/**
* Decorator options for {@link JsonIgnoreType}.
*/
export declare type JsonIgnoreTypeOptions = JsonDecoratorOptions;
/**
* Decorator base options for {@link JsonInclude}.
*/
export interface JsonIncludeBaseOptions {
/**
* Inclusion rule to use for instances (values) of types (Classes) or properties decorated.
*
* @default {@link JsonIncludeType.ALWAYS}
*/
value?: JsonIncludeType;
/**
* Specifies a function to use in case {@link value} is {@link JsonIncludeType.CUSTOM} for filtering the value.
* If it returns `true`, then the value is not serialized.
*
* @param value - value to be filtered.
* @returns boolean
*/
valueFilter?: (value: any) => boolean;
/**
* Inclusion rule to use for entries ("content") of decorated `Map` or "Object Literal" properties.
*
* @default {@link JsonIncludeType.ALWAYS}
*/
content?: JsonIncludeType;
/**
* Specifies a function to use in case {@link content} is {@link JsonIncludeType.CUSTOM} for filtering the content value.
* If it returns `true`, then the content value is not serialized.
*
* @param value - content value to be filtered.
* @returns boolean
*/
contentFilter?: (value: any) => boolean;
}
/**
* Decorator options for {@link JsonInclude}.
*/
export declare type JsonIncludeOptions = JsonIncludeBaseOptions & JsonDecoratorOptions;
/**
* Decorator options for {@link JsonManagedReference}.
*/
export interface JsonManagedReferenceOptions extends JsonDecoratorOptions {
/**
* Logical name for the reference property pair; used to link managed and back references.
* Default name can be used if there is just single reference pair
* (for example, node class that just has parent/child linkage, consisting of one managed reference and matching back reference).
*
* @default `'defaultReference'`
*/
value?: string;
}
/**
* Decorator options for {@link JsonProperty}.
*/
export interface JsonPropertyOptions extends JsonDecoratorOptions {
/**
* Defines name of the logical property.
*/
value?: any;
/**
* Property that may be used to change the way visibility of accessors (getter, field-as-getter)
* and mutators (constructor parameter, setter, field-as-setter) is determined.
*
* @default {@link JsonPropertyAccess.READ_WRITE}
*/
access?: JsonPropertyAccess;
/**
* Property that indicates whether a value (which may be explicit null)
* is expected for property during deserialization or not.
*
* @default `false`
*/
required?: boolean;
}
/**
* Decorator options for {@link JsonPropertyOrder}.
*/
export interface JsonPropertyOrderOptions extends JsonDecoratorOptions {
/**
* Property that defines what to do regarding ordering of properties not explicitly included in decorator instance.
* If set to true, they will be alphabetically ordered; if false, order is undefined (default setting).
*/
alphabetic?: boolean;
/**
* Order in which properties of decorated object are to be serialized in.
*/
value?: string[];
}
/**
* Decorator options for {@link JsonRawValue}.
*/
export declare type JsonRawValueOptions = JsonDecoratorOptions;
/**
* Decorator options for {@link JsonRootName}.
*/
export interface JsonRootNameOptions extends JsonDecoratorOptions {
/**
* Root name to use.
*/
value?: string;
}
/**
* Decorator options for {@link JsonSerialize}.
*/
export interface JsonSerializeOptions extends JsonDecoratorOptions {
/**
* Serializer function to use for serializing associated value.
*
* @param obj
* @param context
*/
using?: (obj: any, context?: JsonStringifierTransformerContext) => any;
/**
* Serializer function to use for serializing contents
* (elements of a Iterables and values of Maps) of decorated property.
*
* @param obj
* @param context
*/
contentUsing?: (obj: any, context?: JsonStringifierTransformerContext) => any;
/**
* Serializer function to use for serializing `Map` of `Object Literal`
* keys of decorated property.
*
* @param key
* @param context
*/
keyUsing?: (key: any, context?: JsonStringifierTransformerContext) => any;
/**
* Serializer function to use for serializing nulls for properties that are decorated.
*
* @param context
*/
nullsUsing?: (context?: JsonStringifierTransformerContext) => any;
}
/**
* Subtypes of the decorated type with {@link JsonSubTypes}.
*/
export interface JsonSubTypeOptions extends JsonDecoratorOptions {
/**
* A function that returns the JavaScript Class of the subtype.
*/
class: () => ClassType<any>;
/**
* Logical type name used as the type identifier for the class.
*/
name?: string;
}
/**
* Decorator options for {@link JsonSubTypes}.
*/
export interface JsonSubTypesOptions extends JsonDecoratorOptions {
/**
* Subtypes of the decorated type.
*/
types: JsonSubTypeOptions[];
}
/**
* Decorator options for {@link JsonTypeInfo}.
*/
export interface JsonTypeInfoOptions extends JsonDecoratorOptions {
/**
* Specifies kind of type metadata to use when serializing type information
* for instances of decorated type and its subtypes;
* as well as what is expected during deserialization.
*/
use: JsonTypeInfoId;
/**
* Specifies mechanism to use for including type metadata.
* Used when serializing, and expected when deserializing.
*/
include: JsonTypeInfoAs;
/**
* Property names used when type inclusion method {@link JsonTypeInfoAs.PROPERTY} is used.
*/
property?: string;
}
/**
* Decorator options for {@link JsonTypeName}.
*/
export interface JsonTypeNameOptions extends JsonDecoratorOptions {
/**
* Logical type name for decorated type.
* If missing (or defined as Empty String), defaults to using class name as the type.
*/
value?: string;
}
/**
* Decorator options for {@link JsonValue}.
*/
export declare type JsonValueOptions = JsonDecoratorOptions;
/**
* Decorator options for {@link JsonView}.
*/
export interface JsonViewOptions extends JsonDecoratorOptions {
/**
* A function that returns the view or a list of views that decorated element is part of.
*/
value: () => ClassType<any>[];
}
/**
* Decorator options for {@link JsonAlias}.
*/
export interface JsonAliasOptions extends JsonDecoratorOptions {
/**
* One or more secondary names to accept as aliases to the official name.
*/
values: string[];
}
/**
* Helper type used in {@link JsonClassType} to declare a ClassType and apply decorators to it.
*/
export declare type ClassTypeWithDecoratorDefinitions = () => ({
/**
* JavaScript type.
*/
target: ClassType<any>;
/**
* Property that contains the list of decorators to be applied.
*/
decorators: {
/**
* Name of the decorator.
*/
name: string;
/**
* Decorator options.
*/
options: JsonDecoratorOptions;
}[];
});
/**
* Decorator options for {@link JsonClassType}.
*/
export interface JsonClassTypeOptions extends JsonDecoratorOptions {
/**
* Function used to get the type of a class property or method parameter.
*/
type: () => ClassList<ClassType<any> | ClassTypeWithDecoratorDefinitions>;
}
/**
* Decorator options for {@link JsonUnwrapped}.
*/
export interface JsonUnwrappedOptions extends JsonDecoratorOptions {
/**
* Property that can be used to add prefix String to use in front of names of properties that are unwrapped:
* this can be done for example to prevent name collisions.
*/
prefix?: string;
/**
* Property that can be used to add suffix String to append at the end of names of properties that are unwrapped:
* this can be done for example to prevent name collisions.
*/
suffix?: string;
}
/**
* Options for version 5 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-5-namespace})
*/
export interface UUIDv5GeneratorOptions {
name?: string | Array<any>;
namespace?: string | FixedLengthArray<number, 16>;
buffer?: Array<any> | Buffer;
offset?: number;
}
/**
* Options for version 4 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-4-random})
*/
export interface UUIDv4GeneratorOptions {
options?: {
random?: FixedLengthArray<number, 16>;
rng?: () => FixedLengthArray<number, 16>;
};
buffer?: Array<any> | Buffer;
offset?: number;
}
/**
* Options for version 3 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-3-namespace})
*/
export interface UUIDv3GeneratorOptions {
name?: string | Array<any>;
namespace?: string | FixedLengthArray<number, 16>;
buffer?: Array<any> | Buffer;
offset?: number;
}
/**
* Options for version 1 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-1-timestamp})
*/
export interface UUIDv1GeneratorOptions {
options?: {
node?: FixedLengthArray<number, 6>;
clockseq?: number;
msecs?: number;
nsecs?: number;
random?: FixedLengthArray<number, 16>;
rng?: () => FixedLengthArray<number, 16>;
};
buffer?: Array<any> | Buffer;
offset?: number;
}
/**
* Decorator options for {@link JsonIdentityInfo}.
*/
export interface JsonIdentityInfoOptions extends JsonDecoratorOptions {
/**
* Generator to use for producing Object Identifier for objects:
* either one of pre-defined generators from {@link ObjectIdGenerator}, or a custom generator.
*/
generator: ObjectIdGenerator | ((obj: any) => any);
/**
* Name of JSON property in which Object Id will reside.
*
* @default `'@id'`
*/
property?: string;
/**
* Scope is used to define applicability of an Object Id: all ids must be unique within their scope;
* where scope is defined as combination of this value and generator type.
*/
scope?: string;
/**
* Options for version 5 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-5-namespace})
*/
uuidv5?: UUIDv5GeneratorOptions;
/**
* Options for version 4 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-4-random})
*/
uuidv4?: UUIDv4GeneratorOptions;
/**
* Options for version 3 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-3-namespace})
*/
uuidv3?: UUIDv3GeneratorOptions;
/**
* Options for version 1 UUID Generator (see {@link https://github.com/uuidjs/uuid#version-1-timestamp})
*/
uuidv1?: UUIDv1GeneratorOptions;
/**
* To be able to use {@link JsonIdentityInfo} with any UUID {@link ObjectIdGenerator}, an UUID library needs to be set.
* UUID libraries supported: {@link https://github.com/uuidjs/uuid}.
*/
uuidLibrary?: any;
}
/**
* Decorator options for {@link JsonIdentityReference}.
*/
export interface JsonIdentityReferenceOptions extends JsonDecoratorOptions {
/**
* Marker to indicate whether all referenced values are to be serialized as ids (true);
* or by serializing the first encountered reference as Class and only then as id (false).
*/
alwaysAsId: boolean;
}
/**
* Decorator options for {@link JsonInject}.
*/
export interface JsonInjectOptions extends JsonDecoratorOptions {
/**
* Logical id of the value to inject; if not specified (or specified as empty String),
* will use id based on declared type of property.
*/
value?: string;
/**
* Whether matching value from input (if any) is used for decorated property or not; if disabled (`false`),
* input value (if any) will be ignored; otherwise it will override injected value.
*
* @default `true`
*/
useInput?: boolean;
}
/**
* Decorator options for {@link JsonFilter}.
*/
export interface JsonFilterOptions extends JsonDecoratorOptions {
/**
* Id of filter to use.
*/
value: string;
}
/**
* Definition of a single attribute-backed property.
* Attribute-backed properties will be appended after (or prepended before, as per JsonAppend.prepend())
* regular properties in specified order, although their placement may be further changed by the usual
* property-ordering (see {@link JsonPropertyOrder}) functionality (alphabetic sorting; explicit ordering).
*/
export interface JsonAppendOptionsAttribute {
/**
* Name of attribute of which value to serialize.
*/
value: string;
/**
* Name to use for serializing value of the attribute; if not defined, {@link value} will be used instead.
*/
propName?: string;
/**
* Property that indicates whether a value (which may be explicit null) is expected for property during serialization or not.
*/
required?: boolean;
/**
* When to include attribute-property.
*/
include?: JsonIncludeType;
}
/**
* Decorator options for {@link JsonAppend}.
*/
export interface JsonAppendOptions extends JsonDecoratorOptions {
/**
* Indicator used to determine whether properties defined are
* to be appended after (`false`) or prepended before (`true`) regular properties.
*
* @default `false`
*/
prepend?: boolean;
/**
* Set of attribute-backed properties to include when serializing.
*
* @default `[]`
*/
attrs?: JsonAppendOptionsAttribute[];
}
/**
* Decorator options for {@link JsonNaming}.
*/
export interface JsonNamingOptions extends JsonDecoratorOptions {
/**
* Strategies that defines how names of JSON properties ("external names")
* are derived from names of Class methods and fields ("internal names").
*/
strategy: PropertyNamingStrategy;
}
/**
* Decorator options for {@link JsonGetter}.
*/
export interface JsonGetterOptions extends JsonDecoratorOptions {
/**
* Defines name of the logical property this method is used to access.
*/
value?: string;
}
/**
* Decorator options for {@link JsonSetter}.
*/
export interface JsonSetterOptions extends JsonDecoratorOptions {
/**
* Property that defines logical property this method is used to modify ("set");
* this is the property name used in JSON content.
*/
value?: string;
/**
* Specifies action to take when input contains explicit `null` value.
*
* @default {@link JsonSetterNulls.SET}
*/
nulls?: JsonSetterNulls;
/**
* Specifies action to take when input to match into content value (of an Iterable, a `Map` or an Object Literal)
* contains explicit `null` value to bind.
*
* @default {@link JsonSetterNulls.SET}
*/
contentNulls?: JsonSetterNulls;
}
/**
* Decorator options for {@link JsonTypeId}.
*/
export declare type JsonTypeIdOptions = JsonDecoratorOptions;
/**
* Interface that defines standard API for converting types to type identifiers and vice versa.
* Used by type resolvers (see {@link JsonTypeIdResolver}) for converting between type and matching id;
* id is stored in JSON and needed for creating instances of proper subtypes when deserializing values.
*/
export interface TypeIdResolver {
/**
* Method called to serialize type of the type of given value as a String to include in serialized JSON content.
*
* @param obj
* @param context
* @returns string
*/
idFromValue: (obj: any, context?: JsonStringifierTransformerContext | JsonParserTransformerContext) => string;
/**
* Method called to resolve type from given type identifier.
*
* @param id
* @param context
* @returns ClassType<any>
*/
typeFromId: (id: string, context?: JsonStringifierTransformerContext | JsonParserTransformerContext) => ClassType<any>;
}
/**
* Decorator options for {@link JsonTypeIdResolver}.
*/
export interface JsonTypeIdResolverOptions extends JsonDecoratorOptions {
resolver: TypeIdResolver;
} | the_stack |
import {
create,
decode,
getNumericDate,
Header,
Payload,
validate,
verify,
} from "../mod.ts";
import {
assertEquals,
assertThrows,
assertThrowsAsync,
decodeHex,
} from "./test_deps.ts";
const header: Header = {
alg: "HS256",
typ: "JWT",
};
const payload: Payload = {
name: "John Doe",
};
const keyHS256 = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode("secret"),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"],
);
const keyHS384 = await crypto.subtle.generateKey(
{ name: "HMAC", hash: "SHA-384" },
true,
["sign", "verify"],
);
const keyHS512 = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode("secret"),
{ name: "HMAC", hash: "SHA-512" },
false,
["sign", "verify"],
);
const keyRS256 = await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["verify", "sign"],
);
const keyRS384 = await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-384",
},
true,
["verify", "sign"],
);
const keyRS512 = await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-512",
},
true,
["verify", "sign"],
);
const keyPS256 = await window.crypto.subtle.generateKey(
{
name: "RSA-PSS",
// Consider using a 4096-bit key for systems that require long-term security
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["sign", "verify"],
);
const keyPS384 = await window.crypto.subtle.generateKey(
{
name: "RSA-PSS",
// Consider using a 4096-bit key for systems that require long-term security
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-384",
},
true,
["sign", "verify"],
);
const keyPS512 = await window.crypto.subtle.generateKey(
{
name: "RSA-PSS",
// Consider using a 4096-bit key for systems that require long-term security
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-512",
},
true,
["sign", "verify"],
);
const keyES256 = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-256",
},
true,
["sign", "verify"],
);
const keyES384 = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-384",
},
true,
["sign", "verify"],
);
// Not supported yet:
// const keyES512 = await window.crypto.subtle.generateKey(
// {
// name: "ECDSA",
// namedCurve: "P-521",
// },
// true,
// ["sign", "verify"],
// );
Deno.test({
name: "[jwt] create",
fn: async function () {
assertEquals(
await create(
header,
payload,
keyHS256,
),
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds",
);
assertEquals(
await create(
{
alg: "HS512",
typ: "JWT",
},
{},
keyHS512,
),
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.e30.dGumW8J3t2BlAwqqoisyWDC6ov2hRtjTAFHzd-Tlr4DUScaHG4OYqTHXLHEzd3hU5wy5xs87vRov6QzZnj410g",
);
assertEquals(
await create({ alg: "HS512", typ: "JWT" }, { foo: "bar" }, keyHS512),
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.WePl7achkd0oGNB8XRF_LJwxlyiPZqpdNgdKpDboAjSTsWq-aOGNynTp8TOv8KjonFym8vwFwppXOLoLXbkIaQ",
);
await assertThrowsAsync(
async () => {
await create(header, payload, keyHS512);
},
Error,
"The jwt's alg 'HS256' does not match the key's algorithm.",
);
},
});
Deno.test({
name: "[jwt] verify",
fn: async function () {
assertEquals(
await verify(
await create(header, payload, keyHS256),
keyHS256,
),
payload,
);
await assertEquals(
await verify(
await create({ alg: "HS512", typ: "JWT" }, {}, keyHS512),
keyHS512,
),
{},
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsd",
keyHS256,
);
},
Error,
"The jwt's signature does not match the verification signature.",
);
await assertThrowsAsync(
async () => {
// payload = { "exp": false }
await verify(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOmZhbHNlfQ.LXb8M9J6ar14CTq7shnqDMWmSsoH_zyIHiD44Rqd6uI",
keyHS512,
);
},
Error,
"The jwt has an invalid 'exp' or 'nbf' claim.",
);
await assertThrowsAsync(
async () => {
await verify("", keyHS512);
},
Error,
"The serialization of the jwt is invalid.",
);
await assertThrowsAsync(
async () => {
await verify("invalid", keyHS512);
},
Error,
"The serialization of the jwt is invalid.",
);
await assertThrowsAsync(
async () => {
await verify(
await create(header, {
// @ts-ignore */
nbf: "invalid",
exp: 100000000000000000000,
}, keyHS256),
keyHS256,
);
},
Error,
"The jwt has an invalid 'exp' or 'nbf' claim",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..F6X5eXaBMszYO1kMrujBGGw4-FTJp2Uld6Daz9v3cu4",
keyHS256,
);
},
Error,
"The serialization of the jwt is invalid.",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.YWJj.uE63kRv-19VnJUBL4OUKaxULtqZ27cJwl8V9IXjJaHg",
keyHS256,
);
},
Error,
"The serialization of the jwt is invalid.",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.bnVsbA.tv7DbhvALc5Eq2sC61Y9IZlG2G15hvJoug9UO6iwmE_UZOLva8EC-9PURg7IIj6f-F9jFWix8vCn9WaAMHR1AA",
keyHS512,
);
},
Error,
"The jwt claims set is not a JSON object",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.dHJ1ZQ.Wmj2Jb9m6FQaZ0rd4AHNR2u9THED_m-aPfGx1w5mtKalrx7NWFS98ZblUNm_Szeugg9CUzhzBfPDyPUA2LTTkA",
keyHS512,
);
},
Error,
"The jwt claims set is not a JSON object",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.W10.BqmZ-tVI9a-HDx6PpMiBdMq6lzcaqO9sW6pImw-NRajCCmRrVi6IgMhEw7lvOG6sxhteceVMl8_xFRGverJJWw",
keyHS512,
);
},
Error,
"The jwt claims set is not a JSON object",
);
await assertThrowsAsync(
async () => {
await verify(
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.WyJhIiwxLHRydWVd.eVsshnlupuoVv9S5Q7VOj2BkLyZmOSC27fCoXwyq_MG8B95P2GkLDkL8Fo0Su7qoh1G0BxYjVRHgVppTgpuZRw",
keyHS512,
);
},
Error,
"The jwt claims set is not a JSON object",
);
},
});
Deno.test({
name: "[jwt] decode",
fn: async function () {
assertEquals(
decode(
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.TVCeFl1nnZWUMQkAQKuSo_I97YeIZAS8T1gOkErT7F8",
),
[
{ alg: "HS256", typ: "JWT" },
{},
decodeHex(new TextEncoder().encode(
"4d509e165d679d959431090040ab92a3f23ded87886404bc4f580e904ad3ec5f",
)),
],
);
assertThrows(
() => {
decode("aaa");
},
Error,
"The serialization of the jwt is invalid.",
);
assertThrows(
() => {
decode("a");
},
Error,
"The serialization of the jwt is invalid.",
);
assertThrows(
() => {
// "ImEi" === base64url("a")
decode("ImEi.ImEi.ImEi.ImEi");
},
Error,
"The serialization of the jwt is invalid.",
);
const jwt =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
const header: Header = {
alg: "HS256",
typ: "JWT",
};
const payload = {
sub: "1234567890",
name: "John Doe",
iat: 1516239022,
};
assertEquals(decode(jwt), [
header,
payload,
decodeHex(
new TextEncoder().encode(
"49f94ac7044948c78a285d904f87f0a4c7897f7e8f3a4eb2255fda750b2cc397",
),
),
]);
assertEquals(
await create(
header,
payload,
await crypto.subtle.importKey(
"raw",
new TextEncoder().encode("your-256-bit-secret"),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"],
),
),
jwt,
);
},
});
Deno.test({
name: "[jwt] validate",
fn: async function () {
assertEquals(
validate(
[
{ alg: "HS256", typ: "JWT" },
{ exp: 1111111111111111111111111111 },
new Uint8Array(),
],
),
{
header: { alg: "HS256", typ: "JWT" },
payload: { exp: 1111111111111111111111111111 },
signature: new Uint8Array(),
},
);
assertThrows(
() => {
validate([, , new Uint8Array()]);
},
Error,
"The jwt's alg header parameter value must be a string.",
);
assertThrows(
() => {
validate([null, {}, new Uint8Array()]);
},
Error,
"The jwt's alg header parameter value must be a string.",
);
assertThrows(
() => {
validate([{ alg: "HS256", typ: "JWT" }, [], new Uint8Array()]);
},
Error,
"The jwt claims set is not a JSON object.",
);
assertThrows(
() => {
validate([{ alg: "HS256" }, { exp: "" }, new Uint8Array()]);
},
Error,
"The jwt has an invalid 'exp' or 'nbf' claim.",
);
assertThrows(
() => {
validate([{ alg: "HS256" }, { exp: 1 }, new Uint8Array()]);
},
Error,
"The jwt is expired.",
);
assertThrows(
() => {
validate([
{ alg: "HS256" },
{ nbf: 1111111111111111111111111111 },
new Uint8Array(),
]);
},
Error,
"The jwt is used too early.",
);
const jwt =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
const header: Header = {
alg: "HS256",
typ: "JWT",
};
const payload = {
sub: "1234567890",
name: "John Doe",
iat: 1516239022,
};
assertEquals(decode(jwt), [
header,
payload,
decodeHex(
new TextEncoder().encode(
"49f94ac7044948c78a285d904f87f0a4c7897f7e8f3a4eb2255fda750b2cc397",
),
),
]);
assertEquals(
await create(
header,
payload,
await crypto.subtle.importKey(
"raw",
new TextEncoder().encode("your-256-bit-secret"),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign", "verify"],
),
),
jwt,
);
},
});
Deno.test({
name: "[jwt] expired jwt",
fn: async function () {
const payload = {
iss: "joe",
jti: "123456789abc",
exp: 20000,
};
const header: Header = {
alg: "HS256",
dummy: 100,
};
await assertThrowsAsync(
async () => {
await verify(
await create(
header,
{ exp: 0 },
keyHS256,
),
keyHS256,
);
},
Error,
"The jwt is expired.",
);
await assertThrowsAsync(
async () => {
await verify(
await create(header, payload, keyHS256),
keyHS256,
);
},
Error,
"The jwt is expired.",
);
},
});
Deno.test({
name: "[jwt] too early jwt",
fn: async function () {
const payload = {
iss: "joe",
jti: "123456789abc",
};
const header: Header = {
alg: "HS256",
};
const lateNbf = Date.now() / 1000 - 5;
const earlyNbf = Date.now() / 1000 + 5;
assertEquals(
await verify(
await create(header, { ...payload, nbf: lateNbf }, keyHS256),
keyHS256,
),
{ ...payload, nbf: lateNbf },
);
await assertThrowsAsync(
async () => {
await verify(
await create(header, { ...payload, nbf: earlyNbf }, keyHS256),
keyHS256,
);
},
Error,
"The jwt is used too early.",
);
},
});
Deno.test({
name: "[jwt] none algorithm",
fn: async function () {
const payload = {
iss: "joe",
"http://example.com/is_root": true,
};
const header: Header = {
alg: "none",
};
const jwt = await create(header, payload, null);
assertEquals(
jwt,
"eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0.",
);
const validatedPayload = await verify(
jwt,
null,
);
assertEquals(validatedPayload, payload);
await assertThrowsAsync(
async () => {
await create(header, payload, keyHS256);
},
Error,
"The alg 'none' does not allow a key.",
);
await assertThrowsAsync(
async () => {
await create({ alg: "HS256" }, payload, null);
},
Error,
"The alg 'HS256' demands a key.",
);
await assertThrowsAsync(
async () => {
await verify(await create(header, payload, null), keyHS256);
},
Error,
"The alg 'none' does not allow a key.",
);
await assertThrowsAsync(
async () => {
await verify(await create({ alg: "HS256" }, payload, keyHS256), null);
},
Error,
"The alg 'HS256' demands a key.",
);
},
});
Deno.test({
name: "[jwt] HS256 algorithm",
fn: async function () {
const header: Header = {
alg: "HS256",
typ: "JWT",
};
const payload = {
sub: "1234567890",
name: "John Doe",
iat: 1516239022,
};
const jwt = await create(header, payload, keyHS256);
const validatedPayload = await verify(jwt, keyHS256);
assertEquals(
jwt,
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o",
);
assertEquals(validatedPayload, payload);
await assertThrowsAsync(
async () => {
const invalidJwt = // jwt with not supported crypto algorithm in alg header:
"eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.bQTnz6AuMJvmXXQsVPrxeQNvzDkimo7VNXxHeSBfClLufmCVZRUuyTwJF311JHuh";
await verify(
invalidJwt,
keyHS256,
);
},
Error,
`The jwt's alg 'HS384' does not match the key's algorithm.`,
);
await assertThrowsAsync(
async () => {
const jwtWithInvalidSignature =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzcXNrz0ogthfEd2o";
await verify(jwtWithInvalidSignature, keyHS256);
},
Error,
"The jwt's signature does not match the verification signature.",
);
},
});
Deno.test({
name: "[jwt] HS384 algorithm",
fn: async function () {
const header: Header = { alg: "HS384", typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyHS384);
const validatedPayload = await verify(jwt, keyHS384);
assertEquals(validatedPayload, payload);
},
});
Deno.test({
name: "[jwt] HS512 algorithm",
fn: async function () {
const header: Header = { alg: "HS512", typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyHS512);
const validatedPayload = await verify(jwt, keyHS512);
assertEquals(validatedPayload, payload);
},
});
Deno.test("[jwt] RS256 algorithm", async function (): Promise<void> {
const header = { alg: "RS256" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyRS256.privateKey);
const receivedPayload = await verify(
jwt,
keyRS256.publicKey,
);
assertEquals(receivedPayload, payload);
await assertThrowsAsync(
async () => {
await verify(
jwt,
keyRS384.publicKey,
);
},
Error,
`The jwt's alg 'RS256' does not match the key's algorithm.`,
);
await assertThrowsAsync(
async () => {
await verify(
jwt,
keyPS256.publicKey,
);
},
Error,
`The jwt's alg 'RS256' does not match the key's algorithm.`,
);
});
Deno.test("[jwt] RS384 algorithm", async function (): Promise<void> {
const header = { alg: "RS384" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyRS384.privateKey);
const receivedPayload = await verify(
jwt,
keyRS384.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] RS512 algorithm", async function (): Promise<void> {
const header = { alg: "RS512" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyRS512.privateKey);
const receivedPayload = await verify(
jwt,
keyRS512.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] PS256 algorithm", async function (): Promise<void> {
const header = { alg: "PS256" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyPS256.privateKey);
const receivedPayload = await verify(
jwt,
keyPS256.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] PS384 algorithm", async function (): Promise<void> {
const header = { alg: "PS384" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyPS384.privateKey);
const receivedPayload = await verify(
jwt,
keyPS384.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] PS512 algorithm", async function (): Promise<void> {
const header = { alg: "PS512" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyPS512.privateKey);
const receivedPayload = await verify(
jwt,
keyPS512.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] ES256 algorithm", async function (): Promise<void> {
const header = { alg: "ES256" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyES256.privateKey);
const receivedPayload = await verify(
jwt,
keyES256.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] ES384 algorithm", async function (): Promise<void> {
const header = { alg: "ES384" as const, typ: "JWT" };
const payload = {
sub: "1234567890",
name: "John Doe",
admin: true,
iat: 1516239022,
};
const jwt = await create(header, payload, keyES384.privateKey);
const receivedPayload = await verify(
jwt,
keyES384.publicKey,
);
assertEquals(receivedPayload, payload);
});
Deno.test("[jwt] getNumericDate", function (): void {
// A specific date:
const t1 = getNumericDate(new Date("2020-01-01"));
const t2 = getNumericDate(new Date("2099-01-01"));
// Ten seconds from now:
const t3 = getNumericDate(10);
// One hour from now:
const t4 = getNumericDate(60 * 60);
// 1 second from now:
const t5 = getNumericDate(1);
// 1 second earlier:
const t6 = getNumericDate(-1);
assertEquals(t1 < Date.now() / 1000, true);
assertEquals(t2 < Date.now() / 1000, false);
assertEquals(10, t3 - Math.round(Date.now() / 1000));
assertEquals(t4 < Date.now() / 1000, false);
assertEquals(t5 < Date.now() / 1000, false);
assertEquals(t6 < Date.now() / 1000, true);
assertEquals(
getNumericDate(10),
getNumericDate(new Date(Date.now() + 10000)),
);
}); | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ConversationDetailsQueryVariables = {
conversationID: string;
};
export type ConversationDetailsQueryResponse = {
readonly me: {
readonly " $fragmentRefs": FragmentRefs<"ConversationDetails_me">;
} | null;
};
export type ConversationDetailsQuery = {
readonly response: ConversationDetailsQueryResponse;
readonly variables: ConversationDetailsQueryVariables;
};
/*
query ConversationDetailsQuery(
$conversationID: String!
) {
me {
...ConversationDetails_me
id
}
}
fragment AttachmentList_conversation on Conversation {
messagesConnection(first: 30, sort: DESC) {
edges {
node {
__typename
attachments {
id
contentType
...FileDownload_attachment
}
id
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
fragment AttachmentPreview_attachment on Attachment {
internalID
}
fragment ConversationDetails_me on Me {
conversation(id: $conversationID) {
...AttachmentList_conversation
to {
name
id
}
items {
item {
__typename
...ItemInfo_item
...OrderInformation_artwork
... on Node {
__isNode: __typename
id
}
}
}
orderConnection(first: 30, states: [APPROVED, PENDING, SUBMITTED, FULFILLED]) {
edges {
node {
__typename
...SellerReplyEstimate_order
...OrderInformation_order
...Shipping_order
...PaymentMethod_order
id
}
}
}
id
}
}
fragment FileDownload_attachment on Attachment {
fileName
downloadURL
...AttachmentPreview_attachment
}
fragment ItemArtwork_artwork on Artwork {
href
image {
thumbnailUrl: url(version: "small")
}
title
artistNames
date
saleMessage
partner {
name
id
}
}
fragment ItemInfo_item on ConversationItemType {
__isConversationItemType: __typename
...ItemArtwork_artwork
...ItemShow_show
__typename
}
fragment ItemShow_show on Show {
name
href
exhibitionPeriod(format: SHORT)
partner {
__typename
... on Partner {
name
}
... on Node {
__isNode: __typename
id
}
... on ExternalPartner {
id
}
}
image: coverImage {
thumbnailUrl: url(version: "small")
}
}
fragment OrderInformation_artwork on Artwork {
listPrice {
__typename
... on Money {
display
}
... on PriceRange {
display
}
}
}
fragment OrderInformation_order on CommerceOrder {
__isCommerceOrder: __typename
code
shippingTotal(precision: 2)
taxTotal(precision: 2)
buyerTotal(precision: 2)
... on CommerceOfferOrder {
lastOffer {
amount(precision: 2)
fromParticipant
id
}
}
}
fragment PaymentMethod_order on CommerceOrder {
__isCommerceOrder: __typename
creditCard {
lastDigits
expirationMonth
expirationYear
id
}
}
fragment SellerReplyEstimate_order on CommerceOrder {
__isCommerceOrder: __typename
displayState
stateExpiresAt(format: "MMM D")
requestedFulfillment {
__typename
}
... on CommerceOfferOrder {
buyerAction
}
lineItems {
edges {
node {
selectedShippingQuote {
displayName
id
}
id
}
}
}
}
fragment Shipping_order on CommerceOrder {
__isCommerceOrder: __typename
requestedFulfillment {
__typename
... on CommerceShip {
name
addressLine1
city
country
postalCode
}
... on CommerceShipArta {
name
addressLine1
city
country
postalCode
}
}
lineItems {
edges {
node {
artwork {
shippingOrigin
id
}
id
}
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "conversationID"
}
],
v1 = {
"kind": "Literal",
"name": "first",
"value": 30
},
v2 = [
(v1/*: any*/),
{
"kind": "Literal",
"name": "sort",
"value": "DESC"
}
],
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v6 = [
(v5/*: any*/),
(v4/*: any*/)
],
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v8 = [
{
"alias": "thumbnailUrl",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "small"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"small\")"
}
],
v9 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
v10 = [
(v4/*: any*/)
],
v11 = {
"kind": "InlineFragment",
"selections": (v10/*: any*/),
"type": "Node",
"abstractKey": "__isNode"
},
v12 = [
(v5/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "addressLine1",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "city",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "country",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "postalCode",
"storageKey": null
}
],
v13 = [
{
"kind": "Literal",
"name": "precision",
"value": 2
}
];
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "ConversationDetailsQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "ConversationDetails_me"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "ConversationDetailsQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Variable",
"name": "id",
"variableName": "conversationID"
}
],
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": (v2/*: any*/),
"concreteType": "MessageConnection",
"kind": "LinkedField",
"name": "messagesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "MessageEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Message",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Attachment",
"kind": "LinkedField",
"name": "attachments",
"plural": true,
"selections": [
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "contentType",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "fileName",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "downloadURL",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
}
],
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "messagesConnection(first:30,sort:\"DESC\")"
},
{
"alias": null,
"args": (v2/*: any*/),
"filters": [],
"handle": "connection",
"key": "Details_messagesConnection",
"kind": "LinkedHandle",
"name": "messagesConnection"
},
{
"alias": null,
"args": null,
"concreteType": "ConversationResponder",
"kind": "LinkedField",
"name": "to",
"plural": false,
"selections": (v6/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationItem",
"kind": "LinkedField",
"name": "items",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "item",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "TypeDiscriminator",
"abstractKey": "__isConversationItemType"
},
{
"kind": "InlineFragment",
"selections": [
(v7/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": (v6/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "listPrice",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": (v9/*: any*/),
"type": "Money",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v9/*: any*/),
"type": "PriceRange",
"abstractKey": null
}
],
"storageKey": null
}
],
"type": "Artwork",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v5/*: any*/),
(v7/*: any*/),
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v5/*: any*/)
],
"type": "Partner",
"abstractKey": null
},
(v11/*: any*/),
{
"kind": "InlineFragment",
"selections": (v10/*: any*/),
"type": "ExternalPartner",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": "image",
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": null
}
],
"type": "Show",
"abstractKey": null
},
(v11/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": [
(v1/*: any*/),
{
"kind": "Literal",
"name": "states",
"value": [
"APPROVED",
"PENDING",
"SUBMITTED",
"FULFILLED"
]
}
],
"concreteType": "CommerceOrderConnectionWithTotalCount",
"kind": "LinkedField",
"name": "orderConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceOrderEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "TypeDiscriminator",
"abstractKey": "__isCommerceOrder"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayState",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "MMM D"
}
],
"kind": "ScalarField",
"name": "stateExpiresAt",
"storageKey": "stateExpiresAt(format:\"MMM D\")"
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "requestedFulfillment",
"plural": false,
"selections": [
(v3/*: any*/),
{
"kind": "InlineFragment",
"selections": (v12/*: any*/),
"type": "CommerceShip",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": (v12/*: any*/),
"type": "CommerceShipArta",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemConnection",
"kind": "LinkedField",
"name": "lineItems",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItem",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuote",
"kind": "LinkedField",
"name": "selectedShippingQuote",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayName",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
(v4/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "shippingOrigin",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "code",
"storageKey": null
},
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "shippingTotal",
"storageKey": "shippingTotal(precision:2)"
},
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "taxTotal",
"storageKey": "taxTotal(precision:2)"
},
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "buyerTotal",
"storageKey": "buyerTotal(precision:2)"
},
{
"alias": null,
"args": null,
"concreteType": "CreditCard",
"kind": "LinkedField",
"name": "creditCard",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lastDigits",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "expirationMonth",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "expirationYear",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
},
(v4/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "buyerAction",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommerceOffer",
"kind": "LinkedField",
"name": "lastOffer",
"plural": false,
"selections": [
{
"alias": null,
"args": (v13/*: any*/),
"kind": "ScalarField",
"name": "amount",
"storageKey": "amount(precision:2)"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "fromParticipant",
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
],
"type": "CommerceOfferOrder",
"abstractKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "orderConnection(first:30,states:[\"APPROVED\",\"PENDING\",\"SUBMITTED\",\"FULFILLED\"])"
},
(v4/*: any*/)
],
"storageKey": null
},
(v4/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "0f29d1ab50da2a550a3bba294f3e822d",
"metadata": {},
"name": "ConversationDetailsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '464d6ba7c5353c651e81dc601cfa0b42';
export default node; | the_stack |
import { Component, State, h, Listen, Element } from '@stencil/core';
import { getUser } from '../../util/auth';
import { identify, trackEvent } from '../../util/hubspot';
import { getUtmParams } from '../../util/analytics';
import { UserInfo } from '../../declarations';
import { Emoji } from '../emoji-picker/emoji-picker';
import { generateAppIconForThemeAndEmoji, generateAppIconForThemeAndImage } from '../../util/app-icon';
const TEMPLATES = [
{ name: 'Tabs', id: 'tabs' },
{ name: 'Menu', id: 'sidemenu' },
{ name: 'List', id: 'list' },
];
const FRAMEWORKS = [
{ name: 'React', id: 'react' },
{ name: 'Angular', id: 'angular' },
{ name: 'Vue', id: 'vue' },
]
const THEMES = [
'#3880FF', // blue
'#5260ff', // purple
'#2dd36f', // green
'#ffc409', // yellow
'#eb445a', // red
'#f4f5f8', // light
'#92949c', // medium
'#222428', // dark
]
declare var window: any;
// const apiUrl = path => `${path}`;
const apiUrl = path => `https://wizard-api.ionicframework.com${path}`;
const emojiSvg = image => `https://twemoji.maxcdn.com/v/latest/svg/${image}.svg`;
@Component({
tag: 'ionic-app-wizard',
styleUrl: 'app-wizard.scss',
shadow: false
})
export class AppWizard {
@Element() el;
STEPS = [
{
name: 'Create app',
id: 'basics'
},
{
name: 'Account',
id: 'profile'
},
{
name: 'Finish',
id: 'finish'
}
]
STEP_BASICS = 0;
STEP_PROFILE = 1;
STEP_FINISH = 2;
@State() step = this.STEP_BASICS;
@State() showSignup = true;
@State() loginErrors = null;
@State() creatingApp = false;
@State() user: UserInfo;
@State() authParams: URLSearchParams;
// The current appId from the server
appId: string;
// Color picker ref
colorPickerRef: HTMLInputElement;
// Reference to the basic form for validation
submitButtonWrapRef: HTMLDivElement;
getRandomEmoji(): Emoji {
const emoji = [
'1f60b', // yum
'1f601', // grin
'1f60e', // shades
'1f61c', //
'1f929', // starstruck
'1f604', // smile
'1f603', // smiley
'1f973', // party
].map(i => ({
image: i
}));
return emoji[Math.floor(Math.random() * emoji.length)];
}
@State() selectedEmoji: Emoji = this.getRandomEmoji();
@State() showEmojiPicker = false;
@State() emojiPickerEvent: MouseEvent = null;
@State() isAppIconDropping = false;
@State() appIconUploadError = '';
// Form state
@State() authenticating = false;
@State() theme = THEMES[0];
@State() appName = '';
@State() framework = 'react';
@State() template = 'tabs';
@State() bundleId = '';
@State() appUrl = '';
@State() appIcon: string;
async componentDidLoad() {
const params = new URLSearchParams(window.location.hash.slice(1));
this.authParams = new URLSearchParams(window.location.search);
if (params.has('state')) {
this.appId = params.get('state');
} else if (params.has('pwa')) {
window.location.hash = '';
trackEvent({id: 'Starting_PWA_Wizard'});
} else if (params.has('vue')) {
this.framework = 'vue';
window.location.hash = '';
trackEvent({id: 'Starting_Vue_Wizard'});
}
const stayOnFinish = params.has('finish');
if (this.appId) {
this.finish(stayOnFinish);
} else {
this.setStep(this.STEP_BASICS);
}
try {
// Get the user to see if they are logged in
this.user = await getUser();
} catch (e) {
}
}
@Listen('popstate', { target: 'window' })
handlePopState(e) {
if (e.state) {
const step = e.state.step;
this.step = step || 0;
}
}
setStep = (step) => {
this.step = step;
let hash = this.STEPS[this.step].id;
history.pushState({ step: this.step }, null, `#${hash}`);
}
authorize = () => {
if (this.authParams.get('client_id') !== 'cli') {
const params = new URLSearchParams();
params.set("scope", "openid profile email");
params.set("response_type", "id_token token");
params.set("client_id", "wizard");
params.set("redirect_uri", window.location.origin + '/start')
params.set("state", this.appId || '');
params.set("nonce", Math.random().toString(36).substring(2));
params.set("source", "wizard-1");
window.location.assign(`/signup?${params.toString()}`);
} else {
const path = this.user ? 'oauth/authorize' : 'signup';
this.authParams.set("state", this.appId || '');
this.authParams.set("source", "cli-start-wizard");
window.location.assign(`/${path}?${this.authParams.toString()}`);
}
};
finish = (stayOnFinish = false) => {
if (this.user) {
identify(this.user.email, this.user.sub);
}
trackEvent({
id: 'Start Wizard Finish'
});
if(stayOnFinish) {
this.setStep(this.STEPS.length - 1);
} else {
const currentOrigin = window.location.origin.toLowerCase();
let urlBase = currentOrigin.indexOf('staging.ionicframework.com') > -1 ?
'https://staging.ionicjs.com' :
currentOrigin.indexOf('ionicframework.com') > -1 ?
'https://dashboard.ionicframework.com' : 'http://localhost:8080'
window.location.href = `${urlBase}/create-app/${this.appId}`
}
};
basicsNext = async (e?) => {
e?.preventDefault();
e?.stopPropagation();
try {
this.creatingApp = true;
const created = await this.save();
if (!created) {
alert('Unable to create app, please ping us on Twitter and try the manual install below.');
this.setStep(this.STEP_BASICS);
return;
}
if (this.user && this.authParams.get('client_id') !== 'cli') {
this.finish();
} else {
this.authorize();
}
} catch (e) {
try {
const data = JSON.parse(e.message);
if (data.type === 'too-large') {
alert('Unable to create app, your icon image is too large. Try a smaller filesize or add it manually later');
} else {
alert('Unable to create app, please ping us on Twitter and try the manual install below.');
}
} catch(e) {
alert('Unable to create app, please ping us on Twitter and try the manual install below.');
}
} finally {
this.creatingApp = false;
}
}
save = async () => {
let iconImage;
let splash;
if (!this.appIcon && this.selectedEmoji) {
const emoji = this.selectedEmoji;
let emojiImage = emoji.image.replace('.png', '');
const emojiSplit = emojiImage.split('-');
let emojiImageName = emojiImage;
if (emojiSplit.length === 2 && emojiSplit[1] === 'fe0f') {
emojiImageName = emojiImage.replace('-fe0f', '');
}
const emojiImageUrl = emojiSvg(emojiImageName);
const renderedAppIcon = await generateAppIconForThemeAndEmoji(this.theme, emojiImageUrl, 1024, 768);
const renderedSplashScreen = await generateAppIconForThemeAndEmoji(this.theme, emojiImageUrl, 2732, 512);
iconImage = renderedAppIcon;
splash = renderedSplashScreen;
} else {
const renderedSplashScreen = await generateAppIconForThemeAndImage(this.theme, this.appIcon, 2732, 512);
iconImage = this.appIcon;
splash = renderedSplashScreen;
}
const res = await fetch(apiUrl('/api/v1/wizard/create'), {
body: JSON.stringify({
type: this.framework,
'package-id': this.bundleId,
tid: this.getHubspotId(),
email: this.user?.email,
appId: this.appId,
template: this.template,
name: this.appName,
theme: this.theme,
appSplash: splash,
appIcon: iconImage,
utm: getUtmParams()
}),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (res.status === 413) {
throw new Error(JSON.stringify({ type: 'too-large' }));
}
if (res.status !== 200) {
throw new Error(JSON.stringify({ type: 'error' }));
}
const data = await res.json();
this.appId = data.appId;
return data;
}
getApp = async () => {
const res = await fetch(apiUrl(`/api/v1/wizard/app/${this.getHubspotId()}`));
return await res.json();
}
getHubspotId = () => {
return window.getCookie('hubspotutk');
}
handlePickEmoji = (e) => {
this.selectedEmoji = e.detail as Emoji;
this.appIcon = null;
this.showEmojiPicker = false;
}
handlePickTheme = (_e) => {
const colorPicker = this.el.querySelector('input[type="color"]');
colorPicker && colorPicker.click();
}
handleInput = (fieldName) => e => {
this[fieldName] = e.target.value;
};
setAppIconFromFile = (file: File) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = new Image();
img.src = reader.result as string;
img.onload = () => {
if (img.width < 1024 || img.height < 1024) {
alert('Icon size must be at least 1024x1024');
} else {
this.selectedEmoji = null;
this.appIcon = reader.result as string;
}
}
}
reader.onerror = () => {
this.appIconUploadError = 'Unable to read file';
}
}
handleAppIconChoose = (e) => {
if (e.target.files.length) {
const file = e.target.files[0];
if (file.size > 1024 * 800) {
this.appIconUploadError = 'Image must be < 800KB';
return;
}
this.setAppIconFromFile(file);
}
}
handleAppIconDragOver = (e: DragEvent) => {
this.isAppIconDropping = true;
e.dataTransfer.dropEffect = 'copy';
e.preventDefault();
}
handleAppIconDragOut = (_e) => {
this.isAppIconDropping = false;
}
handleAppIconDrop = (e: DragEvent) => {
e.preventDefault();
this.isAppIconDropping = false;
if (e.dataTransfer.files) {
const file = e.dataTransfer.files[0];
if (file.size > 1024 * 800) {
this.appIconUploadError = 'Image must be < 800KB';
return;
}
this.setAppIconFromFile(file);
}
}
handleRootDragOver = (e: DragEvent) => {
e.preventDefault();
return false;
};
handleRootDrop = (e: DragEvent) => {
e.preventDefault();
return false;
};
renderBasics() {
const { showEmojiPicker, creatingApp } = this;
let buttonText;
if (creatingApp) {
buttonText = <span><ion-spinner /></span>;
} else if (this.user) {
buttonText = <span>Create App</span>;
} else {
buttonText = <span>Continue {'->'}</span>;
}
return (
<div>
<hgroup>
<h2>Welcome to Ionic</h2>
<p>Let's start your first app</p>
</hgroup>
<form class="form" onSubmit={this.basicsNext}>
<ui-floating-input
label="App name"
type="text"
name="app-name"
value={this.appName}
tabindex={1}
required={true}
onChange={this.handleInput('appName')} />
<div
class={`app-icon-group`}>
<div class="app-icon-pick">
<label>
Pick an icon
<ui-tip
text="An icon for your app. You can easily change this and add your own image later!"
position="top">
<InfoCircle />
</ui-tip>
</label>
<AppIcon
img={this.appIcon}
emoji={this.selectedEmoji}
theme={this.theme}
onChooseEmoji={(e) => { this.showEmojiPicker = true; this.emojiPickerEvent = e }}
onChooseFile={this.handleAppIconChoose}
isDropping={this.isAppIconDropping}
onDragOver={this.handleAppIconDragOver}
onDragLeave={this.handleAppIconDragOut}
onDrop={this.handleAppIconDrop}
/>
</div>
<ionic-emoji-picker
open={showEmojiPicker}
openEvent={this.emojiPickerEvent}
onEmojiPick={this.handlePickEmoji}
onClosed={() => this.showEmojiPicker = false} />
<div class="app-icon-theme">
<label>Pick a theme color</label>
<ui-tip
text="The primary brand color for your app"
position="top">
<InfoCircle />
</ui-tip>
<ThemeSwitcher
value={this.theme}
onChange={(theme) => this.theme = theme}
onPick={this.handlePickTheme}
/>
</div>
</div>
<div class="form-group">
<label>
Pick a layout template
<ui-tip
text="Choose a tabs, menu, or list-style layout"
position="top">
<InfoCircle />
</ui-tip>
</label>
<TemplateSwitcher
value={this.template}
onChange={tmpl => this.template = tmpl} />
</div>
<div class="form-group" id="field-appname">
<label>
Pick a JavaScript Framework
<ui-tip
text="React and Vue are beginner friendly, Angular is popular for enterprise"
position="top">
<InfoCircle />
</ui-tip>
</label>
<FrameworkSwitcher
value={this.framework}
onChange={framework => {
this.framework = framework;
}} />
</div>
<div ref={e => this.submitButtonWrapRef = e} class="next-button-wrapper">
<Button disabled={creatingApp}>
{buttonText}
</Button>
</div>
</form>
</div>
)
}
renderFinish() {
const instructions = `
npm install -g @ionic/cli cordova-res
ionic start --start-id ${this.appId}
`;
document.querySelector('.header__feedback').classList.add('is-visible');
return (
<div class="finish">
<hgroup>
<span class="icon">🎉</span>
<h2>You're all set</h2>
<p>
Run this to see your amazing new app:
</p>
</hgroup>
<div>
<pre><code>{instructions}</code></pre>
</div>
<div class="info">
Requires <b><code>@ionic/cli</code> 6.5.0</b> or above<br />
Need help? See the full <a href="https://ionicframework.com/docs/installation/cli">installation guide</a>
</div>
<div class="share">
<a
href="https://twitter.com/share?ref_src=twsrc%5Etfw"
class="twitter-share-button"
data-size="large"
data-text="Check out the new mobile App Wizard from @ionicframework"
data-url="https://ionicframework.com/start"
data-via="ionicframework"
data-related="ionicframework,maxlynch"
data-show-count="false">Tweet</a>
</div>
<hr />
<div class="social">
<iframe src="https://ghbtns.com/github-btn.html?user=ionic-team&repo=ionic&type=star&count=true" frameborder="0" scrolling="0" width="100px" height="30px"></iframe>
<a class="twitter-follow-button"
data-show-screen-name="false"
href="https://twitter.com/ionicframework">
Follow @IonicFramework</a>
</div>
<twitter-script />
</div>
)
}
renderStep() {
switch (this.step) {
case this.STEP_BASICS: return this.renderBasics();
case this.STEP_PROFILE: return null;
case this.STEP_FINISH: return this.renderFinish();
}
}
render() {
return (
<div id="app-wizard" onDragOver={this.handleRootDragOver} onDrop={this.handleRootDrop}>
{this.step < 2 ? (
<ionic-switcher
items={[this.STEPS[0], this.STEPS[1]].map(s => s.name).join()}
index={this.step}
/>
) : null}
<div class="form-area">
{this.renderStep()}
</div>
<div class="notice notice--fixed">
Prefer to install manually? <br />
<a href="https://ionicframework.com/getting-started#install">Follow our CLI installation guide</a>
</div>
</div>
);
}
}
const Button = (props, children) => (
<button type="submit" class="btn btn-block" {...props}>{ children }</button>
);
const AppIcon = ({ img, emoji, theme, onChooseEmoji, isDropping,
onChooseFile, onDragOver, onDragLeave, onDrop }) => {
const bgColor = img ? 'transparent': theme;
let bgImage;
if (emoji) {
let emojiImage = emoji.image.replace('.png', '');
const imageSplit = emojiImage.split('-');
// For some reason we need to remove fe0f from images that just have it
// as blah-fe0f since those aren't named as such in the twemoji database
if (imageSplit.length == 2 && imageSplit[1] === 'fe0f') {
emojiImage = emojiImage.replace('-fe0f', '');
}
bgImage = `url('${emojiSvg(emojiImage)}')`;
} else {
bgImage = `url(${img})`;
}
return (
<div class={`app-icon-wrapper${isDropping ? ` app-icon-dropping` : ''}`}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}>
<div class="app-icon-dropping-wrapper">
<div class="app-icon-dropping-icon">
<svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
<path d="M9 1V17" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17 9H1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
</div>
<div
class="app-icon"
style={{ backgroundColor: bgColor }}>
<div
class={`app-icon-image${ img ? ' app-icon-image-uploaded' : ''}`}
style={{ backgroundImage: bgImage }} />
<div class="app-icon-hover">
<div class="app-icon-hover-icons">
<div class="icon" onClick={onChooseEmoji} title="Pick emoji">
<svg width="26" height="26" viewBox="0 0 26 26" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13 25C19.6274 25 25 19.6274 25 13C25 6.37258 19.6274 1 13 1C6.37258 1 1 6.37258 1 13C1 19.6274 6.37258 25 13 25Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.19995 16.3C8.19995 16.3 9.99995 18.7 13 18.7C16 18.7 17.8 16.3 17.8 16.3" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.5 11.2H8.512" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17.5 11.2H17.512" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
<div class="icon" onClick={() => (document.querySelector('#file-app-icon') as HTMLInputElement).click()} title="Pick file">
<svg width="18" height="24" viewBox="0 0 18 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17 23H1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9 1V19" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M17 9L9 1L1 9" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
</div>
<input type="file" id="file-app-icon" accept="image/png" onChange={onChooseFile} />
</div>
</div>
</div>
)
};
const ThemeSwitcher = ({ value, onChange, onPick }) => {
const themes = [
...THEMES,
!THEMES.find(t => t === value) ? value : null
].filter(t => !!t);
return (
<div class="themes">
{themes.map(t => (
<div
key={t}
class={`theme ${value === t ? 'selected' : ''}`}
style={{ backgroundColor: t }}
onClick={() => onChange(t)}>
{ value === t ? (
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 1L4 11L1 7.25" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
) : null}
</div>
))}
<div
class="theme pick-theme"
onClick={() => onPick()}
>
<ion-icon name="md-color-filter" />
<input
type="color"
class="color-picker"
value={value}
onInput={(e: any) => onChange(e.currentTarget.value) }
/>
</div>
</div>
)
}
const FrameworkSwitcher = ({ value, onChange }) => (
<div class="frameworks">
{FRAMEWORKS.map(f => (
<div
key={f.id}
class={`framework ${value === f.id ? 'selected' : ''}`}
onClick={() => onChange(f.id)}>
<div class={`framework-logo framework-${f.id}`} />
<h5>{f.name}</h5>
</div>
))}
</div>
);
const TemplateSwitcher = ({ value, onChange }) => (
<div class="templates">
{TEMPLATES.map(f => (
<div
key={f.id}
class={`template ${value === f.id ? 'selected' : ''}`}
onClick={() => onChange(f.id)}>
<div class={`template-image template-${f.id}`} />
<h5>{f.name}</h5>
</div>
))}
</div>
);
const InfoCircle = () => (
<ion-icon class="info-circle" name="information-circle-outline" />
); | the_stack |
import { Select } from "./";
import { IJoinQuery, DATA_TYPE, ERROR_TYPE, ISelectQuery } from "@/common";
import { getDataType, LogHelper, removeSpace, promiseReject } from "@/worker/utils";
export const executeJoinQuery = function (this: Select) {
return new Join(this).execute();
}
interface JoinQueryWithInfo extends IJoinQuery {
joinTableInfo: JoinTableInfo
}
export class Join {
private joinQueryStack_: JoinQueryWithInfo[] = [];
private currentQueryStackIndex_ = 0;
tablesFetched = [];
results = [];
select: Select;
constructor(select: Select) {
this.select = select;
}
get query() {
return this.select.query;
}
getTable(name: string) {
return this.select.table(name);
}
private executeSelect(query: ISelectQuery) {
// this.select.util.emptyTx();
return new Select(query, this.select.util).
execute();
}
execute() {
const query = this.query;
this.joinQueryStack_ = getDataType(query.join) === DATA_TYPE.Object ?
[query.join as JoinQueryWithInfo] : query.join as JoinQueryWithInfo[];
// get the data for first table
const tableName = query.from;
const tablesToFetch = [tableName];
for (let i = 0, length = this.joinQueryStack_.length; i < length; i++) {
const item = this.joinQueryStack_[i];
let jointblInfo = this.getJoinTableInfo_(item.on);
// table 1 is fetched & table2 needs to be fetched for join
if (item.with === jointblInfo.table1.table) {
jointblInfo = {
table1: jointblInfo.table2,
table2: jointblInfo.table1
};
}
const err = this.checkJoinQuery_(jointblInfo, item);
if (err) {
return promiseReject(err);
}
this.joinQueryStack_[i].joinTableInfo = jointblInfo;
tablesToFetch.push(item.with)
}
if (!this.select.isTxQuery) {
this.select.util.createTransaction(tablesToFetch);
}
return this.executeSelect({
from: tableName,
where: query.where,
case: query.case,
flatten: query.flatten
}).then(results => {
this.results = results.map((item) => {
return {
[this.currentQueryStackIndex_]: item
};
});
this.tablesFetched.push(tableName);
return this.startExecutingJoinLogic_();
});
}
private onJoinQueryFinished_() {
// const query = this.query;
if (this.results.length > 0) {
try {
let results = [];
const tables = Object.keys(this.results[0]);
const tablesLength = tables.length;
const mapWithAlias = (query: IJoinQuery, value: object) => {
if (query.as != null) {
for (const key in query.as) {
if (value[(query.as as any)[key]] === undefined) {
value[(query.as as any)[key]] = value[key];
delete value[key];
}
}
}
return value;
};
this.results.forEach((result) => {
let data = result["0"]; // first table data
for (let i = 1; i < tablesLength; i++) {
const query = this.joinQueryStack_[i - 1];
data = { ...data, ...mapWithAlias(query, result[i]) };
}
results.push(data);
});
this.select['results'] = results;
this.select.setLimitAndSkipEvaluationAtEnd_();
this.select.query.flatten = null;
if (process.env.NODE_ENV === 'dev') {
try {
this.select.processOrderBy();
}
catch (ex) {
return promiseReject(
new LogHelper(ERROR_TYPE.InvalidOrderQuery, ex.message)
);
}
}
else {
this.select.processOrderBy();
}
if (process.env.NODE_ENV === 'dev') {
try {
this.select.processGroupDistinctAggr();
}
catch (ex) {
return promiseReject(
new LogHelper(ERROR_TYPE.InvalidGroupQuery, ex.message)
);
}
}
else {
this.select.processGroupDistinctAggr();
}
}
catch (ex) {
return promiseReject(
new LogHelper(ERROR_TYPE.InvalidJoinQuery, ex.message)
);
}
}
return;
}
private startExecutingJoinLogic_() {
const joinQuery = this.joinQueryStack_[this.currentQueryStackIndex_];
if (joinQuery) {
try {
let jointblInfo = joinQuery.joinTableInfo;
return this.executeSelect({
from: joinQuery.with,
where: joinQuery.where,
case: joinQuery.case,
flatten: joinQuery.flatten
}).then(results => {
this.jointables(joinQuery.type, jointblInfo, results);
this.tablesFetched.push(jointblInfo.table2.table);
++this.currentQueryStackIndex_;
return this.startExecutingJoinLogic_();
});
}
catch (ex) {
return promiseReject(
new LogHelper(ERROR_TYPE.InvalidJoinQuery, ex.message)
);
}
}
else {
return this.onJoinQueryFinished_();
}
}
private jointables(joinType: string, jointblInfo: JoinTableInfo, secondtableData: any[]) {
const results = [];
const column1 = jointblInfo.table1.column;
const column2 = jointblInfo.table2.column;
const table1Index = this.tablesFetched.indexOf(jointblInfo.table1.table);
const table2Index = this.currentQueryStackIndex_ + 1;
const performInnerJoin = () => {
let index = 0;
this.results.forEach(valueFromFirstTable => {
secondtableData.forEach((valueFromSecondTable) => {
if (valueFromFirstTable[table1Index][column1] === valueFromSecondTable[column2]) {
results[index] = { ...valueFromFirstTable };
results[index++][table2Index] = valueFromSecondTable;
}
});
});
};
const performleftJoin = () => {
let index = 0;
let valueMatchedFromSecondTable: any[];
let callBack;
const columnDefaultValue = {};
this.getTable(jointblInfo.table2.table).columns.forEach(col => {
columnDefaultValue[col.name] = null;
});
this.results.forEach((valueFromFirstTable) => {
valueMatchedFromSecondTable = [];
if (table2Index === 1) {
callBack = function (valueFromSecondTable) {
if (valueFromFirstTable[table1Index][column1] === valueFromSecondTable[column2]) {
valueMatchedFromSecondTable.push(valueFromSecondTable);
}
};
}
else {
callBack = function (valueFromSecondTable) {
const value = valueFromFirstTable[table1Index];
if (value != null && value[column1] === valueFromSecondTable[column2]) {
valueMatchedFromSecondTable.push(valueFromSecondTable);
}
};
}
secondtableData.forEach(callBack);
if (valueMatchedFromSecondTable.length === 0) {
valueMatchedFromSecondTable = [columnDefaultValue];
}
valueMatchedFromSecondTable.forEach(function (value) {
results[index] = { ...valueFromFirstTable };
results[index++][table2Index] = value;
});
});
};
switch (joinType) {
case "left":
performleftJoin(); break;
default:
performInnerJoin();
}
this.results = results;
}
private getJoinTableInfo_(joinOn: string) {
joinOn = removeSpace(joinOn);
const splittedjoinOn = joinOn.split("=");
const splittedjoinOnbydotFirst = splittedjoinOn[0].split(".");
const splittedjoinOnbydotSecond = splittedjoinOn[1].split(".");
const info = {
table1: {
table: splittedjoinOnbydotFirst[0],
column: splittedjoinOnbydotFirst[1]
},
table2: {
table: splittedjoinOnbydotSecond[0],
column: splittedjoinOnbydotSecond[1]
}
} as JoinTableInfo;
return info;
}
private checkJoinQuery_(jointblInfo: JoinTableInfo, qry: IJoinQuery) {
const table1 = jointblInfo.table1;
const table2 = jointblInfo.table2;
const tableSchemaOf1stTable = this.getTable(table1.table);
const tableSchemaOf2ndTable = this.getTable(table2.table);
let err: LogHelper;
// check on info & with info
if (qry.with !== table2.table) {
err = new LogHelper(ERROR_TYPE.InvalidJoinQuery,
`on value should contains value of with`
);
}
// check for column existance
if (tableSchemaOf1stTable.columns.find(q => q.name === table1.column) == null) {
err = new LogHelper(ERROR_TYPE.InvalidJoinQuery,
`column ${table1.column} does not exist in table ${table1.table}`
);
}
else if (tableSchemaOf2ndTable.columns.find(q => q.name === table2.column) == null) {
err = new LogHelper(ERROR_TYPE.InvalidJoinQuery,
`column ${table2.column} does not exist in table ${table2.table}`
);
}
// check for column match in both table
if (qry.as == null) {
qry.as = {};
}
tableSchemaOf1stTable.columns.every(function (column) {
const columnFound = tableSchemaOf2ndTable.columns.find(q => q.name === column.name && q.name !== table1.column);
if (columnFound != null && qry.as[columnFound.name] == null) {
err = new LogHelper(ERROR_TYPE.InvalidJoinQuery,
`column ${column.name} exist in both table ${table1.table} & ${table2.table}`
);
return false;
}
return true;
});
return err;
}
}
type JoinTableInfo = {
table1: { table: string, column: string }
table2: { table: string, column: string }
}; | the_stack |
import { expect } from 'chai'
import 'mocha'
import * as sinon from 'sinon'
import { IAirGapTransaction, isCoinlibReady, TezosProtocol } from '../../src'
import BigNumber from '../../src/dependencies/src/bignumber.js-9.0.0/bignumber'
import { RawTezosTransaction } from '../../src/serializer/types'
import { TezosTestProtocolSpec } from '../protocols/specs/tezos'
import { TezosTransactionOperation } from '../../src/protocols/tezos/types/operations/Transaction'
import { TezosOperationType } from '../../src/protocols/tezos/types/TezosOperationType'
import { TezosOriginationOperation } from '../../src/protocols/tezos/types/operations/Origination'
import { TezosWrappedOperation } from '../../src/protocols/tezos/types/TezosWrappedOperation'
import { TezosRevealOperation } from '../../src/protocols/tezos/types/operations/Reveal'
import { RunOperationMetadata } from '../../src/protocols/tezos/TezosProtocol'
import { TezosProtocolStub } from './stubs/tezos.stub'
import { AirGapTransactionStatus } from '../../src/interfaces/IAirGapTransaction'
import { TezosOperation } from '../../src/protocols/tezos/types/operations/TezosOperation'
import { ConditionViolationError } from '../../src/errors'
import { Domain } from '../../src/errors/coinlib-error'
const tezosProtocolSpec = new TezosTestProtocolSpec()
const tezosLib = tezosProtocolSpec.lib
const prepareTxHelper = async (rawTezosTx: RawTezosTransaction, protocol: TezosProtocol = tezosLib) => {
const airGapTxs = await protocol.getTransactionDetails({
transaction: rawTezosTx,
publicKey: tezosProtocolSpec.wallet.publicKey
})
const unforgedTransaction = await protocol.unforgeUnsignedTezosWrappedOperation(rawTezosTx.binaryTransaction)
const spendOperation = unforgedTransaction.contents.find((content) => content.kind === TezosOperationType.TRANSACTION)
if (spendOperation) {
const spendTransaction: TezosTransactionOperation = spendOperation as TezosTransactionOperation
return {
spendTransaction,
originationTransaction: {} as any,
unforgedTransaction,
airGapTxs,
rawTezosTx
}
}
const originationOperation = unforgedTransaction.contents.find((content) => content.kind === TezosOperationType.ORIGINATION)
if (originationOperation) {
const originationTransaction: TezosOriginationOperation = originationOperation as TezosOriginationOperation
return {
spendTransaction: {} as any,
originationTransaction,
unforgedTransaction,
airGapTxs,
rawTezosTx
}
}
throw new Error('no supported operation')
}
const prepareSpend = async (receivers: string[], amounts: string[], fee: string) => {
const rawTezosTx = await tezosLib.prepareTransactionFromPublicKey(tezosProtocolSpec.wallet.publicKey, receivers, amounts, fee)
return prepareTxHelper(rawTezosTx)
}
describe(`ICoinProtocol Tezos - Custom Tests`, () => {
afterEach(() => {
sinon.restore()
})
describe('TX Lists', () => {
let getStub
let postStub
beforeEach(() => {
const res = new TezosProtocolStub().registerStub(new TezosTestProtocolSpec(), tezosLib)
getStub = res.getStub
postStub = res.postStub
getStub
.withArgs(`${tezosLib.baseApiUrl}/v3/operations/${tezosProtocolSpec.wallet.addresses[0]}?type=Transaction&p=0&number=20`)
.returns(
Promise.resolve({
data: [
{
hash: 'ooNNmftGhsUriHVWYgHGq6AE3F2sHZFYaCq41NQZSeUdm1UZEAP',
block_hash: 'BMVuKQVUh2hxdgAf7mnXUQuf82BcMxuZjoLNxCi7YSJ4Mzvk7Qe',
network_hash: 'NetXdQprcVkpaWU',
type: {
kind: 'manager',
source: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
operations: [
{
kind: 'transaction',
src: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
amount: 1000000,
destination: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
failed: false,
internal: false,
burn: 0,
counter: 917316,
fee: 1420,
gas_limit: '10100',
storage_limit: '0',
op_level: 261513,
timestamp: '2019-01-08T10:02:15Z'
}
]
}
},
{
hash: 'ooNNmftGhsUriHVWYgHGq6AE3F2sHZFYaCq41NQZSeUdm1UZEAP',
block_hash: 'BMVuKQVUh2hxdgAf7mnXUQuf82BcMxuZjoLNxCi7YSJ4Mzvk7Qe',
network_hash: 'NetXdQprcVkpaWU',
type: {
kind: 'manager',
source: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
operations: [
{
kind: 'transaction',
src: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
amount: 1000000,
destination: {
tz: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'
},
failed: false,
internal: false,
burn: 0,
counter: 917316,
fee: 1420,
gas_limit: '10100',
storage_limit: '0',
op_level: 261513,
timestamp: '2019-01-08T10:02:15Z'
}
]
}
}
]
})
)
})
it('will parse various operations', async () => {
const hexString =
'a732d3520eeaa3de98d78e5e5cb6c85f72204fd46feb9f76853841d4a701add36c0008ba0cb2fad622697145cf1665124096d25bc31ef44e0af44e00b960000008ba0cb2fad622697145cf1665124096d25bc31e006c0008ba0cb2fad622697145cf1665124096d25bc31ed3e7bd1008d3bb0300b1a803000008ba0cb2fad622697145cf1665124096d25bc31e00' // contains: fee, counter, gas_limit, storage_limit and amount
/*
{ "branch":"BLyvCRkxuTXkx1KeGvrcEXiPYj4p1tFxzvFDhoHE7SFKtmP1rbk",
"contents":[{
"kind":"transaction",
"fee":"10100",
"gas_limit":"10100",
"storage_limit": "0",
"amount":"12345",
"counter":"10",
"destination":"tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA",
"source":"tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA"},
{
"kind":"transaction",
"fee":"34567123",
"gas_limit":"56787",
"storage_limit": "0",
"amount":"54321",
"counter":"8",
"destination":"tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA",
"source":"tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA"}]
}
*/
let tezosWrappedOperation: TezosWrappedOperation = await tezosLib.unforgeUnsignedTezosWrappedOperation(hexString)
expect(tezosWrappedOperation.branch).to.equal('BLyvCRkxuTXkx1KeGvrcEXiPYj4p1tFxzvFDhoHE7SFKtmP1rbk')
expect(tezosWrappedOperation.contents.length).to.equal(2)
const spendOperation1: TezosTransactionOperation = tezosWrappedOperation.contents[0] as TezosTransactionOperation
const spendOperation2: TezosTransactionOperation = tezosWrappedOperation.contents[1] as TezosTransactionOperation
expect(spendOperation1.fee).to.equal('10100')
expect(spendOperation1.gas_limit).to.equal('10100')
expect(spendOperation1.storage_limit).to.equal('0')
expect(spendOperation1.amount).to.equal('12345')
expect(spendOperation1.counter).to.equal('10')
expect(spendOperation1.source).to.equal('tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA')
expect(spendOperation1.destination).to.equal('tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA')
expect(spendOperation2.fee).to.equal('34567123')
expect(spendOperation2.gas_limit).to.equal('56787')
expect(spendOperation2.storage_limit).to.equal('0')
expect(spendOperation2.amount).to.equal('54321')
expect(spendOperation2.counter).to.equal('8')
expect(spendOperation2.source).to.equal('tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA')
expect(spendOperation2.destination).to.equal('tz1LSAycAVcNdYnXCy18bwVksXci8gUC2YpA')
/*
{ "branch":"BLyvCRkxuTXkx1KeGvrcEXiPYj4p1tFxzvFDhoHE7SFKtmP1rbk",
"contents":[
{
"kind":"reveal",
"fee":"7866",
"gas_limit":"3984",
"storage_limit": "9",
"counter":"13",
"public_key":"edpkvCq9fHmAukBpFurMwR7YVukezNW7GCdQop3PJsGCo62t5MDeNw",
"source":"tz1i6q8g1dcUha9PkKYpt3NtaXiQDLdLPSVn"
},
{
"kind":"transaction",
"fee":"56723",
"gas_limit":"9875",
"storage_limit": "2342356",
"amount":"67846",
"counter":"87988",
"destination":"KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy",
"source":"tz1KtGwriE7VuLwT3LwuvU9Nv4wAxP7XZ57d"
},
{
"kind":"transaction",
"fee":"31656123",
"gas_limit":"6780893",
"storage_limit": "0",
"amount":"67867",
"counter":"23423856",
"destination":"KT1J5mFAxxzAYDLjYeVXkLcyEzNGRZ3kuFGq",
"source":"tz1dBVokTuhh5UXtKxaVqmiUyhqoQhu71BmS"
}
]
}
*/
const hexBigOperationTransaction =
'a732d3520eeaa3de98d78e5e5cb6c85f72204fd46feb9f76853841d4a701add36b00f6645951a38c13586cda1edb9bdbebcf34a50773ba3d0d901f0900cdbc0c3449784bd53907c3c7a06060cf12087e492a7b937f044c6a73b522a2346c0002b1b8e2338ea7bf67ef23ff1277cbc7d4b6842493bb03b4af05934dd4fb8e0186920401ba4e7349ac25dc5eb2df5a43fceacc58963df4f500006c00c06daac32b63628ff2ed4b75ade88132cbef78d5bb918c0ff0d6950bddef9d03009b9204016834ed66e95b00e7aeeab2778d7c6b5a571171550000'
tezosWrappedOperation = await tezosLib.unforgeUnsignedTezosWrappedOperation(hexBigOperationTransaction)
expect(tezosWrappedOperation.branch).to.equal('BLyvCRkxuTXkx1KeGvrcEXiPYj4p1tFxzvFDhoHE7SFKtmP1rbk')
expect(tezosWrappedOperation.contents.length).to.equal(3)
const operation1: TezosRevealOperation = tezosWrappedOperation.contents[0] as TezosRevealOperation
const operation2: TezosTransactionOperation = tezosWrappedOperation.contents[1] as TezosTransactionOperation
const operation3: TezosTransactionOperation = tezosWrappedOperation.contents[2] as TezosTransactionOperation
expect(operation1.fee).to.equal('7866')
expect(operation1.gas_limit).to.equal('3984')
expect(operation1.storage_limit).to.equal('9')
expect(operation1.counter).to.equal('13')
expect(operation1.source).to.equal('tz1i6q8g1dcUha9PkKYpt3NtaXiQDLdLPSVn')
expect(operation1.public_key).to.equal('edpkvCq9fHmAukBpFurMwR7YVukezNW7GCdQop3PJsGCo62t5MDeNw')
expect(operation2.fee).to.equal('56723')
expect(operation2.gas_limit).to.equal('9875')
expect(operation2.storage_limit).to.equal('2342356')
expect(operation2.amount).to.equal('67846')
expect(operation2.counter).to.equal('87988')
expect(operation2.source).to.equal('tz1KtGwriE7VuLwT3LwuvU9Nv4wAxP7XZ57d')
expect(operation2.destination).to.equal('KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy')
expect(operation3.fee).to.equal('31656123')
expect(operation3.gas_limit).to.equal('6780893')
expect(operation3.storage_limit).to.equal('0')
expect(operation3.amount).to.equal('67867')
expect(operation3.counter).to.equal('23423856')
expect(operation3.source).to.equal('tz1dBVokTuhh5UXtKxaVqmiUyhqoQhu71BmS')
expect(operation3.destination).to.equal('KT1J5mFAxxzAYDLjYeVXkLcyEzNGRZ3kuFGq')
})
it('can unforge a delegation TX', async () => {})
it('can give a list of transactions from Conseil API', async () => {
postStub.withArgs(`${tezosLib.baseApiUrl}/v2/data/tezos/mainnet/operations`).returns(
Promise.resolve({
data: [
{
source: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L',
timestamp: 1561035943000,
block_level: 261513,
operation_group_hash: 'ooNNmftGhsUriHVWYgHGq6AE3F2sHZFYaCq41NQZSeUdm1UZEAP',
amount: 1000000,
destination: 'tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L',
fee: 1420,
status: 'applied'
}
]
})
)
const transactions = await (await tezosLib.getTransactionsFromAddresses(tezosProtocolSpec.wallet.addresses, 20)).transactions
expect(transactions.map((transaction) => ({ ...transaction, network: undefined }))).to.deep.eq([
{
amount: new BigNumber(1000000),
fee: new BigNumber(1420),
from: ['tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'],
isInbound: true,
network: undefined,
timestamp: 1561035943,
protocolIdentifier: tezosLib.identifier,
to: ['tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L'],
hash: 'ooNNmftGhsUriHVWYgHGq6AE3F2sHZFYaCq41NQZSeUdm1UZEAP',
blockHeight: 261513,
status: AirGapTransactionStatus.APPLIED
}
])
expect(transactions.map((transaction) => ({ ...transaction.network, blockExplorer: undefined, extras: undefined }))).to.deep.eq([
{
blockExplorer: undefined,
extras: undefined,
name: 'Mainnet',
rpcUrl: 'https://tezos-node.prod.gke.papers.tech',
type: 'MAINNET'
}
])
})
})
describe('KT1 Prepare/Sign', () => {
let getStub
let postStub
beforeEach(async () => {
await isCoinlibReady()
const res = new TezosProtocolStub().registerStub(new TezosTestProtocolSpec(), tezosLib)
getStub = res.getStub
postStub = res.postStub
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L/counter`)
.returns(Promise.resolve({ data: 917326 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/hash`)
.returns(Promise.resolve({ data: 'BMT1dwxYkLbssY34irU2LbSHEAYBZ3KfqtYCixaZoMoaarhx3Ko' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L/balance`)
.returns(Promise.resolve({ data: 100000000 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy/balance`)
.returns(Promise.resolve({ data: 0 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L/manager_key`)
.returns(Promise.resolve({ data: { key: 'test-key' } }))
})
it('will properly prepare a TX to a KT1 address', async () => {
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '15385',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
],
signature: ''
}
})
)
const result = await prepareSpend(
['KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy'],
['100000'], // send so much funds that it should deduct, given it is a 0-balance receiver (which it is not)
'1420'
)
expect(result.spendTransaction.storage_limit).to.equal('0') // kt addresses do not need to get funed, they are originated :)
expect(result.airGapTxs.length).to.equal(1)
expect(result.airGapTxs[0].amount).to.equal('100000')
expect(result.airGapTxs[0].fee).to.equal('1420')
expect(result.rawTezosTx.binaryTransaction).to.equal(
'e4b7e31c04d23e3a10ea20e11bd0ebb4bde16f632c1d94779fd5849a34ec42a36c0091a9d2b003f19cf5a1f38f04f1000ab482d331768c0bcffe37997800a08d0601ba4e7349ac25dc5eb2df5a43fceacc58963df4f50000'
)
})
it('will properly sign a TX to a KT1 address', async () => {
const signedTezosTx = await tezosLib.signWithPrivateKey(Buffer.from(tezosProtocolSpec.wallet.privateKey, 'hex'), {
binaryTransaction:
'e4b7e31c04d23e3a10ea20e11bd0ebb4bde16f632c1d94779fd5849a34ec42a308000091a9d2b003f19cf5a1f38f04f1000ab482d331768c0bcffe37f44eac02a08d0601ba4e7349ac25dc5eb2df5a43fceacc58963df4f50000'
})
expect(signedTezosTx).to.equal(
'e4b7e31c04d23e3a10ea20e11bd0ebb4bde16f632c1d94779fd5849a34ec42a308000091a9d2b003f19cf5a1f38f04f1000ab482d331768c0bcffe37f44eac02a08d0601ba4e7349ac25dc5eb2df5a43fceacc58963df4f50000a39862b8a5a80ae96f1040c999f9075ba7490d9206ec6443b06d2df3442d6cf09ea264daa09164622b7cb565d8ba37a02c9de7fd04ae50a78f531136cfd9b00e'
)
})
})
describe('Address Init', () => {
let getStub
let postStub
// const sendFee = new BigNumber('1400')
// const revealFee = new BigNumber('1300')
const initializationFee: BigNumber = new BigNumber('257000')
// const originationBurn = new BigNumber('257000')
beforeEach(async () => {
await isCoinlibReady()
sinon.restore()
const res = new TezosProtocolStub().registerStub(new TezosTestProtocolSpec(), tezosLib)
getStub = res.getStub
postStub = res.postStub
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${tezosProtocolSpec.wallet.addresses[0]}/counter`)
.returns(Promise.resolve({ data: 917315 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/hash`)
.returns(Promise.resolve({ data: 'BMJyc7ga9kLV3vH4kbn6GXbBNjRkLEJVSyovoXyY84Er1zMmKKT' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${tezosProtocolSpec.wallet.addresses[0]}/balance`)
.returns(Promise.resolve({ data: 1000000 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/tz1bgWdfd9YS7pTkNgZTNs26c33nBHwSYW6S/balance`)
.returns(Promise.resolve({ data: 0 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7/balance`)
.returns(Promise.resolve({ data: 0.1 }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${tezosProtocolSpec.wallet.addresses[0]}/manager_key`)
.returns(Promise.resolve({ data: { key: 'test-key' } }))
})
describe('Spend', () => {
it('will deduct fee to initialize empty tz1 receiving address, if amount + fee === balance', async () => {
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '300'
},
internal_operation_results: []
}
}
],
signature: ''
}
})
)
const address = 'tz1bgWdfd9YS7pTkNgZTNs26c33nBHwSYW6S'
const amount = '900000'
const fee = '100000'
const result = await prepareSpend(
[address],
[amount], // send so much funds that it should deduct, given it is a 0-balance receiver (which it is not)
fee
)
// check that storage is properly set
expect(result.spendTransaction.storage_limit).to.equal('300')
expect(result.airGapTxs.length).to.equal(1)
expect(result.airGapTxs[0].amount).to.equal('643000') // 900000 - 257000 amount - initializationFee
expect(result.airGapTxs[0].amount).to.equal(new BigNumber(amount).minus(initializationFee).toFixed())
expect(result.airGapTxs[0].fee).to.equal('100000')
expect(result.airGapTxs[0].fee).to.equal(fee)
})
it('will not deduct fee if enough funds are available on the account', async () => {
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '300'
},
internal_operation_results: []
}
}
],
signature: ''
}
})
)
const result = await prepareSpend(
['tz1bgWdfd9YS7pTkNgZTNs26c33nBHwSYW6S'],
['100000'], // send so much funds that it should deduct, given it is a 0-balance receiver (which it is not)
'100000'
)
// check that storage is properly set
expect(result.spendTransaction.storage_limit).to.equal('300')
expect(result.airGapTxs.length).to.equal(1)
expect(result.airGapTxs[0].amount).to.equal('100000') // amount should be correct
expect(result.airGapTxs[0].fee).to.equal('100000')
})
it('will correctly calculate the max transaction value for both revealed and unrevealed accounts', async () => {
const address = tezosProtocolSpec.wallet.addresses[0]
const configs = [tezosProtocolSpec.revealedAddressConfig, tezosProtocolSpec.unrevealedAddressConfig]
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/counter`)
.returns(Promise.resolve({ data: '10147076' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/hash`)
.returns(Promise.resolve({ data: 'BLKAx9imSqD5t1qyu3K1cuZwVzddZRjuHpa8w94fh1aUmPgMohM' }))
for (let config of configs) {
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/balance`)
.returns(Promise.resolve({ data: config.balance }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/manager_key`)
.returns(Promise.resolve({ data: config.manager_key }))
postStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`)
.returns(Promise.resolve({ data: config.run_operation }))
const estimatedFeeDefaults = await tezosLib.estimateFeeDefaultsFromPublicKey(
tezosProtocolSpec.wallet.publicKey,
[config.toAddress],
[new BigNumber(config.balance).toString()]
)
// in case the account is unrevealed, maxFee includes the revealFee of 1300
const maxFee = new BigNumber(estimatedFeeDefaults.medium).shiftedBy(tezosLib.decimals).toNumber()
const maxTransfer = await tezosLib.estimateMaxTransactionValueFromPublicKey(tezosProtocolSpec.wallet.publicKey, [
config.toAddress
])
expect(new BigNumber(maxTransfer).toNumber()).to.equal(new BigNumber(config.balance - maxFee - 1).toNumber())
}
})
// TODO: create an issue
it.skip('will correctly prepare operations for an unrevealed address', async () => {
const address = tezosProtocolSpec.wallet.addresses[0]
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/counter`)
.returns(Promise.resolve({ data: '10147076' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/hash`)
.returns(Promise.resolve({ data: 'BLKAx9imSqD5t1qyu3K1cuZwVzddZRjuHpa8w94fh1aUmPgMohM' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/balance`)
.returns(Promise.resolve({ data: tezosProtocolSpec.unrevealedAddressConfig.balance }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/manager_key`)
.returns(Promise.resolve({ data: tezosProtocolSpec.unrevealedAddressConfig.manager_key }))
postStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`)
.returns(Promise.resolve({ data: tezosProtocolSpec.unrevealedAddressConfig.run_operation }))
const operationRequest = {
kind: 'transaction',
amount: tezosProtocolSpec.unrevealedAddressConfig.balance - 1,
destination: 'tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ',
fee: '0'
} as TezosOperation
const tezosWrappedOperation = await tezosLib.prepareOperations(tezosProtocolSpec.wallet.publicKey, [operationRequest])
const containsRevealOperation = tezosWrappedOperation.contents.some(
(tezosOperation: TezosOperation) => tezosOperation.kind === TezosOperationType.REVEAL
)
expect(containsRevealOperation).eq(true)
const transactions = tezosWrappedOperation.contents.filter(
(tezosOperation: TezosOperation) => tezosOperation.kind === TezosOperationType.TRANSACTION
)
const revealFee = 1300
const totalAmount = transactions
.map((transaction) => (transaction as TezosTransactionOperation).amount)
.reduce((a, b) => new BigNumber(a).plus(b).toString())
expect(totalAmount).eq(new BigNumber(tezosProtocolSpec.unrevealedAddressConfig.balance - 1).minus(revealFee).toString())
})
it('will correctly prepare operations, taking the specified parameters as is', async () => {
const address = tezosProtocolSpec.wallet.addresses[0]
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/counter`)
.returns(Promise.resolve({ data: '10147076' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/hash`)
.returns(Promise.resolve({ data: 'BLKAx9imSqD5t1qyu3K1cuZwVzddZRjuHpa8w94fh1aUmPgMohM' }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/balance`)
.returns(Promise.resolve({ data: tezosProtocolSpec.revealedAddressConfig.balance }))
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${address}/manager_key`)
.returns(Promise.resolve({ data: tezosProtocolSpec.revealedAddressConfig.manager_key }))
postStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`)
.returns(Promise.resolve({ data: tezosProtocolSpec.revealedAddressConfig.run_operation }))
const setValue = '1008'
const operationRequest = {
kind: 'transaction',
amount: tezosProtocolSpec.revealedAddressConfig.balance - 1,
destination: 'tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ',
fee: setValue,
counter: setValue,
gas_limit: setValue,
storage_limit: setValue
} as TezosOperation
const tezosWrappedOperation = await tezosLib.prepareOperations(tezosProtocolSpec.wallet.publicKey, [operationRequest], false)
const preparedOperation = tezosWrappedOperation.contents[0] as any
expect(preparedOperation.kind).to.equal('transaction')
expect(preparedOperation.fee).to.equal(setValue)
expect(preparedOperation.gas_limit).to.equal(setValue)
expect(preparedOperation.storage_limit).to.equal(setValue)
expect(preparedOperation.counter).to.equal(setValue)
})
it('will not mess with anything, given the receiving account has balance already', async () => {
const result = await prepareSpend(
['tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'],
['899999'], // send so much funds that it should deduct, given it is a 0-balance receiver (which it is not)
'100000'
)
// check that storage is properly set
expect(result.spendTransaction.storage_limit).to.equal('0')
expect(result.airGapTxs.length).to.equal(1)
expect(result.airGapTxs[0].amount).to.equal('899999') // amount should be correct
expect(result.airGapTxs[0].fee).to.equal('100000')
})
it('will leave 1 mutez behind if we try to send the full balance', async () => {
const result = await prepareSpend(
['tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'],
['900000'], // send so much funds that it should deduct, given it is a 0-balance receiver (which it is not)
'100000'
)
// check that storage is properly set
expect(result.spendTransaction.storage_limit).to.equal('0')
expect(result.airGapTxs.length).to.equal(1)
expect(result.airGapTxs[0].amount).to.equal('899999') // amount should be 1 less
expect(result.airGapTxs[0].fee).to.equal('100000')
})
})
it('will prepare a transaction with multiple spend operations to KT addresses', async () => {
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy/balance`)
.returns(Promise.resolve({ data: 0 }))
const txRunOperation = {
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [txRunOperation, txRunOperation],
signature: ''
}
})
)
const result = await prepareSpend(
['KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy', 'KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy'],
['12345', '54321'],
'111'
)
// check that storage is properly set
expect(result.spendTransaction.gas_limit).to.equal('10300')
expect(result.spendTransaction.storage_limit).to.equal('0')
expect(result.airGapTxs.length).to.equal(2)
expect(result.airGapTxs[0].amount).to.equal('12345')
expect(result.airGapTxs[0].fee).to.equal('111')
expect(result.airGapTxs[1].amount).to.equal('54321')
expect(result.airGapTxs[1].fee).to.equal('111')
})
it('will correctly prepare a single operation group if below the threshold', async () => {
const txRunOperation = {
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
const numberOfOperations: number = 50
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [...Array(numberOfOperations)].map((x) => txRunOperation),
signature: ''
}
})
)
const result = await prepareSpend(
[...Array(numberOfOperations)].map((x) => 'KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy'),
[...Array(numberOfOperations)].map((v, i) => i.toString()),
'1'
)
expect(result.airGapTxs.length).to.equal(50)
})
it('will throw an error if number of operations is above the threshold for a single operation group', async () => {
const numberOfOperations: number = 51
const txRunOperation = {
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [...Array(numberOfOperations)].map((x) => txRunOperation),
signature: ''
}
})
)
return prepareSpend(
[...Array(numberOfOperations)].map((x) => 'KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy'),
[...Array(numberOfOperations)].map((v, i) => i.toString()),
'1'
).catch((error: Error) =>
expect(error)
.to.be.an('error')
.with.property(
'message',
'this transaction exceeds the maximum allowed number of transactions per operation. Please use the "prepareTransactionsFromPublicKey" method instead.'
)
)
})
it('will correctly prepare a single operation group when calling prepareTransactionsFromPublicKey', async () => {
const numberOfOperations: number = 50
const protocol = new TezosProtocol()
const txRunOperation = {
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [...Array(numberOfOperations)].map((x) => txRunOperation),
signature: ''
}
})
)
const transactions = await protocol.prepareTransactionsFromPublicKey(
tezosProtocolSpec.wallet.publicKey,
[...Array(numberOfOperations)].map((x) => 'KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy'),
[...Array(numberOfOperations)].map((v, i) => i.toString()),
'1'
)
expect(transactions.length).to.equal(1)
const result1 = await prepareTxHelper(transactions[0])
expect(result1.airGapTxs.length).to.equal(50)
})
it('will return 2 operation groups when calling prepareTransactionsFromPublicKey with a number of operations above the threshold', async () => {
const numberOfOperations: number = 215
const protocol = new TezosProtocol()
const txRunOperation = {
kind: 'transaction',
metadata: {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '10300',
paid_storage_size_diff: '0'
},
internal_operation_results: []
}
}
postStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`)
.onCall(0)
.returns(
Promise.resolve({
data: {
contents: [...Array(200)].map((x) => txRunOperation),
signature: ''
}
})
)
postStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`)
.onCall(1)
.returns(
Promise.resolve({
data: {
contents: [...Array(15)].map((x) => txRunOperation),
signature: ''
}
})
)
const transactions = await protocol.prepareTransactionsFromPublicKey(
tezosProtocolSpec.wallet.publicKey,
[...Array(numberOfOperations)].map((x) => 'tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ'),
[...Array(numberOfOperations)].map((v, i) => i.toString()),
'1'
)
expect(transactions.length).to.equal(2)
const result1 = await prepareTxHelper(transactions[0])
const result2 = await prepareTxHelper(transactions[1])
expect(result1.airGapTxs.length).to.equal(200)
expect(result2.airGapTxs.length).to.equal(15)
expect(result1.airGapTxs[0].amount, 'result1 first amount').to.equal('0')
expect(result1.airGapTxs[0].fee, 'result1 first fee').to.equal('1')
expect(result1.airGapTxs[0].transactionDetails.counter, 'result1 first counter').to.equal('917316')
expect(result1.airGapTxs[199].amount).to.equal('199')
expect(result1.airGapTxs[199].fee).to.equal('1')
expect(result1.airGapTxs[199].transactionDetails.counter).to.equal('917515')
expect(result2.airGapTxs[0].amount).to.equal('200')
expect(result2.airGapTxs[0].fee).to.equal('1')
expect(result2.airGapTxs[0].transactionDetails.counter).to.equal('917516')
})
// TODO: add test to test the add reveal to spend transactions
it('will prepare an FA 1.2 transaction', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa12
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
transfer: {
prim: 'pair',
args: [
{
prim: 'address',
annots: [':from']
},
{
prim: 'pair',
args: [
{
prim: 'address',
annots: [':to']
},
{
prim: 'nat',
annots: [':value']
}
]
}
]
}
}
}
})
)
const tx = {
kind: 'transaction',
amount: '0',
fee: '500000',
storage_limit: '60000',
destination: 'KT1LH2o12xVRwTpJMZ6QJG74Fox8gE9QieFd',
parameters: {
entrypoint: 'transfer',
value: {
prim: 'Pair',
args: [
{
string: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7'
},
{
prim: 'Pair',
args: [
{
string: 'tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ'
},
{
int: '10'
}
]
}
]
}
}
}
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{ ...tx, metadata },
{ ...tx, metadata }
]
}
})
)
const incompleteTransaction: any[] = [tx, tx]
const transaction = await protocol.prepareOperations(tezosProtocolSpec.wallet.publicKey, incompleteTransaction)
const forged = await protocol.forgeAndWrapOperations(transaction)
const result = await prepareTxHelper(forged, protocol)
// check that storage is properly set
// expect(result.spendTransaction.storage_limit).to.equal('0')
expect(result.airGapTxs.length).to.equal(2)
const airGapTx = result.airGapTxs[0]
const airGapTx2 = result.airGapTxs[1]
expect(airGapTx.transactionDetails.amount).to.equal('0')
expect(airGapTx.transactionDetails.fee).to.equal('35308')
expect(airGapTx.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.transactionDetails.storage_limit).to.equal('0')
expect(airGapTx.transactionDetails.source).to.equal('tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L')
expect(airGapTx.transactionDetails.destination).to.equal('KT1LH2o12xVRwTpJMZ6QJG74Fox8gE9QieFd')
expect(airGapTx.transactionDetails.parameters).to.not.be.undefined
expect(airGapTx.transactionDetails.parameters.entrypoint).to.equal('transfer')
expect(airGapTx.transactionDetails.parameters.value.args[0].string).to.equal('tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7')
expect(airGapTx.transactionDetails.parameters.value.args[1].args[0].string).to.equal('tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ')
expect(airGapTx.transactionDetails.parameters.value.args[1].args[1].int).to.equal('10')
expect(airGapTx2.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.from.length).to.equal(1)
expect(airGapTx.from[0]).to.equal('tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7')
expect(airGapTx.to.length).to.equal(1)
expect(airGapTx.to[0]).to.equal('tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ')
expect(airGapTx.amount).to.equal('10')
expect(airGapTx.fee).to.equal('35308')
})
it('will prepare an FA2 transaction from public key', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
transfer: {
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%from_']
},
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%to_']
},
{
prim: 'pair',
args: [
{
prim: 'nat',
annots: ['%token_id']
},
{
prim: 'nat',
annots: ['%amount']
}
]
}
]
}
],
annots: ['%txs']
}
]
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const transaction = await protocol.prepareTransactionFromPublicKey(
tezosProtocolSpec.wallet.publicKey,
['tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM', 'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH'],
['100', '200'],
'500000'
)
const result = await prepareTxHelper(transaction, protocol)
const airGapTx = result.airGapTxs[0]
expect(airGapTx.transactionDetails.amount).to.equal('0')
expect(airGapTx.transactionDetails.fee).to.equal('500000')
expect(airGapTx.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.transactionDetails.storage_limit).to.equal('0')
expect(airGapTx.transactionDetails.source).to.equal('tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L')
expect(airGapTx.transactionDetails.destination).to.equal(protocol.contractAddress)
expect(airGapTx.transactionDetails.parameters).to.not.be.undefined
expect(airGapTx.transactionDetails.parameters.entrypoint).to.equal('transfer')
expect(airGapTx.transactionDetails.parameters.value[0].args[0].string).to.equal(tezosProtocolSpec.wallet.addresses[0])
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[0].string).to.equal('tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[1].args[0].int).to.equal('0')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[1].args[1].int).to.equal('100')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[0].string).to.equal('tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[1].args[0].int).to.equal('0')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[1].args[1].int).to.equal('200')
})
it('will prepare an FA2 transfer transaction', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
transfer: {
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%from_']
},
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%to_']
},
{
prim: 'pair',
args: [
{
prim: 'nat',
annots: ['%token_id']
},
{
prim: 'nat',
annots: ['%amount']
}
]
}
]
}
],
annots: ['%txs']
}
]
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const transaction = await protocol.transfer(
[
{
from: 'tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM',
txs: [
{
to: 'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH',
amount: '100',
tokenID: 10
},
{
to: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt',
amount: '110',
tokenID: 11
}
]
},
{
from: 'tz1Xsrfv6hn86fp88YfRs6xcKwt2nTqxVZYM',
txs: [
{
to: 'tz1NpWrAyDL9k2Lmnyxcgr9xuJakbBxdq7FB',
amount: '200',
tokenID: 20
}
]
}
],
'500000',
tezosProtocolSpec.wallet.publicKey
)
const result = await prepareTxHelper(transaction, protocol)
const airGapTx = result.airGapTxs[0]
expect(airGapTx.transactionDetails.amount).to.equal('0')
expect(airGapTx.transactionDetails.fee).to.equal('500000')
expect(airGapTx.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.transactionDetails.storage_limit).to.equal('0')
expect(airGapTx.transactionDetails.source).to.equal('tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L')
expect(airGapTx.transactionDetails.destination).to.equal(protocol.contractAddress)
expect(airGapTx.transactionDetails.parameters).to.not.be.undefined
expect(airGapTx.transactionDetails.parameters.entrypoint).to.equal('transfer')
expect(airGapTx.transactionDetails.parameters.value[0].args[0].string).to.equal('tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[0].string).to.equal('tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[1].args[0].int).to.equal('10')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][0].args[1].args[1].int).to.equal('100')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[0].string).to.equal('tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[1].args[0].int).to.equal('11')
expect(airGapTx.transactionDetails.parameters.value[0].args[1][1].args[1].args[1].int).to.equal('110')
expect(airGapTx.transactionDetails.parameters.value[1].args[0].string).to.equal('tz1Xsrfv6hn86fp88YfRs6xcKwt2nTqxVZYM')
expect(airGapTx.transactionDetails.parameters.value[1].args[1][0].args[0].string).to.equal('tz1NpWrAyDL9k2Lmnyxcgr9xuJakbBxdq7FB')
expect(airGapTx.transactionDetails.parameters.value[1].args[1][0].args[1].args[0].int).to.equal('20')
expect(airGapTx.transactionDetails.parameters.value[1].args[1][0].args[1].args[1].int).to.equal('200')
})
it('will prepare an FA2 update operators transaction', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
update_operators: {
prim: 'list',
args: [
{
prim: 'or',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%owner']
},
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%operator']
},
{
prim: 'nat',
annots: ['%token_id']
}
]
}
],
annots: ['%add_operator']
},
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%owner']
},
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%operator']
},
{
prim: 'nat',
annots: ['%token_id']
}
]
}
],
annots: ['%remove_operator']
}
]
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const transaction = await protocol.updateOperators(
[
{
operation: 'add',
owner: 'tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM',
operator: 'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH',
tokenId: 0
},
{
operation: 'remove',
owner: 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt',
operator: 'tz1Xsrfv6hn86fp88YfRs6xcKwt2nTqxVZYM',
tokenId: 1
}
],
'500000',
tezosProtocolSpec.wallet.publicKey
)
const result = await prepareTxHelper(transaction, protocol)
const airGapTx = result.airGapTxs[0]
expect(airGapTx.transactionDetails.amount).to.equal('0')
expect(airGapTx.transactionDetails.fee).to.equal('500000')
expect(airGapTx.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.transactionDetails.storage_limit).to.equal('0')
expect(airGapTx.transactionDetails.source).to.equal('tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L')
expect(airGapTx.transactionDetails.destination).to.equal(protocol.contractAddress)
expect(airGapTx.transactionDetails.parameters).to.not.be.undefined
expect(airGapTx.transactionDetails.parameters.entrypoint).to.equal('update_operators')
expect(airGapTx.transactionDetails.parameters.value[0].args[0].args[0].string).to.equal('tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM')
expect(airGapTx.transactionDetails.parameters.value[0].args[0].args[1].args[0].string).to.equal(
'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH'
)
expect(airGapTx.transactionDetails.parameters.value[0].args[0].args[1].args[1].int).to.equal('0')
expect(airGapTx.transactionDetails.parameters.value[1].args[0].args[0].string).to.equal('tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt')
expect(airGapTx.transactionDetails.parameters.value[1].args[0].args[1].args[0].string).to.equal(
'tz1Xsrfv6hn86fp88YfRs6xcKwt2nTqxVZYM'
)
expect(airGapTx.transactionDetails.parameters.value[1].args[0].args[1].args[1].int).to.equal('1')
})
it('will prepare an FA2 token metadata transaction', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
token_metadata: {
prim: 'pair',
args: [
{
prim: 'list',
args: [
{
prim: 'nat'
}
],
annots: ['%token_ids']
},
{
prim: 'lambda',
args: [
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'nat',
annots: ['%token_id']
},
{
prim: 'pair',
args: [
{
prim: 'string',
annots: ['%symbol']
},
{
prim: 'pair',
args: [
{
prim: 'string',
annots: ['%name']
},
{
prim: 'pair',
args: [
{
prim: 'nat',
annots: ['%decimals']
},
{
prim: 'map',
args: [
{
prim: 'string'
},
{
prim: 'string'
}
],
annots: ['%extras']
}
]
}
]
}
]
}
]
}
]
},
{
prim: 'unit'
}
],
annots: ['%handler']
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
}
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const transaction = await protocol.tokenMetadata([0, 1, 2], 'handler', '500000', tezosProtocolSpec.wallet.publicKey)
const result = await prepareTxHelper(transaction, protocol)
const airGapTx = result.airGapTxs[0]
expect(airGapTx.transactionDetails.amount).to.equal('0')
expect(airGapTx.transactionDetails.fee).to.equal('500000')
expect(airGapTx.transactionDetails.gas_limit).to.equal('350000')
expect(airGapTx.transactionDetails.storage_limit).to.equal('0')
expect(airGapTx.transactionDetails.source).to.equal('tz1YvE7Sfo92ueEPEdZceNWd5MWNeMNSt16L')
expect(airGapTx.transactionDetails.destination).to.equal(protocol.contractAddress)
expect(airGapTx.transactionDetails.parameters).to.not.be.undefined
expect(airGapTx.transactionDetails.parameters.entrypoint).to.equal('token_metadata')
expect(airGapTx.transactionDetails.parameters.value.args[0][0].int).to.equal('0')
expect(airGapTx.transactionDetails.parameters.value.args[0][1].int).to.equal('1')
expect(airGapTx.transactionDetails.parameters.value.args[0][2].int).to.equal('2')
expect(airGapTx.transactionDetails.parameters.value.args[1].string).to.equal('handler')
})
it('will check FA2 balance', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
balance_of: {
prim: 'pair',
args: [
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%owner']
},
{
prim: 'nat',
annots: ['%token_id']
}
]
}
],
annots: ['%requests']
},
{
prim: 'contract',
args: [
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{
prim: 'pair',
args: [
{
prim: 'address',
annots: ['%owner']
},
{
prim: 'nat',
annots: ['%token_id']
}
],
annots: ['%request']
},
{
prim: 'nat',
annots: ['%balance']
}
]
}
]
}
],
annots: ['%callback']
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
},
internal_operation_results: [
{
parameters: {
entrypoint: 'default',
value: [
{
prim: 'Pair',
args: [
{
prim: 'Pair',
args: [
{
string: 'tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM'
},
{
int: '0'
}
]
},
{
int: 100
}
]
},
{
prim: 'Pair',
args: [
{
prim: 'Pair',
args: [
{
string: 'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH'
},
{
int: '1'
}
]
},
{
int: 110
}
]
}
]
}
}
]
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const source = 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt'
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${source}/counter`).returns(
Promise.resolve({
data: 0
})
)
const balanceResults = await protocol.balanceOf(
[
{
address: 'tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM',
tokenID: 0
},
{
address: 'tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH',
tokenID: 1
}
],
source,
'KT1B3vuScLjXeesTAYo19LdnnLgGqyYZtgae'
)
expect(balanceResults.length).to.equal(2)
expect(balanceResults[0].address).to.equal('tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM')
expect(balanceResults[0].tokenID).to.equal(0)
expect(balanceResults[0].amount).to.equal('100')
expect(balanceResults[1].address).to.equal('tz1awXW7wuXy21c66vBudMXQVAPgRnqqwgTH')
expect(balanceResults[1].tokenID).to.equal(1)
expect(balanceResults[1].amount).to.equal('110')
})
it('will gets FA2 token metadata address', async () => {
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/`).returns(
Promise.resolve({
data: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
chain_id: 'NetXdQprcVkpaWU',
hash: 'BKuTvcx5LJQgtiNXbd4py3RFRE4x7EYjTFwJjVjj4XP7h2vSxs6',
header: {
level: 940455,
proto: 6,
predecessor: 'BLurthGbZXstELdA3hXtGAA5kXxgtxmfUpzCq7bzpPVB92u9g1z',
timestamp: '2020-05-06T10:41:32Z',
validation_pass: 4,
operations_hash: 'LLoajfGAHirmjbJWjX81gNiZPqyv8pqEyUx7FAygiYBXLQ18H2kX8',
fitness: ['01', '00000000000459a7'],
context: 'CoVNfjwSR78ChDuvVpRW6Lvjq6nwC6UsyrZzhDgrU2ZMiPYXNjYy',
priority: 0,
proof_of_work_nonce: '0639894462090000',
signature: 'sigjnLFcgqv8QC1QwNhPgg4WomUGtL4nQ68u3GavKXLLWyFcf8g2ceaT6FeuRRVGcdDY7qj7MBo2iUo83L1rtroQKMhqZbw2'
},
metadata: {
protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
next_protocol: 'PsCARTHAGazKbHtnKfLzQg3kms52kSRpgnDY982a9oYsSXRLQEb',
test_chain_status: { status: 'not_running' },
max_operations_ttl: 60,
max_operation_data_length: 16384,
max_block_header_length: 238,
max_operation_list_length: [
{
max_size: 32768,
max_op: 32
},
{ max_size: 32768 },
{
max_size: 135168,
max_op: 132
},
{ max_size: 524288 }
],
baker: 'tz1Kt4P8BCaP93AEV4eA7gmpRryWt5hznjCP',
level: {
level: 940455,
level_position: 940454,
cycle: 229,
cycle_position: 2470,
voting_period: 28,
voting_period_position: 22950,
expected_commitment: false
},
voting_period_kind: 'proposal',
nonce_hash: null,
consumed_gas: '0',
deactivated: [],
balance_updates: []
},
operations: [[], [], [], []]
}
})
)
const protocol = tezosProtocolSpec.fa2
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/script`).returns(
Promise.resolve({
data: {
code: []
}
})
)
getStub.withArgs(`${protocol.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${protocol.contractAddress}/entrypoints`).returns(
Promise.resolve({
data: {
entrypoints: {
token_metadata_registry: {
prim: 'contract',
args: [
{
prim: 'address'
}
]
}
}
}
})
)
const metadata: RunOperationMetadata = {
balance_updates: [],
operation_result: {
status: 'applied',
balance_updates: [],
consumed_gas: '350000'
},
internal_operation_results: [
{
parameters: {
entrypoint: 'default',
value: {
string: 'tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM'
}
}
}
]
}
postStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/helpers/scripts/run_operation`).returns(
Promise.resolve({
data: {
contents: [
{
kind: 'transaction',
amount: '0',
fee: '35308',
storage_limit: '60000',
destination: protocol.contractAddress,
metadata
}
]
}
})
)
const source = 'tz1Yju7jmmsaUiG9qQLoYv35v5pHgnWoLWbt'
getStub.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/${source}/counter`).returns(
Promise.resolve({
data: 0
})
)
const tokenMetadataRegistry = await protocol.tokenMetadataRegistry(source, 'KT1B3vuScLjXeesTAYo19LdnnLgGqyYZtgae')
expect(tokenMetadataRegistry).to.equal('tz1MecudVJnFZN5FSrriu8ULz2d6dDTR7KaM')
})
it('will throw an error if the number of recipients and amounts do not match', async () => {
getStub
.withArgs(`${tezosLib.jsonRPCAPI}/chains/main/blocks/head/context/contracts/KT1RZsEGgjQV5iSdpdY3MHKKHqNPuL9rn6wy/balance`)
.returns(Promise.resolve({ data: 0 }))
return prepareSpend(['KT1X6SSqro2zUo1Wa7X5BnDWBvfBxZ6feUnc', 'KT1QLtQ54dKzcfwxMHmEM6PC8tooUg6MxDZ3'], ['12345'], '111').catch(
(error: Error) =>
expect(error)
.to.be.an('error')
.with.property('message', new ConditionViolationError(Domain.TEZOS, 'length of recipients and values does not match!').message)
)
})
})
describe('TransactionDetails', () => {
it('correctly get transaction details from a forged, unsigned transaction', async () => {
const forgedUnsignedTransaction: string =
'e879f5c6312b85da97cbb3bcb14dd515f29b407a0cc08b70fbcdece5bb49d8b06e00bf97f5f1dbfd6ada0cf986d0a812f1bf0a572abc8c0bbe8139bc5000ff0012548f71994cb2ce18072d0dcb568fe35fb74930'
const protocol: TezosProtocol = new TezosProtocol()
const details: IAirGapTransaction[] = await protocol.getTransactionDetails({
publicKey: '',
transaction: { binaryTransaction: forgedUnsignedTransaction }
})
expect(details[0].amount).to.equal('0')
expect(details[0].fee).to.equal('1420')
expect(details[0].from[0]).to.equal('tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7')
expect(details[0].to[0]).to.equal('tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ')
expect(details[0].transactionDetails).to.deep.equal({
kind: 'delegation',
source: 'tz1d75oB6T4zUMexzkr5WscGktZ1Nss1JrT7',
fee: '1420',
counter: '934078',
gas_limit: '10300',
storage_limit: '0',
delegate: 'tz1MJx9vhaNRSimcuXPK2rW4fLccQnDAnVKJ'
})
})
})
}) | the_stack |
import * as stream from 'stream';
import * as db from '../util/db';
import { tokenize, stripUnsafeTokens } from '../util/tokenize';
export interface Row {
id : number;
schema_id : number|null;
is_base : boolean;
language : string;
type : string;
flags : string;
utterance : string;
preprocessed : string;
target_json : string;
target_code : string;
context : string|null;
click_count : number;
like_count : number;
owner : number|null;
name : string|null;
}
export type OptionalFields = 'schema_id' | 'is_base' | 'language' | 'type' | 'flags'
| 'context' | 'click_count' | 'like_count' | 'owner' | 'name';
export interface LogRow {
id : number;
language : string;
context : string|null;
preprocessed : string;
target_code : string;
time : Date;
}
export type LogOptionalFields = 'language' | 'context' | 'time';
export interface SuggestionRow {
id : string;
command : string;
suggest_time : Date;
}
export type SuggestionOptionalFields = 'suggest_time';
export async function createMany(client : db.Client, examples : Array<db.WithoutID<db.Optional<Row, OptionalFields>>>, updateExisting : boolean) {
if (examples.length === 0)
return Promise.resolve();
const KEYS = ['id', 'schema_id', 'is_base', 'flags', 'language', 'utterance', 'preprocessed',
'target_json', 'target_code', 'context',
'type', 'click_count', 'like_count', 'owner', 'name'] as const;
const arrays : any[] = [];
examples.forEach((ex) => {
if (!ex.type)
ex.type = 'thingpedia';
if (ex.click_count === undefined)
ex.click_count = 1;
ex.like_count = 0;
const vals = KEYS.map((key) => {
return ex[key];
});
arrays.push(vals);
});
if (updateExisting) {
return db.insertOne(client, 'insert into example_utterances(' + KEYS.join(',') + ') '
+ `values ? on duplicate key update
utterance=values(utterance), preprocessed=values(preprocessed), context=values(context),
target_code=values(target_code), type=values(type), flags=values(flags), is_base=values(is_base)`,
[arrays]);
} else {
return db.insertOne(client, 'insert into example_utterances(' + KEYS.join(',') + ') '
+ 'values ?', [arrays]);
}
}
export async function create(client : db.Client, ex : db.WithoutID<db.Optional<Row, OptionalFields>>, updateExisting ?: boolean) {
if (!ex.type)
ex.type = 'thingpedia';
if (ex.click_count === undefined)
ex.click_count = 1;
if (updateExisting) {
return db.insertOne(client, `insert into example_utterances set ? on duplicate key update
utterance=values(utterance), preprocessed=values(preprocessed), context=values(context),
target_code=values(target_code), type=values(type), flags=values(flags), is_base=values(is_base)`,
[ex]);
} else {
return db.insertOne(client, 'insert into example_utterances set ?', [ex]);
}
}
export async function getAll(client : db.Client) : Promise<Row[]> {
console.error('example.getAll called, where is this from?');
return db.selectAll(client, "select * from example_utterances");
}
export type CommandRow = Pick<Row, "id"|"language"|"type"|"utterance"|"preprocessed"|"target_code"
|"click_count"|"like_count"|"is_base"> & {
kind ?: string|null;
owner_name : string|null;
liked ?: boolean;
devices ?: string[];
};
export type CommandRowForUser = CommandRow & { liked : boolean };
// The ForUser variants of getCommands and getCommandsByFuzzySearch
// return an additional column, "liked", which is a boolean indicating
// whether the named user liked the given command or not
// They are used to color the hearts in Commandpedia, if the user is logged in
export async function getCommandsForUser(client : db.Client, language : string, userId : number, start ?: number, end ?: number) : Promise<CommandRowForUser[]> {
const query = `
(select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,null as kind,u.username as owner_name,
(exists (select 1 from example_likes where example_id = eu.id and user_id = ?)) as liked
from example_utterances eu left join users u on u.id = eu.owner where
type = 'commandpedia' and language = ? and not find_in_set('replaced', flags)
and not find_in_set('augmented', flags) and not find_in_set('obsolete', flags)
) union all (
select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name,
(exists (select 1 from example_likes where example_id = eu.id and user_id = ?)) as liked
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where ds.id = eu.schema_id and type = 'thingpedia' and language = ? and ds.approved_version is not null
and is_base
) order by like_count desc,click_count desc,md5(utterance) asc`;
if (start !== undefined && end !== undefined)
return db.selectAll(client, `${query} limit ?,?`, [userId, language, userId, language, start, end + 1]);
else
return db.selectAll(client, query, [userId, language, userId, language]);
}
export async function getCommandsByFuzzySearchForUser(client : db.Client, language : string, userId : number, query : string) : Promise<CommandRowForUser[]> {
const regexp = '(^| )(' + stripUnsafeTokens(tokenize(query)).join('|') + ')( |$)';
return db.selectAll(client, `
(select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,null as kind,u.username as owner_name,
(exists (select 1 from example_likes where example_id = eu.id and user_id = ?)) as liked
from example_utterances eu left join users u on u.id = eu.owner where
type = 'commandpedia' and language = ? and not find_in_set('replaced', flags)
and not find_in_set('augmented', flags) and not find_in_set('obsolete', flags)
and ( utterance like ? or target_code like ?)
) union all (
select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name,
(exists (select 1 from example_likes where example_id = eu.id and user_id = ?)) as liked
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where eu.schema_id = ds.id and eu.is_base = 1 and eu.type = 'thingpedia' and language = ?
and preprocessed rlike (?) and target_code <> ''
) union distinct (
select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name,
(exists (select 1 from example_likes where example_id = eu.id and user_id = ?)) as liked
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where eu.schema_id = ds.id and eu.is_base = 1 and eu.type = 'thingpedia' and language = ?
and match kind_canonical against (?) and target_code <> ''
) order by like_count desc,click_count desc,md5(utterance) asc`, [userId, language, `%${query}%`, `%${query}%`,
userId, language, regexp, userId, language, query]);
}
export async function getCommands(client : db.Client, language : string, start ?: number, end ?: number) : Promise<CommandRow[]> {
const query = `
(select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,null as kind,u.username as owner_name
from example_utterances eu left join users u on u.id = eu.owner where
type = 'commandpedia' and language = ? and not find_in_set('replaced', flags)
and not find_in_set('augmented', flags) and not find_in_set('obsolete', flags)
) union all (
select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where ds.id = eu.schema_id and type = 'thingpedia' and language = ? and ds.approved_version is not null
and is_base
) order by like_count desc,click_count desc,md5(utterance) asc`;
if (start !== undefined && end !== undefined)
return db.selectAll(client, `${query} limit ?,?`, [language, language, start, end + 1]);
else
return db.selectAll(client, query, [language, language]);
}
export async function getCommandsByFuzzySearch(client : db.Client, language : string, query : string) : Promise<CommandRow[]> {
const regexp = '(^| )(' + stripUnsafeTokens(tokenize(query)).join('|') + ')( |$)';
return db.selectAll(client, `
(select eu.id,eu.language,eu.type,eu.utterance,
eu.preprocessed,eu.target_code,eu.click_count,eu.like_count,eu.is_base,null as kind,u.username as owner_name
from example_utterances eu left join users u on u.id = eu.owner where
type = 'commandpedia' and language = ? and not find_in_set('replaced', flags)
and not find_in_set('augmented', flags) and not find_in_set('obsolete', flags)
and ( utterance like ? or target_code like ?)
) union all (
select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where eu.schema_id = ds.id and eu.is_base = 1 and eu.type = 'thingpedia' and language = ?
and preprocessed rlike (?) and target_code <> ''
) union distinct (
select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.is_base,ds.kind,org.name as owner_name
from (example_utterances eu, device_schema ds) left join organizations org on org.id = ds.owner
where eu.schema_id = ds.id and eu.is_base = 1 and eu.type = 'thingpedia' and language = ?
and match kind_canonical against (?) and target_code <> ''
) order by like_count desc,click_count desc,md5(utterance) asc`, [language, `%${query}%`, `%${query}%`, language, regexp, language, query]);
}
export type CheatsheetRow = Pick<Row, "id"|"utterance"|"target_code"> & { kind : string };
export async function getCheatsheet(client : db.Client, language : string) : Promise<CheatsheetRow[]> {
return db.selectAll(client, `select eu.id,eu.utterance,eu.target_code,ds.kind
from example_utterances eu, device_schema ds where eu.schema_id = ds.id and
eu.is_base = 1 and eu.type = 'thingpedia' and language = ? and ds.approved_version is not null
order by click_count desc, id asc`,
[language]);
}
export type PrimitiveTemplateRow = Pick<Row, "id"|"language"|"type"|"utterance"|"preprocessed"|"target_code"|"click_count"|"like_count"|"name">;
export async function getBaseByLanguage(client : db.Client, org : number|null, language : string) : Promise<Array<Omit<PrimitiveTemplateRow, "type"|"language">>> {
if (org === -1) { // admin
return db.selectAll(client, `select eu.id,eu.utterance,eu.preprocessed,eu.target_code,
eu.click_count,eu.like_count,eu.name from example_utterances eu
where eu.is_base = 1 and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
order by id asc`,
[language]);
} else if (org !== null) {
return db.selectAll(client, `select eu.id,eu.utterance,eu.preprocessed,eu.target_code,
eu.click_count,eu.like_count,eu.name from example_utterances eu, device_schema ds
where eu.schema_id = ds.id and
eu.is_base = 1 and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and (ds.approved_version is not null or ds.owner = ?)
order by id asc`,
[language, org]);
} else {
return db.selectAll(client, `select eu.id,eu.utterance,eu.preprocessed,eu.target_code,
eu.click_count,eu.like_count,eu.name from example_utterances eu, device_schema ds
where eu.schema_id = ds.id and eu.is_base = 1 and eu.type = 'thingpedia' and
not find_in_set('synthetic', flags) and language = ? and ds.approved_version is not null
order by id asc`,
[language]);
}
}
export async function getByKey(client : db.Client, key : string, org : number|null, language : string) : Promise<PrimitiveTemplateRow[]> {
const regexp = '(^| )(' + stripUnsafeTokens(tokenize(key)).join('|') + ')( |$)';
if (org === -1) { // admin
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and preprocessed rlike (?) and target_code <> '')
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and match kind_canonical against (?) and target_code <> '')
order by id asc
limit 50`,
[language, regexp, language, key]);
} else if (org !== null) {
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and preprocessed rlike (?) and target_code <> ''
and (ds.approved_version is not null or ds.owner = ?))
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and match kind_canonical against (?) and target_code <> ''
and (ds.approved_version is not null or ds.owner = ?))
order by id asc
limit 50`,
[language, regexp, org, language, key, org]);
} else {
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and preprocessed rlike (?) and target_code <> ''
and ds.approved_version is not null)
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' and not find_in_set('synthetic', flags) and language = ?
and match kind_canonical against (?) and target_code <> ''
and ds.approved_version is not null)
order by id asc
limit 50`,
[language, regexp, language, key]);
}
}
export async function getByKinds(client : db.Client, kinds : string[], org : number|null, language : string, includeSynthetic ?: boolean) : Promise<PrimitiveTemplateRow[]> {
if (org === -1) { // admin
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and ds.kind in (?) and target_code <> '')
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds, device_class dc, device_class_kind dck where
eu.schema_id = ds.id and ds.kind = dck.kind and dck.device_id = dc.id
and not dck.is_child and dc.primary_kind in (?) ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and target_code <> '' and eu.type = 'thingpedia' and eu.is_base = 1)
order by id asc`,
[language, kinds, kinds, language]);
} else if (org !== null) {
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and ds.kind in (?) and target_code <> ''
and (ds.approved_version is not null or ds.owner = ?))
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds, device_class dc, device_class_kind dck where
eu.schema_id = ds.id and ds.kind = dck.kind and dck.device_id = dc.id
and not dck.is_child and dc.primary_kind in (?) ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and target_code <> '' and eu.type = 'thingpedia' and eu.is_base = 1
and (ds.approved_version is not null or ds.owner = ?)
and (dc.approved_version is not null or dc.owner = ?))
order by id asc`,
[language, kinds, org, kinds, language, org, org]);
} else {
return db.selectAll(client,
`(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds where eu.schema_id = ds.id and eu.is_base = 1
and eu.type = 'thingpedia' ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and ds.kind in (?) and target_code <> ''
and ds.approved_version is not null)
union distinct
(select eu.id,eu.language,eu.type,eu.utterance,eu.preprocessed,
eu.target_code,eu.click_count,eu.like_count,eu.name from example_utterances eu,
device_schema ds, device_class dc, device_class_kind dck where
eu.schema_id = ds.id and ds.kind = dck.kind and dck.device_id = dc.id
and not dck.is_child and dc.primary_kind in (?) ${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'} and language = ?
and target_code <> '' and eu.type = 'thingpedia' and eu.is_base = 1
and ds.approved_version is not null and dc.approved_version is not null)
order by id asc`,
[language, kinds, kinds, language]);
}
}
export async function getBaseBySchema(client : db.Client, schemaId : number, language : string, includeSynthetic ?: boolean) : Promise<Row[]> {
return db.selectAll(client, `select * from example_utterances use index(language_type)
where schema_id = ? and is_base and type = 'thingpedia' and language = ?
${includeSynthetic ? '' : 'and not find_in_set(\'synthetic\', flags)'}
order by id asc`, [schemaId, language]);
}
export async function getBaseBySchemaKind(client : db.Client, schemaKind : string, language : string) : Promise<Row[]> {
return db.selectAll(client, `select eu.* from example_utterances eu, device_schema ds where
eu.schema_id = ds.id and ds.kind = ? and is_base and type = 'thingpedia' and not find_in_set('synthetic', flags)
and language = ? order by id asc`
, [schemaKind, language]);
}
export function insertStream(client : db.Client, updateExisting : boolean) {
return new stream.Writable({
objectMode: true,
highWaterMark: 200,
write(obj, encoding, callback) {
create(client, obj, updateExisting).then(() => callback(), callback);
},
writev(objs, callback) {
createMany(client, objs.map((o) => o.chunk), updateExisting).then(() => callback(), callback);
}
});
}
export async function logUtterance(client : db.Client, data : db.WithoutID<db.Optional<LogRow, LogOptionalFields>>) {
return db.insertOne(client, `insert into utterance_log set ?`, [data]);
}
export async function deleteMany(client : db.Client, ids : number[]) {
if (ids.length === 0)
return;
await db.query(client, "delete from example_utterances where id in (?)", [ids]);
}
export async function deleteBySchema(client : db.Client, schemaId : number, language : string) {
await db.query(client, "delete from example_utterances where schema_id = ? and language = ?",
[schemaId, language]);
}
export async function update(client : db.Client, id : number, example : Partial<Row>) {
await db.query(client, "update example_utterances set ? where id = ?", [example, id]);
}
export async function click(client : db.Client, exampleId : number) {
await db.query(client, "update example_utterances set click_count = click_count + 1 where id = ?", [exampleId]);
}
export async function like(client : db.Client, userId : number, exampleId : number) {
const inserted = await db.insertIgnore(client, `insert ignore into example_likes(example_id, user_id) values (?, ?)`, [exampleId, userId]);
if (inserted)
await db.query(client, `update example_utterances set like_count = like_count + 1 where id = ?`, [exampleId]);
return inserted;
}
export async function unlike(client : db.Client, userId : number, exampleId : number) {
await db.query(client, `update example_utterances set like_count = like_count - 1 where id = ? and
exists (select 1 from example_likes where user_id = ? and example_id = ?)`, [exampleId, userId, exampleId]);
const [result,] = await db.query(client, `delete from example_likes where user_id = ? and example_id = ?`, [userId, exampleId]);
return result.affectedRows > 0;
}
export async function hide(client : db.Client, exampleId : number) {
await db.query(client, "update example_utterances set click_count = -1 where id = ?", [exampleId]);
}
export async function deleteById(client : db.Client, exampleId : number) {
await db.query(client, "delete from example_utterances where id = ?", [exampleId]);
}
export async function deleteAllLikesFromUser(client : db.Client, userId : number) {
await db.query(client, `update example_utterances set like_count = like_count - 1 where
exists (select 1 from example_likes where user_id = ? and example_id = id)`, [userId]);
await db.query(client, `delete from example_likes where user_id = ?`, [userId]);
}
export async function getTypes(client : db.Client) : Promise<Array<{ language : string, type : string, size : number }>> {
return db.selectAll(client, "select distinct language,type,count(*) as size from example_utterances group by language,type");
}
export async function getByType(client : db.Client, language : string, type : string, start : number, end : number) : Promise<Row[]> {
return db.selectAll(client, `select * from example_utterances where not is_base and
language = ? and type = ? and not find_in_set('replaced', flags)
and not find_in_set('augmented', flags) order by id desc limit ?,?`,
[language, type, start, end]);
}
export async function getByIntentName(client : db.Client, language : string, kind : string, name : string) : Promise<Row> {
return db.selectOne(client, `select ex.* from example_utterances ex, device_schema ds
where ds.id = ex.schema_id and ds.kind = ? and ex.language = ? and ex.name = ?`,
[kind, language, name]);
}
export async function getExact(client : db.Client, language : string) : Promise<Array<Pick<Row, "preprocessed"|"target_code">>> {
return db.selectAll(client, `select preprocessed,target_code from example_utterances use index (language_flags)
where language = ? and find_in_set('exact', flags) and not is_base and preprocessed <> ''
order by type asc, id asc`, [language]);
}
export async function getExactById(client : db.Client, exampleId : number) : Promise<Pick<Row, "preprocessed"|"target_code">> {
return db.selectOne(client, `select preprocessed,target_code from example_utterances where id = ?`, [exampleId]);
}
export async function suggest(client : db.Client, command : string) {
await db.query(client, "insert into command_suggestions (command) values (?)", [command]);
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/workspacesMappers";
import * as Parameters from "../models/parameters";
import { MachineLearningWorkspacesManagementClientContext } from "../machineLearningWorkspacesManagementClientContext";
/** Class representing a Workspaces. */
export class Workspaces {
private readonly client: MachineLearningWorkspacesManagementClientContext;
/**
* Create a Workspaces.
* @param {MachineLearningWorkspacesManagementClientContext} client Reference to the service client.
*/
constructor(client: MachineLearningWorkspacesManagementClientContext) {
this.client = client;
}
/**
* Gets the properties of the specified machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesGetResponse>
*/
get(resourceGroupName: string, workspaceName: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesGetResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param callback The callback
*/
get(resourceGroupName: string, workspaceName: string, callback: msRest.ServiceCallback<Models.Workspace>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, workspaceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Workspace>): void;
get(resourceGroupName: string, workspaceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Workspace>, callback?: msRest.ServiceCallback<Models.Workspace>): Promise<Models.WorkspacesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
workspaceName,
options
},
getOperationSpec,
callback) as Promise<Models.WorkspacesGetResponse>;
}
/**
* Creates or updates a workspace with the specified parameters.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for creating or updating a machine learning workspace.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: Models.Workspace, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for creating or updating a machine learning workspace.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: Models.Workspace, callback: msRest.ServiceCallback<Models.Workspace>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for creating or updating a machine learning workspace.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: Models.Workspace, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Workspace>): void;
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: Models.Workspace, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Workspace>, callback?: msRest.ServiceCallback<Models.Workspace>): Promise<Models.WorkspacesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
workspaceName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.WorkspacesCreateOrUpdateResponse>;
}
/**
* Deletes a machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, workspaceName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, workspaceName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, workspaceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, workspaceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
workspaceName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Updates a machine learning workspace with the specified parameters.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for updating a machine learning workspace.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesUpdateResponse>
*/
update(resourceGroupName: string, workspaceName: string, parameters: Models.WorkspaceUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for updating a machine learning workspace.
* @param callback The callback
*/
update(resourceGroupName: string, workspaceName: string, parameters: Models.WorkspaceUpdateParameters, callback: msRest.ServiceCallback<Models.Workspace>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param workspaceName The name of the machine learning workspace.
* @param parameters The parameters for updating a machine learning workspace.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, workspaceName: string, parameters: Models.WorkspaceUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Workspace>): void;
update(resourceGroupName: string, workspaceName: string, parameters: Models.WorkspaceUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Workspace>, callback?: msRest.ServiceCallback<Models.Workspace>): Promise<Models.WorkspacesUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
workspaceName,
parameters,
options
},
updateOperationSpec,
callback) as Promise<Models.WorkspacesUpdateResponse>;
}
/**
* Resync storage keys associated with this workspace.
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
resyncStorageKeys(workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param callback The callback
*/
resyncStorageKeys(workspaceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param options The optional parameters
* @param callback The callback
*/
resyncStorageKeys(workspaceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
resyncStorageKeys(workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
workspaceName,
resourceGroupName,
options
},
resyncStorageKeysOperationSpec,
callback);
}
/**
* List the authorization keys associated with this workspace.
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesListWorkspaceKeysResponse>
*/
listWorkspaceKeys(workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesListWorkspaceKeysResponse>;
/**
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param callback The callback
*/
listWorkspaceKeys(workspaceName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.WorkspaceKeysResponse>): void;
/**
* @param workspaceName The name of the machine learning workspace.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param options The optional parameters
* @param callback The callback
*/
listWorkspaceKeys(workspaceName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceKeysResponse>): void;
listWorkspaceKeys(workspaceName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceKeysResponse>, callback?: msRest.ServiceCallback<Models.WorkspaceKeysResponse>): Promise<Models.WorkspacesListWorkspaceKeysResponse> {
return this.client.sendOperationRequest(
{
workspaceName,
resourceGroupName,
options
},
listWorkspaceKeysOperationSpec,
callback) as Promise<Models.WorkspacesListWorkspaceKeysResponse>;
}
/**
* Lists all the available machine learning workspaces under the specified resource group.
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning workspace
* belongs.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceListResult>, callback?: msRest.ServiceCallback<Models.WorkspaceListResult>): Promise<Models.WorkspacesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.WorkspacesListByResourceGroupResponse>;
}
/**
* Lists all the available machine learning workspaces under the specified subscription.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceListResult>, callback?: msRest.ServiceCallback<Models.WorkspaceListResult>): Promise<Models.WorkspacesListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.WorkspacesListResponse>;
}
/**
* Lists all the available machine learning workspaces under the specified resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceListResult>, callback?: msRest.ServiceCallback<Models.WorkspaceListResult>): Promise<Models.WorkspacesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.WorkspacesListByResourceGroupNextResponse>;
}
/**
* Lists all the available machine learning workspaces under the specified subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.WorkspacesListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WorkspacesListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WorkspaceListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WorkspaceListResult>, callback?: msRest.ServiceCallback<Models.WorkspaceListResult>): Promise<Models.WorkspacesListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.WorkspacesListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.workspaceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Workspace
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.workspaceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Workspace,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Workspace
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.workspaceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.workspaceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.WorkspaceUpdateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Workspace
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const resyncStorageKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}/resyncStorageKeys",
urlParameters: [
Parameters.subscriptionId,
Parameters.workspaceName,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listWorkspaceKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces/{workspaceName}/listWorkspaceKeys",
urlParameters: [
Parameters.subscriptionId,
Parameters.workspaceName,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WorkspaceKeysResponse
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearning/workspaces",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WorkspaceListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearning/workspaces",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WorkspaceListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WorkspaceListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WorkspaceListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as React from "react";
import styles from "./ReactPnPjsTester.module.scss";
import { IReactPnPjsTesterProps } from "./IReactPnPjsTesterProps";
import { sp } from "@pnp/sp/presets/all";
import {
TextField,
Panel,
PanelType,
Checkbox,
Icon,
Dropdown,
TooltipHost,
DirectionalHint,
Toggle,
Stack,
} from "office-ui-fabric-react";
// import AceEditor from "react-ace";
import { DefaultButton, ActionButton, IconButton } from "office-ui-fabric-react/lib/Button";
// import "ace-builds/src-noconflict/mode-json";
// import "ace-builds/src-noconflict/theme-github";
import ReactJson from "react-json-view";
const samples:ISamples = require("./Samples.json");
export interface ISamples{
samples:any[];
}
export interface IReactPnPjsTesterState {
jsonResponse: any;
pnpCommand: any;
displayDataTypes: boolean;
displayObjectSize: boolean;
enableClipboard: boolean;
openPanel: boolean;
isError: boolean;
errorMessage: any;
siteUrl: string;
isUpdate: boolean;
showAddUpdateInformation: boolean;
defaultCollapsed: boolean;
requestType: string;
isOtherSite: boolean;
}
var spObj = null;
export default class ReactPnPjsTester extends React.Component<
IReactPnPjsTesterProps,
IReactPnPjsTesterState
> {
private addCommand =
'sp.web.lists.getByTitle("CustomList").items.add({Title: "PnpJS Explorer"})';
private exampleJson = samples.samples;
// constructor to intialize state and pnp sp object.
constructor(props: IReactPnPjsTesterProps, state: IReactPnPjsTesterState) {
super(props);
this.state = {
requestType: "GET",
jsonResponse: null,
pnpCommand: null,
displayDataTypes: false,
displayObjectSize: false,
enableClipboard: false,
openPanel: false,
isError: false,
errorMessage: null,
siteUrl: "",
isUpdate: false,
showAddUpdateInformation: false,
defaultCollapsed: false,
isOtherSite: false,
};
}
private _reqBodyChanged = (val: string) => {
// this.setState({
// jsonResponse: val,
// });
}
public render(): React.ReactElement<IReactPnPjsTesterProps> {
return (
<div className={styles.reactPnPjsTester}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<TooltipHost
content="This webpart will allow SPFx developers to test PnPjs Sharepoint methods and it displays response in JSON viewer to identify properties/attributes returned by method"
id="tooltip"
directionalHint={DirectionalHint.rightCenter}
calloutProps={{ gapSpace: 0 }}
styles={{ root: { display: "inline-block" } }}
>
<h2 style={{ cursor: "pointer" }}>PnPjs Tester
<IconButton iconProps={{ iconName: 'InfoSolid' }} title="InfoSolid" ariaLabel="InfoSolid" />
</h2>
</TooltipHost>
</div>
</div>
<div className={styles.row}>
<div className={styles.col1}>
<Dropdown
selectedKey={this.state.requestType}
onChanged={(val) => {
let isUpdate = val.key === "POST" ? true : false;
this.setState({ isUpdate: isUpdate, requestType: val.text });
}}
className={styles.methodSelector}
options={[
{ key: "GET", text: "GET" },
{ key: "POST", text: "POST" },
]}
/>
</div>
<div className={styles.col11}>
<TextField
value={this.state.pnpCommand}
placeholder="Enter your query here e.g. sp.web.select('Title')"
onChange={(e) => this.setCommand(e.target)}
/>
</div>
</div>
<div className={styles.row}>
<div className={styles.column}>
<Checkbox
label="Use for other Site collection or Subsite"
onChange={(event, checked) => {
this.setState({ isOtherSite: checked });
}}
/>
</div>
<div
className={styles.column}
style={{
display: this.state.isOtherSite ? "block" : "none",
marginTop: 10,
}}
>
<TextField
placeholder="Enter site collection or subsite url"
value={this.state.siteUrl}
onChange={(e) => this.setSiteUrl(e.target)}
/>
</div>
</div>
<div className={styles.row}>
<div className={styles.column}>
<Panel
isLightDismiss
isOpen={this.state.openPanel}
headerText="Samples"
closeButtonAriaLabel="Close"
type={PanelType.custom}
customWidth={"600px"}
>
<p>{this.getPanelCommands()}</p>
</Panel>
<DefaultButton
onClick={() => this.executeCommand()}
className={styles.button}
>
<Icon className={styles.icon} iconName="LightningBolt" /> Run
query
</DefaultButton>
<DefaultButton
onClick={() => {
this.setState({ openPanel: true });
}}
className={styles.button}
>
<Icon className={styles.icon} iconName="ReadingMode"></Icon>
Samples
</DefaultButton>
<DefaultButton
onClick={() => {
window.open("https://pnp.github.io/pnpjs/sp/", "__blank");
}}
className={styles.button}
>
<Icon className={styles.icon} iconName="Info"></Icon>About PnPjs
</DefaultButton>
{this.state.jsonResponse && (
<div>
{/* <Checkbox
label="Wrap code"
className={styles.collapse}
onChange={() => this.onCollapseAll()}
checked={this.state.defaultCollapsed}
/> */}
<br></br>
{this.state.jsonResponse &&
<React.Fragment>
<Stack horizontal tokens={{ childrenGap: 25 }}>
<Toggle checked={this.state.displayDataTypes} label="Show Data Types" inlineLabel onChange={() => { this.setState({ displayDataTypes: !this.state.displayDataTypes }); }} />
<Toggle checked={this.state.displayObjectSize} label="Show Count" inlineLabel onChange={() => { this.setState({ displayObjectSize: !this.state.displayObjectSize }); }} />
<Toggle checked={this.state.enableClipboard} label="Enable Clipboard" inlineLabel onChange={() => { this.setState({ enableClipboard: !this.state.enableClipboard }); }}/>
<Toggle checked={this.state.defaultCollapsed} label="Collapse All" inlineLabel onChange={()=>this.onCollapseAll()}/>
{/* <Checkbox className={styles.collapse} label="Collapse All" /> */}
</Stack>
<div className={styles.jsonviewcont}>
<ReactJson src={this.state.jsonResponse} collapsed={this.state.defaultCollapsed} displayDataTypes={this.state.displayDataTypes} displayObjectSize={this.state.displayObjectSize} enableClipboard={this.state.enableClipboard} />
</div>
</React.Fragment>
}
{this.state.errorMessage &&
<div>{JSON.stringify(this.state.errorMessage)} </div>
}
{/* <AceEditor
mode="json"
theme="github"
className={styles.codeZone}
value={JSON.stringify(this.state.jsonResponse, null, 2)}
onChange={this._reqBodyChanged}
highlightActiveLine={true}
editorProps={{ $blockScrolling: true }}
setOptions={{
wrap: this.state.defaultCollapsed,
showPrintMargin: false,
}}
height="500px"
width="100%"
/> */}
</div>
)}
{this.state.errorMessage && (
<div>{JSON.stringify(this.state.errorMessage)} </div>
)}
</div>
</div>
</div>
</div>
);
}
private onCollapseAll = () => {
this.setState({ defaultCollapsed: !this.state.defaultCollapsed });
}
private setCommand = (element) => {
var val = (element as HTMLInputElement).value;
this.setState({ pnpCommand: val });
}
private setSiteUrl = (element) => {
var val = (element as HTMLInputElement).value;
this.setState({ siteUrl: val });
}
private setPnP = () => {
spObj = null;
if (this.state.siteUrl != "" && this.state.isOtherSite) {
sp.setup({
sp: {
headers: {
Accept: "application/json;odata=minimalmetadata",
},
baseUrl: this.state.siteUrl,
},
});
} else {
sp.setup({
spfxContext: this.props.spcontext
});
}
spObj = sp;
}
private executeCommand() {
this.setPnP();
this.setState({ jsonResponse: null, errorMessage: null,openPanel:false });
var command = this.state.pnpCommand;
command = command.replace("sp", "spObj");
command = command.replace(/"/g, "'");
command = command.replace(".get()", "");
command = command.replace(";", "");
command = command.replace("()", "");
var evalString = "try{" + command;
if (!this.state.isUpdate) {
evalString += "()";
}
evalString +=
".then(\
(result) => {\
debugger;\
console.log(result);\
this.setState({jsonResponse:result});\
}\
)\
.catch(\
(error) => {\
debugger;\
console.log(error);\
this.setState({jsonResponse:{error:error.message}});\
}\
);\
}\
catch(e){\
alert(e);\
}";
eval(evalString);
}
private getPanelCommands = () => {
return (
<React.Fragment>
{this.exampleJson.map((item: any, index: number) => (
<div>
<ActionButton
onClick={() => {
this.setState({ pnpCommand: item.command, openPanel: false });
}}
iconProps={{ iconName: "Copy" }}
title="Copy"
ariaLabel="Copy"
>
{item.command}
</ActionButton>
</div>
))}
</React.Fragment>
);
}
} | the_stack |
import { type ComputedRef, type Slots, type VNode, computed, reactive, ref, watchEffect } from 'vue'
import { isNil } from 'lodash-es'
import { type BreakpointKey, useSharedBreakpoints } from '@idux/cdk/breakpoint'
import { type VKey, convertArray, flattenNode } from '@idux/cdk/utils'
import { type TableColumnBaseConfig, type TableColumnExpandableConfig, type TableConfig } from '@idux/components/config'
import { tableColumnKey } from '../column'
import {
type TableColumn,
type TableColumnAlign,
type TableColumnBase,
type TableColumnExpandable,
type TableColumnFixed,
type TableColumnSelectable,
type TableProps,
} from '../types'
export function useColumns(
props: TableProps,
slots: Slots,
config: TableConfig,
scrollBarSizeOnFixedHolder: ComputedRef<number>,
): ColumnsContext {
const breakpoints = useSharedBreakpoints()
const mergedColumns = computed(() => {
const { columns } = props
if (columns && columns.length > 0) {
return mergeColumns(props.columns, breakpoints, config.columnBase, config.columnExpandable)
} else {
return mergeColumns(convertColumns(slots.default?.()), breakpoints, config.columnBase, config.columnExpandable)
}
})
const { flattedColumns, scrollBarColumn, flattedColumnsWithScrollBar } = useFlattedColumns(
mergedColumns,
scrollBarSizeOnFixedHolder,
)
const fixedColumnKeys = useFixedColumnKeys(flattedColumnsWithScrollBar)
const hasEllipsis = computed(() => flattedColumns.value.some(column => (column as TableColumnBase).ellipsis))
const hasFixed = computed(() => flattedColumns.value.some(column => column.fixed))
const { columnWidths, columnWidthsWithScrollBar, changeColumnWidth } = useColumnWidths(
flattedColumns,
scrollBarColumn,
)
const { columnOffsets, columnOffsetsWithScrollBar } = useColumnOffsets(columnWidths, columnWidthsWithScrollBar)
const mergedRows = computed(() => mergeRows(mergedColumns.value, scrollBarColumn.value))
return {
flattedColumns,
scrollBarColumn,
flattedColumnsWithScrollBar,
fixedColumnKeys,
hasEllipsis,
hasFixed,
columnWidths,
columnWidthsWithScrollBar,
changeColumnWidth,
columnOffsets,
columnOffsetsWithScrollBar,
mergedRows,
}
}
export interface ColumnsContext {
flattedColumns: ComputedRef<TableColumnMerged[]>
scrollBarColumn: ComputedRef<TableColumnScrollBar | undefined>
flattedColumnsWithScrollBar: ComputedRef<(TableColumnMerged | TableColumnScrollBar)[]>
fixedColumnKeys: ComputedRef<{
lastStartKey: VKey | undefined
firstEndKey: VKey | undefined
}>
hasEllipsis: ComputedRef<boolean>
hasFixed: ComputedRef<boolean>
columnWidths: ComputedRef<number[]>
columnWidthsWithScrollBar: ComputedRef<number[]>
changeColumnWidth: (key: VKey, width: number | false) => void
columnOffsets: ComputedRef<{ starts: number[]; ends: number[] }>
columnOffsetsWithScrollBar: ComputedRef<{ starts: number[]; ends: number[] }>
mergedRows: ComputedRef<TableColumnMergedExtra[][]>
}
export type TableColumnMerged = TableColumnMergedBase | TableColumnMergedExpandable | TableColumnMergedSelectable
export type TableColumnMergedExtra =
| TableColumnMergedBaseExtra
| TableColumnMergedExpandable
| TableColumnMergedSelectable
| TableColumnMergedScrollBar
export interface TableColumnMergedBase extends TableColumnBase {
align: TableColumnAlign
key: VKey
}
export interface TableColumnMergedBaseExtra extends TableColumnMergedBase {
colStart: number
colEnd: number
hasChildren: boolean
titleColSpan: number
titleRowSpan?: number
}
export interface TableColumnMergedExpandable extends TableColumnMergedBaseExtra, TableColumnExpandable {
align: TableColumnAlign
key: VKey
icon: string
titleColSpan: number
}
export interface TableColumnMergedSelectable extends TableColumnMergedBaseExtra, TableColumnSelectable {
align: TableColumnAlign
key: VKey
multiple: boolean
titleColSpan: number
}
export interface TableColumnScrollBar {
key: string
type: 'scroll-bar'
fixed: TableColumnFixed | undefined
width: number
}
export type TableColumnMergedScrollBar = TableColumnMergedBaseExtra & TableColumnScrollBar
function mergeColumns(
columns: TableColumn[],
breakpoints: Record<BreakpointKey, boolean>,
baseConfig: TableColumnBaseConfig,
expandableConfig: TableColumnExpandableConfig,
): TableColumnMerged[] {
return columns
.filter(column => !column.responsive || column.responsive.some(key => breakpoints[key]))
.map((column, index) => covertColumn(column, breakpoints, baseConfig, expandableConfig, index))
}
function convertColumns(nodes: VNode[] | undefined) {
const columns: Array<TableColumn> = []
flattenNode(nodes, { key: tableColumnKey }).forEach((node, index) => {
const { props, children } = node
const { key = index, editable, ellipsis, ...newColumn } = props || {}
newColumn.key = key
newColumn.editable = editable || editable === ''
newColumn.editable = ellipsis || ellipsis === ''
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { default: defaultSlot, cell, title, expand, icon } = (children || {}) as any
if (defaultSlot) {
newColumn.children = convertColumns(defaultSlot())
}
if (cell) {
newColumn.customCell = cell
}
if (title) {
newColumn.customTitle = title
}
if (expand) {
newColumn.customExpand = expand
}
if (icon) {
newColumn.customIcon = icon
}
columns.push(newColumn as TableColumn)
})
return columns
}
function covertColumn(
column: TableColumn,
breakpoints: Record<BreakpointKey, boolean>,
baseConfig: TableColumnBaseConfig,
expandableConfig: TableColumnExpandableConfig,
index: number,
): TableColumnMerged {
const { align = baseConfig.align } = column
if ('type' in column) {
const key = `IDUX_TABLE_KEY_${column.type}`
if (column.type === 'expandable') {
const { icon = expandableConfig.icon } = column
return { ...column, key, align, icon }
} else {
// The default value for `multiple` is true
const multiple = column.multiple ?? true
return { ...column, key, align, multiple }
}
} else {
const { key, dataKey, sortable, filterable, children } = column
const _key = key ?? (convertArray(dataKey).join('-') || `'IDUX_TABLE_KEY_${index}`)
const newColumn = { ...column, key: _key, align }
if (sortable) {
newColumn.sortable = { ...baseConfig.sortable, ...sortable }
}
if (filterable) {
newColumn.filterable = { ...baseConfig.filterable, ...filterable }
}
if (children?.length) {
newColumn.children = mergeColumns(children, breakpoints, baseConfig, expandableConfig)
}
return newColumn
}
}
function useFlattedColumns(
mergedColumns: ComputedRef<TableColumnMerged[]>,
scrollBarSizeOnFixedHolder: ComputedRef<number>,
) {
const flattedColumns = computed(() => flatColumns(mergedColumns.value))
const scrollBarColumn = computed<TableColumnScrollBar | undefined>(() => {
const scrollBarSize = scrollBarSizeOnFixedHolder.value
if (scrollBarSize === 0) {
return undefined
}
const columns = flattedColumns.value
const lastColumn = columns[columns.length - 1]
return {
key: 'IDUX_TABLE_KEY_scroll-bar',
type: 'scroll-bar',
fixed: lastColumn && lastColumn.fixed,
width: scrollBarSize,
}
})
const flattedColumnsWithScrollBar = computed(() => {
const columns = flattedColumns.value
if (columns.length === 0) {
return columns
}
const scrollBar = scrollBarColumn.value
return scrollBar ? [...columns, scrollBar] : columns
})
return { flattedColumns, scrollBarColumn, flattedColumnsWithScrollBar }
}
function flatColumns(columns: TableColumnMerged[]) {
const result: TableColumnMerged[] = []
columns.forEach(column => {
const { fixed, children: subColumns } = column as TableColumnBase
if (subColumns?.length) {
let subFlattedColumns = flatColumns(subColumns as TableColumnMerged[])
if (fixed) {
subFlattedColumns = subFlattedColumns.map(item => ({ fixed, ...item }))
}
result.push(...subFlattedColumns)
} else {
result.push(column)
}
})
return result
}
function useFixedColumnKeys(flattedColumnsWithScrollBar: ComputedRef<(TableColumnMerged | TableColumnScrollBar)[]>) {
return computed(() => {
let lastStartKey: VKey | undefined
let firstEndKey: VKey | undefined
flattedColumnsWithScrollBar.value.forEach(column => {
const { fixed, key } = column
if (fixed === 'start') {
lastStartKey = key
} else if (fixed === 'end') {
if (!firstEndKey) {
firstEndKey = key
}
}
})
return { lastStartKey, firstEndKey }
})
}
function useColumnWidths(
flattedColumns: ComputedRef<TableColumnMerged[]>,
scrollBarColumn: ComputedRef<TableColumnScrollBar | undefined>,
) {
const widthMap = reactive<Record<VKey, number>>({})
const widthString = ref<string>()
watchEffect(() => {
const keys = Object.keys(widthMap)
const columns = flattedColumns.value
if (keys.length !== columns.length) {
widthString.value = undefined
return
}
widthString.value = columns.map(column => widthMap[column.key]).join('-')
})
const columnWidths = computed(() => {
const _widthString = widthString.value
return _widthString ? _widthString.split('-').map(Number) : []
})
const columnWidthsWithScrollBar = computed(() => {
const widths = columnWidths.value
if (widths.length === 0) {
return widths
}
const scrollBar = scrollBarColumn.value
return scrollBar ? [...widths, scrollBar.width] : widths
})
const changeColumnWidth = (key: VKey, width: number | false) => {
if (width === false) {
delete widthMap[key]
} else {
widthMap[key] = width
}
}
return { columnWidths, columnWidthsWithScrollBar, changeColumnWidth }
}
function useColumnOffsets(columnWidths: ComputedRef<number[]>, columnWidthsWithScrollBar: ComputedRef<number[]>) {
const columnOffsets = computed(() => calculateOffsets(columnWidths.value))
const columnOffsetsWithScrollBar = computed(() => calculateOffsets(columnWidthsWithScrollBar.value))
return { columnOffsets, columnOffsetsWithScrollBar }
}
function calculateOffsets(widths: number[]) {
const count = widths.length
const startOffsets: number[] = []
const endOffsets: number[] = []
let startOffset = 0
let endOffset = 0
for (let start = 0; start < count; start++) {
// Start offset
startOffsets[start] = startOffset
startOffset += widths[start] || 0
// End offset
const end = count - start - 1
endOffsets[end] = endOffset
endOffset += widths[end] || 0
}
return {
starts: startOffsets,
ends: endOffsets,
}
}
function mergeRows(mergedColumns: TableColumnMerged[], scrollBarColumn: TableColumnScrollBar | undefined) {
const rows: TableColumnMergedExtra[][] = []
function calculateColSpans(columns: TableColumnMerged[], colIndex: number, rowIndex: number) {
rows[rowIndex] ??= []
let colStart = colIndex
const titleColSpans = columns.map(column => {
let titleColSpan = (column as TableColumnMergedBase).titleColSpan ?? 1
let hasChildren = false
const subColumns = (column as TableColumnMergedBase).children as TableColumnMerged[] | undefined
if (subColumns?.length) {
hasChildren = true
const subColumnSpans = calculateColSpans(subColumns, colStart, rowIndex + 1)
if (isNil((column as TableColumnMergedBase).titleColSpan)) {
titleColSpan = subColumnSpans.reduce((total, count) => total + count)
}
}
const colEnd = colStart + titleColSpan - 1
rows[rowIndex].push({ ...column, titleColSpan, colStart, colEnd, hasChildren } as TableColumnMergedExtra)
colStart += titleColSpan
return titleColSpan
})
return titleColSpans
}
const rootColumns = scrollBarColumn
? [...mergedColumns, scrollBarColumn as unknown as TableColumnMerged]
: mergedColumns
calculateColSpans(rootColumns, 0, 0)
const rowCount = rows.length
rows.forEach((columns, rowIndex) => {
columns.forEach(col => {
if (!col.hasChildren) {
col.titleRowSpan = rowCount - rowIndex
}
})
})
return rows
} | the_stack |
import { ClassType, getObjectKeysSize, isArray } from '@deepkit/core';
import { ClassSchema, getClassSchema, plainToClass, t, ValidationFailed } from '@deepkit/type';
import { AppModule } from '@deepkit/app';
import { http, httpClass, JSONResponse } from '@deepkit/http';
import { Database, DatabaseRegistry, Query, UniqueConstraintFailure } from '@deepkit/orm';
import { PropertySchema } from '../../type';
function applySelect(query: Query<any>, select: string[] | string): Query<any> {
const names: string[] = isArray(select) ? select.map(v => v.trim()) : select.replace(/\s+/g, '').split(',');
try {
return query.select(...names);
} catch (error) {
throw ValidationFailed.from([{ message: String(error.message), path: 'select', code: 'invalid_select' }]);
}
}
function applyJoins(query: Query<any>, joins: { [name: string]: string }): Query<any> {
for (const [field, projection] of Object.entries(joins)) {
if (!query.classSchema.hasProperty(field)) throw new Error(`Join '${field}' does not exist`);
let join = query.useJoinWith(field);
if (projection.length && projection !== '*') {
join = join.select(...projection.split(','));
}
query = join.end();
}
return query;
}
interface AutoCrudOptions {
/**
* To limit the route generation to a subset of operations, specify an array of
* 'create' | 'read' | 'readMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany'.
*
* ```typescript
* {limitOperations: ['create', 'read', 'readMany']}
* ```
*/
limitOperations?: ('create' | 'read' | 'readMany' | 'update' | 'updateMany' | 'delete' | 'deleteMany')[];
/**
* Defaults to the primary key.
* If you have an additional unique field, you can specify here its name.
*/
identifier?: string;
/**
* Per default all fields are selectable in list/get routes.
*
* Specify each field to limit the selection.
*/
selectableFields?: string[];
/**
* Per default all fields are sortable in list/get routes.
*
* Specify each field to limit the selection.
*/
sortFields?: string[];
/**
* Per default the identifier/primary key can not be changed.
*
* Set this to true to allow it.
*/
identifierChangeable?: true;
/**
* Per default all joins are selectable in list/get routes.
*
* Specify each field to limit the selection.
*/
joins?: string[];
/**
* Per default max is 1000.
*/
maxLimit?: number;
/**
* Per default limit is 30.
*/
defaultLimit?: number;
}
function createController(schema: ClassSchema, options: AutoCrudOptions = {}): ClassType {
if (!schema.name) throw new Error(`Class ${schema.getClassName()} needs an entity name via @entity.name()`);
const joinNames: string[] = options.joins || schema.getProperties().filter(v => v.isReference || v.backReference).map(v => v.name);
const sortNames: string[] = options.sortFields || schema.getProperties().filter(v => !v.isReference && !v.backReference).map(v => v.name);
const selectNames: string[] = options.selectableFields || schema.getProperties().filter(v => !v.isReference && !v.backReference).map(v => v.name);
const identifier = options.identifier ? schema.getProperty(options.identifier) : schema.getPrimaryField();
interface ListQuery {
filter?: Partial<any>;
select?: string;
orderBy: { [name: string]: 'asc' | 'desc' };
joins?: { [name: string]: string };
offset: number;
limit: number;
}
let listQuery = t.schema({
filter: t.partial(schema).optional,
select: t.union(t.array(t.union(...selectNames)), t.string.name('fields')).description('List of or string of comma separated field names').optional,
orderBy: t.map(t.union('asc', 'desc'), t.union(...sortNames)).default({}),
offset: t.number.default(0).positive(),
limit: t.number.default(0).positive().maximum(options.maxLimit || 1000),
});
interface GetQuery {
select?: string;
joins?: { [name: string]: string };
}
let getQuery = t.schema({
select: t.union(t.array(t.union(...selectNames)), t.string).description('List of or string of comma separated field names').optional,
});
if (joinNames.length) {
const joins = t.map(t.string, t.union(...joinNames)).description('Each entry with field names, comma separated, or all with *').optional;
listQuery.addProperty('joins', joins);
getQuery.addProperty('joins', joins);
}
const createDto = schema.getPrimaryField().isAutoIncrement ? schema.exclude(schema.getPrimaryField().name) : schema;
const error = t.schema({
message: t.string,
});
const identifierChangeable = options && options.identifierChangeable ? true : false;
function applyIdentifier(target: object, property: PropertySchema) {
identifier.clone(property);
}
@http.controller('/entity/' + schema.name).group('crud')
class RestController {
constructor(protected registry: DatabaseRegistry) {
}
protected getDatabase(): Database {
return this.registry.getDatabaseForEntity(schema);
}
@http.GET('')
.description(`A list of ${schema.name}.`)
.response(200, `List of ${schema.name}.`, t.array(schema))
.response(400, `When parameter validation failed.`, ValidationFailed)
async readMany(@t.type(listQuery) @http.queries() listQuery: ListQuery) {
listQuery.limit = Math.min(options.maxLimit || 1000, listQuery.limit || options.defaultLimit || 30);
let query = this.getDatabase().query(schema);
if (listQuery.joins) query = applyJoins(query, listQuery.joins);
if (listQuery.select) query = applySelect(query, listQuery.select);
if (getObjectKeysSize(listQuery.orderBy) > 0) {
for (const field of Object.keys(listQuery.orderBy)) {
if (!schema.hasProperty(field)) throw new Error(`Can not order by '${field}' since it does not exist.`);
}
query.model.sort = listQuery.orderBy;
}
return await query
.filter(listQuery.filter)
.limit(listQuery.limit ? listQuery.limit : undefined)
.skip(listQuery.offset)
.find();
}
@http.POST('')
.description(`Add a new ${schema.name}.`)
.response(201, 'When successfully created.', schema)
.response(400, `When parameter validation failed`, ValidationFailed)
.response(409, 'When unique entity already exists.', error)
async create(@t.type(createDto) @http.body() body: any) {
//body is automatically validated
const item = plainToClass(schema, body);
try {
await this.getDatabase().persist(item);
} catch (e) {
if (e instanceof UniqueConstraintFailure) {
return new JSONResponse({ message: `This ${schema.name} already exists` }).status(409);
}
throw e;
}
return new JSONResponse(item).status(201);
}
@http.DELETE(':' + identifier.name)
.description(`Delete a single ${schema.name}.`)
.response(400, `When parameter validation failed`, ValidationFailed)
.response(200, `When deletion was successful`, t.type({ deleted: t.number }))
async delete(@t.use(applyIdentifier).description(`The identifier of ${schema.name}`) id: any) {
const result = await this.getDatabase().query(schema).filter({ [identifier.name]: id }).deleteOne();
return { deleted: result.modified };
}
@http.GET(':' + identifier.name)
.description(`Get a single ${schema.name}.`)
.response(200, `When ${schema.name} was found.`, schema)
.response(400, `When parameter validation failed`, ValidationFailed)
.response(404, `When ${schema.name} was not found.`, error)
async read(
@t.use(applyIdentifier).description(`The identifier of ${schema.name}`) id: any,
@t.type(getQuery) @http.queries() options: GetQuery
) {
let query = this.getDatabase().query(schema).filter({ [identifier.name]: id });
if (options.select) query = applySelect(query, options.select);
if (options.joins) query = applyJoins(query, options.joins);
const item = await query.findOneOrUndefined();
if (item) return item;
return new JSONResponse({ message: `${schema.name} not found` }).status(404);
}
@http.PUT(':' + identifier.name)
.description(`Update a single ${schema.name}.`)
.response(200, `When ${schema.name} was successfully updated.`, schema)
.response(400, `When parameter validation failed`, ValidationFailed)
.response(404, `When ${schema.name} was not found.`, error)
@t.type(schema)
async update(
@t.use(applyIdentifier).description(`The identifier of ${schema.name}`) id: any,
@t.type(createDto) @http.body() body: any
) {
let query = this.getDatabase().query(schema).filter({ [identifier.name]: id });
const item = await query.findOneOrUndefined();
if (!item) return new JSONResponse({ message: `${schema.name} not found` }).status(404);
if (!identifierChangeable && identifier.name in body) delete body[identifier.name];
Object.assign(item, body);
await this.getDatabase().persist(item);
return item;
}
}
Object.defineProperty(RestController, 'name', { value: 'RestController' + schema.getClassName() });
if (options.limitOperations) {
const data = httpClass._fetch(RestController);
if (!data) throw new Error('httpClass has no RestController');
for (const action of data.actions) {
if (!options.limitOperations.includes(action.methodName as any)) {
data.removeAction(action.methodName);
}
}
}
return RestController;
}
export class CrudAppModule<T> extends AppModule<T> {}
/**
* Create a module that provides CRUD routes for given entities.
*/
export function createCrudRoutes(schemas: (ClassType | ClassSchema)[], options: AutoCrudOptions = {}) {
const controllers = schemas.map(getClassSchema).map(v => createController(v, options));
return new CrudAppModule({
controllers: controllers
}, 'autoCrud');
} | the_stack |
import { PdfQRBarcodeValues } from './qr-barcode-values';
import { QRCodeVersion, ErrorCorrectionLevel } from '../barcode/enum/enum';
/**
* Qrcode used to calculate the Qrcode control
*/
export class ErrorCorrectionCodewords {
/**
* Holds the length
*/
private mLength: number;
/**
* Holds the Error Correction Code Word
*/
private eccw: number;
/**
* Holds the databits
*/
private databits: number;
/**
* Holds the Data Code word
*/
private mDataCodeWord: string[];
/**
* Holds G(x)
*/
private gx: number[];
/**
* Holds all the values of Alpha
*/
private alpha: number[] = [1, 2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19, 38, 76, 152, 45, 90, 180, 117, 234, 201, 143,
3, 6, 12, 24, 48, 96, 192, 157, 39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238, 193, 159, 35, 70, 140, 5, 10, 20, 40, 80,
160, 93, 186, 105, 210, 185, 111, 222, 161, 95, 190, 97, 194, 153, 47, 94, 188, 101, 202, 137, 15, 30, 60, 120, 240, 253, 231,
211, 187, 107, 214, 177, 127, 254, 225, 223, 163, 91, 182, 113, 226, 217, 175, 67, 134, 17, 34, 68, 136, 13, 26, 52, 104, 208,
189, 103, 206, 129, 31, 62, 124, 248, 237, 199, 147, 59, 118, 236, 197, 151, 51, 102, 204, 133, 23, 46, 92, 184, 109, 218, 169,
79, 158, 33, 66, 132, 21, 42, 84, 168, 77, 154, 41, 82, 164, 85, 170, 73, 146, 57, 114, 228, 213, 183, 115, 230, 209, 191, 99,
198, 145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255, 227, 219, 171, 75, 150, 49, 98, 196, 149, 55, 110, 220, 165, 87,
174, 65, 130, 25, 50, 100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166, 81, 162, 89, 178, 121, 242, 249, 239, 195,
155, 43, 86, 172, 69, 138, 9, 18, 36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22, 44, 88, 176, 125,
250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142];
/**
* Holds the Decimal value
*/
private decimalValue: number[];
/**
* Holds the values of QR Barcode
*/
private mQrBarcodeValues: PdfQRBarcodeValues;
/**
* Sets and Gets the Data code word
*
* @param {string} value - Sets and Gets the Data code word
* @private
*/
public set DC(value: string[]) {
this.mDataCodeWord = value;
}
/**
* Sets and Gets the DataBits
*
* @param {string} value - Sets and Gets the DataBits
* @private
*/
public set DataBits(value: number) {
this.databits = value;
}
/**
* Sets and Gets the Error Correction Code Words
*
* @param {string} value - Sets and Gets the Error Correction Code Words
* @private
*/
public set Eccw(value: number) {
this.eccw = value;
}
/**
* Initializes Error correction code word
*
* @param {QRCodeVersion} version - version of the qr code
* @param {ErrorCorrectionLevel} correctionLevel - defines the level of error correction.
*/
constructor(version: QRCodeVersion, correctionLevel: ErrorCorrectionLevel) {
this.mQrBarcodeValues = new PdfQRBarcodeValues(version, correctionLevel);
let variable: string = 'DataCapacity';
this.mLength = this.mQrBarcodeValues[variable];
variable = 'NumberOfErrorCorrectingCodeWords';
this.eccw = this.mQrBarcodeValues[variable];
}
/**
* Gets the Error correction code word
*
* @returns { number} Gets the Error correction code word
* @private
*/
public getErcw(): string[] {
//const decimalRepresentation: number[];
//let ecw: string[];
this.decimalValue = [this.databits];
switch (this.eccw) {
case 7:
this.gx = [0, 87, 229, 146, 149, 238, 102, 21];
break;
case 10:
this.gx = [0, 251, 67, 46, 61, 118, 70, 64, 94, 32, 45];
break;
case 13:
this.gx = [0, 74, 152, 176, 100, 86, 100, 106, 104, 130, 218, 206, 140, 78];
break;
case 15:
this.gx = [0, 8, 183, 61, 91, 202, 37, 51, 58, 58, 237, 140, 124, 5, 99, 105];
break;
case 16:
this.gx = [0, 120, 104, 107, 109, 102, 161, 76, 3, 91, 191, 147, 169, 182, 194, 225, 120];
break;
case 17:
this.gx = [0, 43, 139, 206, 78, 43, 239, 123, 206, 214, 147, 24, 99, 150, 39, 243, 163, 136];
break;
case 18:
this.gx = [0, 215, 234, 158, 94, 184, 97, 118, 170, 79, 187, 152, 148, 252, 179, 5, 98, 96, 153];
break;
case 20:
this.gx = [0, 17, 60, 79, 50, 61, 163, 26, 187, 202, 180, 221, 225, 83, 239, 156, 164, 212, 212, 188, 190];
break;
case 22:
this.gx = [0, 210, 171, 247, 242, 93, 230, 14, 109, 221, 53, 200, 74, 8, 172, 98, 80, 219, 134, 160, 105, 165, 231];
break;
case 24:
this.gx = [0, 229, 121, 135, 48, 211, 117, 251, 126, 159, 180, 169, 152, 192, 226, 228, 218, 111, 0, 117, 232, 87,
96, 227, 21];
break;
case 26:
this.gx = [0, 173, 125, 158, 2, 103, 182, 118, 17, 145, 201, 111, 28, 165, 53, 161, 21, 245, 142, 13, 102, 48, 227, 153,
145, 218, 70];
break;
case 28:
this.gx = [0, 168, 223, 200, 104, 224, 234, 108, 180, 110, 190, 195, 147, 205, 27, 232, 201, 21, 43, 245, 87, 42, 195,
212, 119, 242, 37, 9, 123];
break;
case 30:
this.gx = [0, 41, 173, 145, 152, 216, 31, 179, 182, 50, 48, 110, 86, 239, 96, 222, 125, 42, 173, 226, 193, 224, 130,
156, 37, 251, 216, 238, 40, 192, 180];
break;
}
this.gx = this.getElement(this.gx, this.alpha);
this.toDecimal(this.mDataCodeWord);
const decimalRepresentation: number[] = this.divide();
const ecw: string[] = this.toBinary(decimalRepresentation);
return ecw;
}
/* tslint:enable */
/**
* Convert to decimal
*
* @returns {void}Convert to decimal.
* @param {string[]} inString - Provide the version for the QR code
* @private
*/
private toDecimal(inString: string[]): void {
for (let i: number = 0; i < inString.length; i++) {
this.decimalValue[i] = parseInt(inString[i], 2);
}
}
/**
* Convert decimal to binary.
*
* @returns {string[]}Convert decimal to binary.
* @param {number[]} decimalRepresentation - Provide the version for the QR code
* @private
*/
private toBinary(decimalRepresentation: number[]): string[] {
const toBinary: string[] = [];
for (let i: number = 0; i < this.eccw; i++) {
let str: string = '';
const temp: string = decimalRepresentation[i].toString(2);
if (temp.length < 8) {
for (let j: number = 0; j < 8 - temp.length; j++) {
str += '0';
}
}
toBinary[i] = str + temp;
}
return toBinary;
}
/**
* Polynomial division.
*
* @returns {string[]}Polynomial division.
* @private
*/
private divide(): number[] {
let messagePolynom: { [key: number]: number } = {};
for (let i: number = 0; i < this.decimalValue.length; i++) {
messagePolynom[this.decimalValue.length - 1 - i] = this.decimalValue[i];
}
let generatorPolynom: { [key: number]: number } = {};
for (let i: number = 0; i < this.gx.length; i++) {
generatorPolynom[this.gx.length - 1 - i] = this.findElement(this.gx[i], this.alpha);
}
let tempMessagePolynom: { [key: number]: number } = {};
for (const poly of Object.keys(messagePolynom)) {
tempMessagePolynom[Number(poly) + this.eccw] = messagePolynom[poly];
}
messagePolynom = tempMessagePolynom;
const genLeadtermFactor: number = this.decimalValue.length + this.eccw - this.gx.length;
tempMessagePolynom = {};
for (const poly of Object.keys(generatorPolynom)) {
tempMessagePolynom[Number(poly) + genLeadtermFactor] = generatorPolynom[poly];
}
generatorPolynom = tempMessagePolynom;
let leadTermSource: { [key: number]: number } = messagePolynom;
for (let i: number = 0; i < Object.keys(messagePolynom).length; i++) {
const largestExponent: number = this.findLargestExponent(leadTermSource);
if (leadTermSource[largestExponent] === 0) {
// First coefficient is already 0, simply remove it and continue
delete leadTermSource[largestExponent];
} else {
const alphaNotation: { [key: number]: number } = this.convertToAlphaNotation(leadTermSource);
let resPoly: { [key: number]: number } = this.multiplyGeneratorPolynomByLeadterm(
generatorPolynom, alphaNotation[this.findLargestExponent(alphaNotation)], i);
resPoly = this.convertToDecNotation(resPoly);
resPoly = this.xORPolynoms(leadTermSource, resPoly);
leadTermSource = resPoly;
}
}
//Add the error correction word count according to polynomial values.
this.eccw = Object.keys(leadTermSource).length;
const returnValue: number[] = [];
for (const temp of Object.keys(leadTermSource)) {
returnValue.push(leadTermSource[temp]);
}
return returnValue.reverse();
}
private xORPolynoms(messagePolynom: { [key: number]: number }, resPolynom: { [key: number]: number }): { [key: number]: number } {
const resultPolynom: { [key: number]: number } = {};
let longPoly: { [key: number]: number } = {};
let shortPoly: { [key: number]: number } = {};
if (Object.keys(messagePolynom).length >= Object.keys(resPolynom).length) {
longPoly = messagePolynom;
shortPoly = resPolynom;
} else {
longPoly = resPolynom;
shortPoly = messagePolynom;
}
const messagePolyExponent: number = this.findLargestExponent(messagePolynom);
const shortPolyExponent: number = this.findLargestExponent(shortPoly);
let i: number = Object.keys(longPoly).length - 1;
for (const longPolySingle of Object.keys(longPoly)) {
resultPolynom[messagePolyExponent - i] = longPoly[longPolySingle] ^ (Object.keys(shortPoly).length > i ?
shortPoly[shortPolyExponent - i] : 0);
i--;
}
const resultPolyExponent: number = this.findLargestExponent(resultPolynom);
delete resultPolynom[resultPolyExponent];
return resultPolynom;
}
private multiplyGeneratorPolynomByLeadterm(
genPolynom: { [key: number]: number }, leadTermCoefficient: number, lowerExponentBy: number): { [key: number]: number } {
const tempPolynom: { [key: number]: number } = {};
for (const treeNode of Object.keys(genPolynom)) {
tempPolynom[Number(treeNode) - lowerExponentBy] = (genPolynom[treeNode] + leadTermCoefficient) % 255;
}
return tempPolynom;
}
private convertToDecNotation(poly: { [key: number]: number }): { [key: number]: number } {
const tempPolynom: { [key: number]: number } = {};
for (const treeNode of Object.keys(poly)) {
tempPolynom[treeNode] = this.getIntValFromAlphaExp(poly[treeNode], this.alpha);
}
return tempPolynom;
}
private convertToAlphaNotation(polynom: { [key: number]: number }): { [key: number]: number } {
const tempPolynom: { [key: number]: number } = {};
for (const poly of Object.keys(polynom)) {
if (polynom[poly] !== 0) {
tempPolynom[poly] = this.findElement(polynom[poly], this.alpha);
}
}
return tempPolynom;
}
private findLargestExponent(polynom: { [key: number]: number }): number {
let largCo: number = 0;
for (const poly of Object.keys(polynom)) {
if (Number(poly) > largCo) {
largCo = Number(poly);
}
}
return largCo;
}
private getIntValFromAlphaExp(element: number, alpha: number[]): number {
if (element > 255) {
element = element - 255;
}
return alpha[element];
}
/**
* Find the element in the alpha
*
* @returns {number}Find the element in the alpha.
* @param {QRCodeVersion} element - Provide the element for the Qr code
* @param {ErrorCorrectionLevel} alpha -provide the number
* @private
*/
private findElement(element: number, alpha: number[]): number {
let j: number;
for (j = 0; j < alpha.length; j++) {
if (element === alpha[j]) { break; }
}
return j;
}
/**
* Gets g(x) of the element
*/
/**
* Gets g(x) of the element
*
* @returns {number}Gets g(x) of the element .
* @param {QRCodeVersion} element - Provide the element for the Qr code
* @param {ErrorCorrectionLevel} alpha -provide the number
* @private
*/
private getElement(element: number[], alpha: number[]): number[] {
const gx: number[] = [element.length];
for (let i: number = 0; i < element.length; i++) {
if (element[i] > 255) {
element[i] = element[i] - 255;
}
gx[i] = alpha[element[i]];
}
return gx;
}
} | the_stack |
import * as crypto from "crypto";
import * as fs from "fs";
import * as path from "path";
import * as vscode from "vscode";
import * as zhihuEncrypt from "zhihu-encrypt";
import * as cheerio from "cheerio";
import { DefaultHTTPHeader, LoginPostHeader, QRCodeOptionHeader, WeixinLoginHeader } from "../const/HTTP";
import { TemplatePath } from "../const/PATH";
import { CaptchaAPI, LoginAPI, SMSAPI, QRCodeAPI, UDIDAPI, WeixinLoginPageAPI, WeixinLoginQRCodeAPI, WeixinState, WeixinLoginRedirectAPI, JianshuWeixinLoginRedirectAPI } from "../const/URL";
import { ILogin, ISmsData } from "../model/login.model";
import { FeedTreeViewProvider } from "../treeview/feed-treeview-provider";
import { LoginEnum, LoginTypes, SettingEnum, JianshuLoginTypes } from "../const/ENUM";
import { AccountService } from "./account.service";
import { HttpService, clearCookie, sendRequest } from "./http.service";
import { ProfileService } from "./profile.service";
import { WebviewService } from "./webview.service";
import { getExtensionPath } from "../global/globa-var";
import { Output } from "../global/logger";
var formurlencoded = require('form-urlencoded').default;
export class AuthenticateService {
constructor(
protected profileService: ProfileService,
protected accountService: AccountService,
protected feedTreeViewProvider: FeedTreeViewProvider,
protected webviewService: WebviewService) {
}
public logout() {
try {
clearCookie();
this.feedTreeViewProvider.refresh();
// fs.writeFileSync(path.join(getExtensionPath(), 'cookie.txt'), '');
} catch (error) {
console.log(error);
}
vscode.window.showInformationMessage('注销成功!');
}
public async login() {
if (await this.accountService.isAuthenticated()) {
vscode.window.showInformationMessage(`你已经登录了哦~ ${this.profileService.name}`);
return;
}
clearCookie()
const selectedLoginType: LoginEnum = await vscode.window.showQuickPick<vscode.QuickPickItem & { value: LoginEnum }>(
LoginTypes.map(type => ({ value: type.value, label: type.ch, description: '' })),
{ placeHolder: "选择登录方式: " }
).then(item => item.value);
if (selectedLoginType == LoginEnum.password) {
this.passwordLogin();
} else if (selectedLoginType == LoginEnum.sms) {
this.smsLogin();
} else if (selectedLoginType == LoginEnum.qrcode) {
this.qrcodeLogin();
} else if (selectedLoginType == LoginEnum.weixin) {
this.weixinLogin();
}
}
public async jianshuLogin() {
const selectedLoginType: LoginEnum = await vscode.window.showQuickPick<vscode.QuickPickItem & { value: LoginEnum }>(
JianshuLoginTypes.map(type => ({ value: type.value, label: type.ch, description: '' })),
{ placeHolder: "选择登录方式: " }
).then(item => item.value);
if (selectedLoginType == LoginEnum.weixin) {
this.jianshuWeixinLogin();
}
}
public async passwordLogin() {
let resp = await sendRequest({
uri: CaptchaAPI,
method: 'get',
gzip: true,
json: true
});
if (resp.show_captcha) {
let captchaImg = await sendRequest({
uri: CaptchaAPI,
method: 'put',
json: true,
gzip: true
});
let base64Image = captchaImg['img_base64'].replace('\n', '');
fs.writeFileSync(path.join(getExtensionPath(), './captcha.jpg'), base64Image, 'base64');
const panel = vscode.window.createWebviewPanel("zhihu", "验证码", { viewColumn: vscode.ViewColumn.One, preserveFocus: true });
const imgSrc = panel.webview.asWebviewUri(vscode.Uri.file(
path.join(getExtensionPath(), './captcha.jpg')
));
this.webviewService.renderHtml({
title: '验证码',
showOptions: {
viewColumn: vscode.ViewColumn.One,
preserveFocus: true
},
pugTemplatePath: path.join(
getExtensionPath(),
TemplatePath,
'captcha.pug'
),
pugObjects: {
title: '验证码',
captchaSrc: imgSrc.toString(),
useVSTheme: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.useVSTheme)
}
}, panel)
do {
var captcha: string | undefined = await vscode.window.showInputBox({
prompt: "输入验证码",
placeHolder: "",
ignoreFocusOut: true
});
if (!captcha) return
let headers = DefaultHTTPHeader;
headers['cookie'] = fs.readFileSync
resp = await sendRequest({
method: 'POST',
uri: CaptchaAPI,
form: {
input_text: captcha
},
json: true,
simple: false,
gzip: true,
resolveWithFullResponse: true,
});
if (resp.statusCode != 201) {
vscode.window.showWarningMessage('请输入正确的验证码')
}
} while (resp.statusCode != 201);
Output('验证码正确。', 'info')
panel.dispose()
}
const phoneNumber: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入手机号或邮箱",
placeHolder: "",
});
if (!phoneNumber) return;
const password: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入密码",
placeHolder: "",
password: true
});
if (!password) return
let loginData: ILogin = {
'client_id': 'c3cef7c66a1843f8b3a9e6a1e3160e20',
'grant_type': 'password',
'source': 'com.zhihu.web',
'username': '+86' + phoneNumber,
'password': password,
'lang': 'en',
'ref_source': 'homepage',
'utm_source': '',
'captcha': captcha,
'timestamp': Math.round(new Date().getTime()),
'signature': ''
};
loginData.signature = crypto.createHmac('sha1', 'd1b964811afb40118a12068ff74a12f4')
// .update(loginData.grant_type + loginData.client_id + loginData.source + loginData.timestamp.toString())
.update("password" + loginData.client_id + loginData.source + loginData.timestamp.toString())
.digest('hex');
let encryptedFormData = zhihuEncrypt.loginEncrypt(formurlencoded(loginData));
var loginResp = await sendRequest(
{
uri: LoginAPI,
method: 'post',
body: encryptedFormData,
gzip: true,
resolveWithFullResponse: true,
simple: false,
headers: LoginPostHeader
});
this.profileService.fetchProfile().then(() => {
if (loginResp.statusCode == '201') {
Output(`你好,${this.profileService.name}`, 'info');
this.feedTreeViewProvider.refresh();
} else if (loginResp.statusCode == '401') {
Output('密码错误!' + loginResp.statusCode, 'warn');
} else {
Output('登录失败!错误代码' + loginResp.statusCode, 'warn');
}
})
}
public async smsLogin() {
await sendRequest({
uri: 'https://www.zhihu.com/signin'
})
const phoneNumber: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入手机号或邮箱",
placeHolder: "",
});
if (!phoneNumber) {
return;
}
let smsData: ISmsData = {
phone_no: '+86' + phoneNumber,
sms_type: 'text'
};
let encryptedFormData = zhihuEncrypt.smsEncrypt(formurlencoded(smsData));
// phone_no%3D%252B8618324748963%26sms_type%3Dtext
var loginResp = await sendRequest(
{
uri: SMSAPI,
method: 'post',
body: encryptedFormData,
gzip: true,
resolveWithFullResponse: true,
simple: false,
json: true
});
console.log(loginResp);
const smsCaptcha: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入短信验证码:",
placeHolder: "",
});
}
public async qrcodeLogin() {
await sendRequest({
uri: UDIDAPI,
method: 'post'
});
let resp = await sendRequest({
uri: QRCodeAPI,
method: 'post',
json: true,
gzip: true,
header: QRCodeOptionHeader
});
let qrcode = await sendRequest({
uri: `${QRCodeAPI}/${resp.token}/image`,
encoding: null
});
fs.writeFileSync(path.join(getExtensionPath(), 'qrcode.png'), qrcode);
const panel = vscode.window.createWebviewPanel("zhihu", "验证码", { viewColumn: vscode.ViewColumn.One, preserveFocus: true });
const imgSrc = panel.webview.asWebviewUri(vscode.Uri.file(
path.join(getExtensionPath(), './qrcode.png')
))
this.webviewService.renderHtml(
{
title: '二维码',
showOptions: {
viewColumn: vscode.ViewColumn.One,
preserveFocus: true
},
pugTemplatePath: path.join(
getExtensionPath(),
TemplatePath,
'qrcode.pug'
),
pugObjects: {
title: '打开知乎 APP 扫一扫',
qrcodeSrc: imgSrc.toString(),
useVSTheme: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.useVSTheme)
}
},
panel
);
let intervalId = setInterval(() => {
sendRequest({
uri: `${QRCodeAPI}/${resp.token}/scan_info`,
json: true,
gzip: true
}).then(
r => {
if (r.status == 1) {
vscode.window.showInformationMessage('请在手机上确认登录!');
} else if (r.user_id) {
clearInterval(intervalId);
panel.dispose();
this.profileService.fetchProfile().then(() => {
vscode.window.showInformationMessage(`你好,${this.profileService.name}`);
this.feedTreeViewProvider.refresh();
})
}
}
);
}, 1000)
panel.onDidDispose(() => {
console.log('Window is disposed')
clearInterval(intervalId)
})
}
public async weixinLogin() {
await sendRequest({
uri: 'https://www.zhihu.com/signin?next=%2F',
});
let uri = WeixinLoginRedirectAPI();
let prefetch = await sendRequest({
uri,
gzip: true,
followRedirect: false,
followAllRedirects: false,
resolveWithFullResponse: true
})
uri = prefetch.headers['location'];
let html = await sendRequest({
uri,
gzip: true
})
var reg = /state=(\w+)/g;
const state = uri.match(reg)[0].replace(reg, '$1');
const $ = cheerio.load(html)
const panel = vscode.window.createWebviewPanel("zhihu", "微信登录", { viewColumn: vscode.ViewColumn.One, preserveFocus: true });
const imgSrc = WeixinLoginQRCodeAPI($('img')[0].attribs['src']);
const uuid = imgSrc.match(/\/connect\/qrcode\/([\w\d]*)/)[1];
this.webviewService.renderHtml(
{
title: '二维码',
showOptions: {
viewColumn: vscode.ViewColumn.One,
preserveFocus: true
},
pugTemplatePath: path.join(
getExtensionPath(),
TemplatePath,
'qrcode.pug'
),
pugObjects: {
title: '打开微信 APP 扫一扫',
qrcodeSrc: imgSrc,
useVSTheme: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.useVSTheme)
}
},
panel
);
var p = "https://lp.open.weixin.qq.com";
var intervalId = setInterval(() => {
this.weixinPolling(p, uuid, panel, state).then(r => {
if (r == true) {
clearInterval(intervalId);
panel.dispose()
}
})
}, 1000)
panel.onDidDispose(l => {
clearInterval(intervalId);
})
// this.weixinPolling(p, uuid, panel, state);
}
public async jianshuWeixinLogin() {
let uri = JianshuWeixinLoginRedirectAPI();
let prefetch = await sendRequest({
uri,
gzip: true,
followRedirect: false,
followAllRedirects: false,
resolveWithFullResponse: true
})
uri = prefetch.headers['location'];
let html = await sendRequest({
uri,
gzip: true
})
var reg = /state=([\w%]+)/g;
const state = uri.match(reg)[0].replace(reg, '$1');
const $ = cheerio.load(html)
const panel = vscode.window.createWebviewPanel("zhihu", "微信登录", { viewColumn: vscode.ViewColumn.One, preserveFocus: true });
const imgSrc = WeixinLoginQRCodeAPI($('img')[0].attribs['src']);
const uuid = imgSrc.match(/\/connect\/qrcode\/([\w\d]*)/)[1];
this.webviewService.renderHtml(
{
title: '二维码',
showOptions: {
viewColumn: vscode.ViewColumn.One,
preserveFocus: true
},
pugTemplatePath: path.join(
getExtensionPath(),
TemplatePath,
'qrcode.pug'
),
pugObjects: {
title: '打开微信 APP 扫一扫',
qrcodeSrc: imgSrc,
useVSTheme: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.useVSTheme)
}
},
panel
);
var p = "https://lp.open.weixin.qq.com";
var intervalId = setInterval(() => {
this.jianshuWeixinPolling(p, uuid, panel, state).then(r => {
if (r == true) {
clearInterval(intervalId);
panel.dispose()
}
})
}, 1000)
panel.onDidDispose(l => {
clearInterval(intervalId)
panel.dispose()
})
}
private async weixinPolling(p: string, uuid: string, panel: vscode.WebviewPanel, state: string): Promise<boolean> {
let weixinResp = await sendRequest({
uri: p + `/connect/l/qrconnect?uuid=${uuid}`,
timeout: 6e4,
resolveWithFullResponse: true,
headers: WeixinLoginHeader(WeixinLoginPageAPI())
});
let wx_errcode = ""
let wx_code = ""
// if (weixinResp.body && weixinResp.body.length > 0) {
wx_errcode = weixinResp.body.match(/window\.wx_errcode=(\d+)/)[1];
wx_code = weixinResp.body.match(/window\.wx_code='(.*)'/)[1];
// }
var g = parseInt(wx_errcode);
switch (g) {
case 405:
var h = "https://www.zhihu.com/oauth/callback/wechat?action=login&from=";
h = h.replace(/&/g, "&"),
h += (h.indexOf("?") > -1 ? "&" : "?") + "code=" + wx_code + `&state=${state}`;
let r = await sendRequest({
uri: h,
resolveWithFullResponse: true,
// gzip: true,
headers: WeixinLoginHeader(WeixinLoginPageAPI())
})
this.profileService.fetchProfile().then(() => {
Output(`你好,${this.profileService.name}`, 'info');
this.feedTreeViewProvider.refresh();
});
panel.onDidDispose(() => {
console.log('Window is disposed');
});
return Promise.resolve(true);
break;
case undefined:
this.weixinPolling(p, uuid, panel, state)
return Promise.resolve(false);
default:
Output('请在微信上扫码, 点击确认!', 'info');
return Promise.resolve(false);
// this.weixinPolling(p, uuid, panel, state)
}
}
private async jianshuWeixinPolling(p: string, uuid: string, panel: vscode.WebviewPanel, state: string): Promise<boolean> {
let weixinResp = await sendRequest({
uri: p + `/connect/l/qrconnect?uuid=${uuid}`,
timeout: 6e4,
resolveWithFullResponse: true,
headers: WeixinLoginHeader(WeixinLoginPageAPI())
});
let wx_code = ""
let wx_errcode = ""
if (weixinResp.body && weixinResp.body.length > 0) {
wx_errcode = weixinResp.body.match(/window\.wx_errcode=(\d+)/)[1];
wx_code = weixinResp.body.match(/window\.wx_code='(.*)'/)[1];
}
var g = parseInt(wx_errcode);
switch (g) {
// "https://open.weixin.qq.com/connect/qrconnect?appid=wxe9199d568fe57fdd&client_id=wxe9199d568fe57fdd&redirect_uri=http%3A%2F%2Fwww.jianshu.com%2Fusers%2Fauth%2Fwechat%2Fcallback&response_type=code&scope=snsapi_login&state=%257B%257D"
case 405:
var h = "http://www.jianshu.com/users/auth/wechat/callback";
// "http://www.jianshu.com/users/auth/wechat/callback?code=021jPsAa1isZkM1Z5zza1turAa1jPsAi&state=%7B%7D"
h = h.replace(/&/g, "&"),
h += (h.indexOf("?") > -1 ? "&" : "?") + "code=" + wx_code + `&state=${state}`;
let r = await sendRequest({
uri: h,
resolveWithFullResponse: true,
gzip: true,
// headers: WeixinLoginHeader(WeixinLoginPageAPI())
})
// request twice, don't know why, but jianshu does this way.
r = await sendRequest({
uri: h,
resolveWithFullResponse: true,
gzip: true,
// headers: WeixinLoginHeader(WeixinLoginPageAPI())
})
this.profileService.fetchProfile().then(() => {
Output(`你好,简书登录成功`, 'info');
this.feedTreeViewProvider.refresh();
});
panel.onDidDispose(() => {
console.log('Window is disposed');
});
return Promise.resolve(true);
break;
case undefined:
// this.weixinPolling(p, uuid, panel, state)
return Promise.resolve(false);
default:
Output('请在微信上扫码, 点击确认!', 'info');
return Promise.resolve(false);
// this.weixinPolling(p, uuid, panel, state)
}
}
} | the_stack |
import * as DiffMatchPatch from 'diff-match-patch';
function testDiffMainEach() {
const oldValue = "hello world, how are you?";
const newValue = "hello again world. how have you been?";
const diffEngine = new DiffMatchPatch.diff_match_patch();
const diffs = diffEngine.diff_main(oldValue, newValue);
diffEngine.diff_cleanupSemantic(diffs);
let changes = "";
let pattern = "";
diffs.forEach((diff) => {
const operation = diff[0]; // Operation (insert, delete, equal)
const text = diff[1]; // Text of change
switch (operation) {
case DiffMatchPatch.DIFF_INSERT:
pattern += "I";
break;
case DiffMatchPatch.DIFF_DELETE:
pattern += "D";
break;
case DiffMatchPatch.DIFF_EQUAL:
pattern += "E";
break;
}
changes += text;
});
}
const DIFF_DELETE: number = DiffMatchPatch.DIFF_DELETE;
const DIFF_INSERT: number = DiffMatchPatch.DIFF_INSERT;
const DIFF_EQUAL: number = DiffMatchPatch.DIFF_EQUAL;
const dmp = new DiffMatchPatch.diff_match_patch();
// DIFF TEST FUNCTIONS
function testDiffCommonPrefix() {
assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz'));
}
function testDiffCommonSuffix() {
assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz'));
}
function testDiffCommonOverlap() {
assertEquals(0, dmp.diff_commonOverlap_('', 'abcd'));
}
function testDiffHalfMatch() {
dmp.Diff_Timeout = 1;
assertEquals(null, dmp.diff_halfMatch_('1234567890', 'abcdef'));
assertEquivalent(['12', '90', 'a', 'z', '345678'], dmp.diff_halfMatch_('1234567890', 'a345678z'));
assertEquivalent(['12123', '123121', 'a', 'z', '1234123451234'], dmp.diff_halfMatch_('121231234123451234123121', 'a1234123451234z'));
}
function testDiffLinesToChars() {
assertLinesToCharsResultEquals({chars1: '\x01\x02\x01', chars2: '\x02\x01\x02', lineArray: ['', 'alpha\n', 'beta\n']}, dmp.diff_linesToChars_('alpha\nbeta\nalpha\n', 'beta\nalpha\nbeta\n'));
}
function testDiffCharsToLines() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_EQUAL, '\x01\x02\x01'], [DIFF_INSERT, '\x02\x01\x02']];
dmp.diff_charsToLines_(diffs, ['', 'alpha\n', 'beta\n']);
assertEquivalent([[DIFF_EQUAL, 'alpha\nbeta\nalpha\n'], [DIFF_INSERT, 'beta\nalpha\nbeta\n']], diffs);
}
function testDiffCleanupMerge() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'b'], [DIFF_INSERT, 'c']];
dmp.diff_cleanupMerge(diffs);
assertEquivalent([[DIFF_EQUAL, 'a'], [DIFF_DELETE, 'b'], [DIFF_INSERT, 'c']], diffs);
}
function testDiffCleanupSemanticLossless() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_EQUAL, 'AAA\r\n\r\nBBB'], [DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'], [DIFF_EQUAL, '\r\nEEE']];
dmp.diff_cleanupSemanticLossless(diffs);
assertEquivalent([[DIFF_EQUAL, 'AAA\r\n\r\n'], [DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'], [DIFF_EQUAL, 'BBB\r\nEEE']], diffs);
}
function testDiffCleanupSemantic() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, 'cd'], [DIFF_EQUAL, '12'], [DIFF_DELETE, 'e']];
dmp.diff_cleanupSemantic(diffs);
assertEquivalent([[DIFF_DELETE, 'ab'], [DIFF_INSERT, 'cd'], [DIFF_EQUAL, '12'], [DIFF_DELETE, 'e']], diffs);
}
function testDiffCleanupEfficiency() {
dmp.Diff_EditCost = 4;
const diffs: DiffMatchPatch.Diff[] = [[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'wxyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']];
dmp.diff_cleanupEfficiency(diffs);
assertEquivalent([[DIFF_DELETE, 'ab'], [DIFF_INSERT, '12'], [DIFF_EQUAL, 'wxyz'], [DIFF_DELETE, 'cd'], [DIFF_INSERT, '34']], diffs);
}
function testDiffPrettyHtml() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_EQUAL, 'a\n'], [DIFF_DELETE, '<B>b</B>'], [DIFF_INSERT, 'c&d']];
assertEquals('<span>a¶<br></span><del style="background:#ffe6e6;"><B>b</B></del><ins style="background:#e6ffe6;">c&d</ins>', dmp.diff_prettyHtml(diffs));
}
function testDiffText() {
const diffs: DiffMatchPatch.Diff[] = [[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, ' lazy']];
assertEquals('jumps over the lazy', dmp.diff_text1(diffs));
assertEquals('jumped over a lazy', dmp.diff_text2(diffs));
}
function testDiffDelta() {
const diffs: DiffMatchPatch.Diff[] =
[[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, ' lazy'], [DIFF_INSERT, 'old dog']];
const text1 = dmp.diff_text1(diffs);
assertEquals('jumps over the lazy', text1);
const delta = dmp.diff_toDelta(diffs);
assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta);
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta));
}
function testDiffXIndex() {
assertEquals(5, dmp.diff_xIndex([[DIFF_DELETE, 'a'], [DIFF_INSERT, '1234'], [DIFF_EQUAL, 'xyz']], 2));
}
function testDiffLevenshtein() {
assertEquals(4, dmp.diff_levenshtein([[DIFF_DELETE, 'abc'], [DIFF_INSERT, '1234'], [DIFF_EQUAL, 'xyz']]));
}
function testDiffBisect() {
const a = 'cat';
const b = 'map';
assertEquivalent([[DIFF_DELETE, 'c'], [DIFF_INSERT, 'm'], [DIFF_EQUAL, 'a'], [DIFF_DELETE, 't'], [DIFF_INSERT, 'p']], dmp.diff_bisect_(a, b, Number.MAX_VALUE));
}
function testDiffMain() {
assertEquivalent([], dmp.diff_main('', '', false));
dmp.Diff_Timeout = 0;
// Simple cases.
assertEquivalent([[DIFF_DELETE, 'a'], [DIFF_INSERT, 'b']], dmp.diff_main('a', 'b', false));
}
// MATCH TEST FUNCTIONS
function testMatchAlphabet() {
const expected: {[char: string]: number} = {};
expected['a'] = 4;
expected['b'] = 2;
expected['c'] = 1;
assertEquivalent(expected, dmp.match_alphabet_('abc'));
}
function testMatchBitap() {
dmp.Match_Distance = 100;
dmp.Match_Threshold = 0.5;
assertEquals(5, dmp.match_bitap_('abcdefghijk', 'fgh', 5));
}
function testMatchMain() {
assertEquals(0, dmp.match_main('abcdef', 'abcdef', 1000));
}
// PATCH TEST FUNCTIONS
function testPatchObj() {
// Patch Object.
const p = new DiffMatchPatch.patch_obj();
assertEquals(null, p.start1);
assertEquals(null, p.start2);
p.start1 = 20;
p.start2 = 21;
p.length1 = 18;
p.length2 = 17;
p.diffs = [[DIFF_EQUAL, 'jump'], [DIFF_DELETE, 's'], [DIFF_INSERT, 'ed'], [DIFF_EQUAL, ' over '], [DIFF_DELETE, 'the'], [DIFF_INSERT, 'a'], [DIFF_EQUAL, '\nlaz']];
const strp = p.toString();
assertEquals('@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n', strp);
}
function testPatchFromText() {
const strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n';
assertEquals(strp, dmp.patch_fromText(strp)[0].toString());
}
function testPatchToText() {
const strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n';
const p = dmp.patch_fromText(strp);
assertEquals(strp, dmp.patch_toText(p));
}
function testPatchAddContext() {
dmp.Patch_Margin = 4;
const p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[0];
dmp.patch_addContext_(p, 'The quick brown fox jumps over the lazy dog.');
assertEquals('@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n', p.toString());
}
function testPatchMake() {
const text1 = 'The quick brown fox jumps over the lazy dog.';
const text2 = 'That quick brown fox jumped over a lazy dog.';
let expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n';
let patches = dmp.patch_make(text2, text1);
assertEquals(expectedPatch, dmp.patch_toText(patches));
// Method 1
expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n';
patches = dmp.patch_make(text1, text2);
assertEquals(expectedPatch, dmp.patch_toText(patches));
// Method 2
const diffs = dmp.diff_main(text1, text2, false);
patches = dmp.patch_make(diffs);
assertEquals(expectedPatch, dmp.patch_toText(patches));
// Method 3
patches = dmp.patch_make(text1, diffs);
assertEquals(expectedPatch, dmp.patch_toText(patches));
// Method 4
patches = dmp.patch_make(text1, text2, diffs);
assertEquals(expectedPatch, dmp.patch_toText(patches));
}
function testPatchSplitMax() {
const patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890', 'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0');
dmp.patch_splitMax(patches);
assertEquals(
[
'@@ -1,32 +1,46 @@\n',
'+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\nuv\n+X\n wx\n+X\n yz\n+X\n 012345\n',
'@@ -25,13 +39,18 @@',
'\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n'
].join(''),
dmp.patch_toText(patches));
}
function testPatchAddPadding() {
const patches = dmp.patch_make('', 'test');
assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches));
dmp.patch_addPadding(patches);
assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches));
}
function testPatchApply() {
dmp.Match_Distance = 1000;
dmp.Match_Threshold = 0.5;
dmp.Patch_DeleteThreshold = 0.5;
const patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.', 'That quick brown fox jumped over a lazy dog.');
const results = dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.');
assertEquivalent(['That quick brown fox jumped over a lazy dog.', [true, true]], results);
}
declare function assertEquals<T>(expected: T, actual: T): void;
declare function assertEquivalent<T>(expected: T[], actual: T[]): void;
declare function assertEquivalent<T extends {}>(expected: T, actual: T): void;
declare function assertLinesToCharsResultEquals(expected: {chars1: string, chars2: string, lineArray: string[]}, actual: {chars1: string, chars2: string, lineArray: string[]}): void; | the_stack |
import {
ReactNode,
forwardRef,
Ref,
ButtonHTMLAttributes,
AnchorHTMLAttributes,
HTMLAttributes,
FC,
} from 'react';
import { css } from '@emotion/react';
import isPropValid from '@emotion/is-prop-valid';
import { ChevronRight, IconProps } from '@sumup/icons';
import styled, { StyleProps } from '../../styles/styled';
import {
disableVisually,
focusVisible,
spacing,
} from '../../styles/style-mixins';
import { ReturnType } from '../../types/return-type';
import { ClickEvent } from '../../types/events';
import { EmotionAsPropType } from '../../types/prop-types';
import { isFunction, isString } from '../../util/type-check';
import { warn } from '../../util/logger';
import { useClickEvent, TrackingProps } from '../../hooks/useClickEvent';
import { useComponents } from '../ComponentsContext';
import Body from '../Body';
type Variant = 'action' | 'navigation';
interface BaseProps {
/**
* Choose between 'action' and 'navigation' variant. Default: 'action'.
* The `navigation` variant renders a chevron in the trailing section.
*/
variant?: Variant;
/**
* Display a leading component.
* Pass an icon from `@sumup/icons` or a custom component.
*/
leadingComponent?: FC<IconProps> | ReactNode;
/**
* Display a main label.
*/
label: ReactNode;
/**
* Display a details line below the main label.
*/
details?: ReactNode;
/**
* Display a trailing label.
* If using the `navigation` variant, the chevron icon will be center aligned with this label.
*/
trailingLabel?: string | ReactNode;
/**
* Display a trailing details label.
*/
trailingDetails?: string | ReactNode;
/**
* Display a custom trailing component.
* If using the `navigation` variant, the chevron icon will be center aligned with this component.
*/
trailingComponent?: ReactNode;
/**
* Visually mark the list item as selected.
*/
selected?: boolean;
/**
* Visually and functionally disable the list item.
*/
disabled?: boolean;
/**
* Function that is called when the list item is clicked.
*/
onClick?: (event: ClickEvent) => void;
/**
* Link to another part of the application or external page.
*/
href?: string;
/**
* Additional data that is dispatched with the tracking event.
*/
tracking?: TrackingProps;
/**
* The ref to the HTML DOM element
*/
ref?: Ref<HTMLDivElement & HTMLAnchorElement & HTMLButtonElement>;
}
type DivElProps = Omit<HTMLAttributes<HTMLDivElement>, 'onClick'>;
type LinkElProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'onClick'>;
type ButtonElProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'>;
export type ListItemProps = BaseProps &
DivElProps &
LinkElProps &
ButtonElProps;
type InteractiveProps = { isInteractive: boolean };
type StyledListItemProps = Pick<BaseProps, 'selected'> &
InteractiveProps &
DivElProps &
LinkElProps &
ButtonElProps;
const baseStyles = ({ theme }: StyleProps) => css`
background-color: ${theme.colors.white};
color: ${theme.colors.bodyColor};
border: ${theme.borderWidth.mega} solid ${theme.colors.n200};
border-radius: ${theme.borderRadius.mega};
display: flex;
align-items: center;
padding: ${theme.spacings.kilo} ${theme.spacings.mega};
margin: 0;
width: 100%;
text-align: left;
text-decoration: none;
position: relative;
&:focus {
border-color: transparent;
z-index: 2;
}
&:focus:not(:focus-visible) {
border-color: ${theme.colors.n200};
z-index: auto;
}
&:disabled,
&[disabled] {
${disableVisually()};
}
`;
const interactiveStyles = ({
theme,
isInteractive,
}: StyleProps & StyledListItemProps) =>
isInteractive &&
css`
cursor: pointer;
&:hover {
background-color: ${theme.colors.n100};
}
&:active {
background-color: ${theme.colors.n200};
border-color: ${theme.colors.n200};
}
`;
const selectedStyles = ({
theme,
selected,
}: StyleProps & StyledListItemProps) =>
selected &&
css`
background-color: ${theme.colors.p100};
&:hover,
&:active {
background-color: ${theme.colors.p100};
}
&:after {
content: '';
position: absolute;
top: -${theme.borderWidth.mega};
bottom: -${theme.borderWidth.mega};
left: -${theme.borderWidth.mega};
right: -${theme.borderWidth.mega};
border: ${theme.borderWidth.mega} solid ${theme.colors.p500};
border-radius: ${theme.borderRadius.mega};
z-index: 1;
pointer-events: none;
}
`;
const StyledListItem = styled('div', {
shouldForwardProp: (prop) => isPropValid(prop) && prop !== 'label',
})<StyledListItemProps>(
focusVisible,
baseStyles,
interactiveStyles,
selectedStyles,
);
const leadingContainerStyles = ({ theme }: StyleProps) => css`
flex: none;
display: flex;
margin-right: ${theme.spacings.mega};
`;
const LeadingContainer = styled.div(leadingContainerStyles);
const contentContainerStyles = css`
flex: auto;
display: flex;
align-items: center;
min-width: 0;
`;
const ContentContainer = styled.div(contentContainerStyles);
const mainContainerStyles = css`
flex: auto;
display: flex;
flex-direction: column;
align-items: flex-start;
min-width: 0;
`;
const MainContainer = styled.div(mainContainerStyles);
const labelStyles = css`
max-width: 100%;
overflow-x: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;
const Label = styled(Body)(labelStyles);
const detailsContainerStyles = ({ theme }: StyleProps) =>
css`
display: flex;
align-items: center;
max-width: 100%;
min-height: ${theme.typography.body.one.lineHeight};
`;
const DetailsContainer = styled.div(detailsContainerStyles);
type NavigationProps = { isNavigation: boolean };
type TrailingContainerProps = { hasLabel: boolean } & NavigationProps;
const trailingContainerStyles = ({
theme,
hasLabel,
}: StyleProps & TrailingContainerProps) => css`
flex: none;
align-self: stretch;
display: flex;
flex-direction: column;
align-items: flex-end;
justify-content: ${hasLabel ? 'flex-start' : 'center'};
margin-left: ${theme.spacings.mega};
`;
const trailingContainerNavigationStyles = ({
theme,
isNavigation,
}: StyleProps & TrailingContainerProps) =>
isNavigation &&
css`
margin-right: -${theme.spacings.bit};
`;
const TrailingContainer = styled.div(
trailingContainerStyles,
trailingContainerNavigationStyles,
);
const trailingChevronContainerStyles = css`
display: flex;
align-items: center;
`;
const TrailingChevronContainer = styled.div(trailingChevronContainerStyles);
const trailingDetailsContainerNavigationStyles = ({
theme,
isNavigation,
}: StyleProps & NavigationProps) =>
isNavigation &&
css`
margin-right: calc(${theme.spacings.mega} + ${theme.spacings.bit});
height: ${theme.typography.body.one.lineHeight};
`;
const TrailingDetailsContainer = styled.div(
detailsContainerStyles,
trailingDetailsContainerNavigationStyles,
);
/**
* The ListItem component enables the user to render a list item with various
* textual and visual elements.
*/
export const ListItem = forwardRef(
(
{
variant = 'action',
leadingComponent: LeadingComponent,
label,
details,
trailingLabel,
trailingDetails,
trailingComponent,
tracking,
...props
}: ListItemProps,
ref?: BaseProps['ref'],
): ReturnType => {
if (
process.env.NODE_ENV !== 'production' &&
process.env.NODE_ENV !== 'test'
) {
if (trailingDetails && !trailingLabel) {
warn(
'ListItem',
'Using `trailingDetails` without `trailingLabel` is not supported.',
'Use a custom `trailingComponent` if necessary.',
);
}
if (trailingComponent && trailingLabel) {
warn(
'ListItem',
'Using `trailingLabel` and `trailingComponent` at the same time is not supported.',
'Add a label to the custom `trailingComponent` if necessary.',
);
}
}
const { Link } = useComponents();
let as: EmotionAsPropType = 'div';
if (props.href) {
as = Link as EmotionAsPropType;
} else if (props.onClick) {
as = 'button';
}
const handleClick = useClickEvent(props.onClick, tracking, 'ListItem');
const isInteractive = !!props.href || !!props.onClick;
const isNavigation = variant === 'navigation';
const hasTrailing = !!trailingLabel || !!trailingComponent;
const shouldRenderTrailingContainer = hasTrailing || isNavigation;
return (
<StyledListItem
{...props}
ref={ref}
as={as}
isInteractive={isInteractive}
onClick={handleClick}
>
{LeadingComponent && (
<LeadingContainer>
{isFunction(LeadingComponent) ? (
<LeadingComponent size="24" role="presentation" />
) : (
LeadingComponent
)}
</LeadingContainer>
)}
<ContentContainer>
<MainContainer>
{isString(label) ? (
<Label size="one" noMargin>
{label}
</Label>
) : (
label
)}
{details && (
<DetailsContainer>
{isString(details) ? (
<Body size="two" variant="subtle" noMargin>
{details}
</Body>
) : (
details
)}
</DetailsContainer>
)}
</MainContainer>
{shouldRenderTrailingContainer && (
<TrailingContainer
hasLabel={!!trailingLabel}
isNavigation={isNavigation}
>
<TrailingChevronContainer>
{isString(trailingLabel) ? (
<Body size="one" variant="highlight" noMargin>
{trailingLabel}
</Body>
) : (
trailingLabel
)}
{trailingComponent}
{isNavigation && (
<ChevronRight
size="16"
role="presentation"
css={hasTrailing && spacing({ left: 'bit' })}
/>
)}
</TrailingChevronContainer>
{trailingDetails && (
<TrailingDetailsContainer isNavigation={isNavigation}>
{isString(trailingDetails) ? (
<Body size="two" variant="subtle" noMargin>
{trailingDetails}
</Body>
) : (
trailingDetails
)}
</TrailingDetailsContainer>
)}
</TrailingContainer>
)}
</ContentContainer>
</StyledListItem>
);
},
);
ListItem.displayName = 'ListItem'; | the_stack |
import { Long } from "./long";
import { ParametricDescription } from "./parametric_description";
// 1 vectors; 3 states per vector; array length = 3
const toStates0 = /*2 bits per value */ [
new Long(0x23)
];
const offsetIncrs0 = /*1 bits per value */ [
new Long(0x0)
];
// 2 vectors; 5 states per vector; array length = 10
const toStates1 = /*3 bits per value */ [
new Long(0x13688b44)
];
const offsetIncrs1 = /*1 bits per value */ [
new Long(0x3e0)
];
// 4 vectors; 13 states per vector; array length = 52
const toStates2 = /*4 bits per value */ [
new Long(0x5200b504, 0x60dbb0b0), new Long(0x27062227, 0x52332176), new Long(0x14323235, 0x23555432), new Long(0x4354)
];
const offsetIncrs2 = /*2 bits per value */ [
new Long(0x00002000, 0x555080a8), new Long(0x55555555, 0x55)
];
// 8 vectors; 28 states per vector; array length = 224
const toStates3 = /*5 bits per value */ [
new Long(0x40059404, 0xe701c029), new Long(0x00a50000, 0xa0101620), new Long(0xa1416288, 0xb02c8c40), new Long(0x310858c0, 0xa821032),
new Long(0x0d28b201, 0x31442398), new Long(0x847788e0, 0x5281e528), new Long(0x08c2280e, 0xa23980d3), new Long(0xa962278c, 0x1e3294b1),
new Long(0x2288e528, 0x8c41309e), new Long(0x021aca21, 0x11444409), new Long(0x86b1086b, 0x11a46248), new Long(0x1d6240c4, 0x2a625894),
new Long(0x489074ad, 0x5024a50b), new Long(0x520c411a, 0x14821aca), new Long(0x0b594a44, 0x5888b589), new Long(0xc411a465, 0x941d6520),
new Long(0xad6a62d4, 0x8b589075), new Long(0x1a5055a4)
];
const offsetIncrs3 = /*2 bits per value */ [
new Long(0x00002000, 0x30c302), new Long(0xc3fc333c, 0x2a0030f3), new Long(0x8282a820, 0x233a0032), new Long(0x32b283a8, 0x55555555),
new Long(0x55555555, 0x55555555), new Long(0x55555555, 0x55555555), new Long(0x55555555, 0x55555555)
];
// 16 vectors; 45 states per vector; array length = 720
const toStates4 = /*6 bits per value */ [
new Long(0x002c5004, 0x3801450), new Long(0x00000e38, 0xc500014b), new Long(0x51401402, 0x514), new Long(0x0),
new Long(0x14010000, 0x518000b), new Long(0x28e20230, 0x9f1c208), new Long(0x830a70c2, 0x219f0df0), new Long(0x08208200, 0x82000082),
new Long(0x60800800, 0x8050501), new Long(0x02602643, 0x30820986), new Long(0x50508064, 0x45640142), new Long(0x20000831, 0x8500514),
new Long(0x85002082, 0x41405820), new Long(0x0990c201, 0x45618098), new Long(0x50a01051, 0x8316d0c), new Long(0x050df0e0, 0x21451420),
new Long(0x14508214, 0xd142140), new Long(0x50821c60, 0x3c21c018), new Long(0xcb142087, 0x1cb1403), new Long(0x1851822c, 0x80082145),
new Long(0x20800020, 0x200208), new Long(0x87180345, 0xd0061820), new Long(0x24976b09, 0xcb0a81cb), new Long(0x624709d1, 0x8b1a60e),
new Long(0x82249089, 0x2490820), new Long(0x00d2c024, 0xc31421c6), new Long(0x15454423, 0x3c314515), new Long(0xc21cb140, 0x31853c22),
new Long(0x2c208214, 0x4514500b), new Long(0x508b0051, 0x8718034), new Long(0x5108f0c5, 0xb2cb4551), new Long(0x1cb0a810, 0xe824715d),
new Long(0x908b0e60, 0x1422cb14), new Long(0xc02cb145, 0x30812c22), new Long(0x0cb1420c, 0x84202202), new Long(0x20ce0850, 0x5c20ce08),
new Long(0x8b0d70c2, 0x20820820), new Long(0x14214208, 0x42085082), new Long(0x50830c20, 0x9208340), new Long(0x13653592, 0xc6134dc6),
new Long(0x6dc4db4d, 0xd309341c), new Long(0x54d34d34, 0x6424d908), new Long(0x030814c2, 0x92072c22), new Long(0x24a30930, 0x4220724b),
new Long(0x25c920e2, 0x2470d720), new Long(0x975c9082, 0x92c92d70), new Long(0x04924e08, 0xcb0880c2), new Long(0xc24c2481, 0x45739728),
new Long(0xda6174da, 0xc6da4db5), new Long(0x5d30971d, 0x4b5d35d7), new Long(0x93825ce2, 0x1030815c), new Long(0x020cb145, 0x51442051),
new Long(0x2c220e2c, 0xc538210e), new Long(0x52cb0d70, 0x8514214), new Long(0x85145142, 0x204b0850), new Long(0x4051440c, 0x92156083),
new Long(0xa60e6595, 0x4d660e4d), new Long(0x1c6dc658, 0x94d914e4), new Long(0x1454d365, 0x82642659), new Long(0x51030813, 0x2892072c),
new Long(0xcb2ca30b, 0xe2c22072), new Long(0x20538910, 0x452c70d7), new Long(0x708e3891, 0x8b2cb2d), new Long(0xc204b24e, 0x81cb1440),
new Long(0x28c2ca24, 0xda44e38e), new Long(0x85d660e4, 0x1dc6da65), new Long(0x8e5d914e, 0xe2cb5d33), new Long(0x38938238)
];
const offsetIncrs4 = /*3 bits per value */ [
new Long(0x00080000, 0x30020000), new Long(0x20c060), new Long(0x04000000, 0x81490000), new Long(0x10824824, 0x40249241),
new Long(0x60002082, 0xdb6030c3), new Long(0x301b0d80, 0x6c36c06c), new Long(0x000db0db, 0xb01861b0), new Long(0x9188e06d, 0x1b703620),
new Long(0x06d86db7, 0x8009200), new Long(0x02402490, 0x4920c24), new Long(0x08249009, 0x490002), new Long(0x28124804, 0x49081281),
new Long(0x124a44a2, 0x34800104), new Long(0x0d24020c, 0xc3093090), new Long(0x24c24d24, 0x40009a09), new Long(0x9201061a, 0x4984a06),
new Long(0x71269262, 0x494d0492), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249),
new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924),
new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492),
new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249),
new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x2492)
];
// 32 vectors; 45 states per vector; array length = 1440
const toStates5 = /*6 bits per value */ [
new Long(0x002c5004, 0x3801450), new Long(0x00000e38, 0xc500014b), new Long(0x51401402, 0x514), new Long(0x0),
new Long(0x14010000, 0x514000b), new Long(0x038e00e0, 0x550000), new Long(0x0600b180, 0x26451850), new Long(0x08208208, 0x82082082),
new Long(0x40820820, 0x2c500), new Long(0x808c0146, 0x70820a38), new Long(0x9c30827c, 0xc37c20c2), new Long(0x20800867, 0x208208),
new Long(0x02002080, 0xb1401020), new Long(0x00518000, 0x828e2023), new Long(0x209f1c20, 0x830a70c), new Long(0x853df0df, 0x51451450),
new Long(0x14508214, 0x16142142), new Long(0x30805050, 0x60260264), new Long(0x43082098, 0x25050806), new Long(0x14564014, 0x42000083),
new Long(0x20850051, 0x8500208), new Long(0x14140582, 0x80990c20), new Long(0x08261809, 0x82019202), new Long(0x90060941, 0x8920519),
new Long(0xc22cb242, 0x22492492), new Long(0x0162492c, 0x43080505), new Long(0x86026026, 0x80414515), new Long(0xc5b43142, 0x37c38020),
new Long(0x14508014, 0x42085085), new Long(0x50850051, 0x1414058), new Long(0x980990c2, 0x51456180), new Long(0x0c50a010, 0xe008316d),
new Long(0x508b21f0, 0x2c52cb2c), new Long(0xc22cb249, 0x600d2c92), new Long(0x1850821c, 0x873c21c0), new Long(0x03cb1420, 0x2c01cb14),
new Long(0x45185182, 0x20800821), new Long(0x08208000, 0x45002002), new Long(0x20871803, 0x8700614), new Long(0x050821cf, 0x740500f5),
new Long(0x18609000, 0x934d9646), new Long(0x30824d30, 0x4c24d34d), new Long(0xc600d642, 0x1860821), new Long(0x25dac274, 0xc2a072c9),
new Long(0x91c27472, 0x2c698398), new Long(0x89242242, 0x92420820), new Long(0x34b00900, 0x82087180), new Long(0xb09d0061, 0x1cb24976),
new Long(0x9d1cb0a8, 0x60e62470), new Long(0x1574ce3e, 0xd31455d7), new Long(0x25c25d74, 0x1c600d38), new Long(0x423c3142, 0x51515454),
new Long(0x1403c314, 0xc22c21cb), new Long(0x21431853, 0xb2c208), new Long(0x05145145, 0x34508b0), new Long(0x0c508718, 0x5515108f),
new Long(0xf2051454, 0x8740500), new Long(0x0618f090, 0xe2534d92), new Long(0x6592c238, 0x49382659), new Long(0x21c600d6, 0x4423c314),
new Long(0xcb2d1545, 0x72c2a042), new Long(0xa091c574, 0x422c3983), new Long(0x508b2c52, 0xb2c514), new Long(0x8034b08b, 0xf0c50871),
new Long(0x45515108, 0xa810b2cb), new Long(0x715d1cb0, 0x2260e824), new Long(0x8e2d74ce, 0xe6592c53), new Long(0x38938238, 0x420c3081),
new Long(0x22020cb1, 0x8508420), new Long(0xce0820ce, 0x70c25c20), new Long(0x08208b0d, 0x42082082), new Long(0x50821421, 0xc204208),
new Long(0x832c5083, 0x21080880), new Long(0x0838c214, 0xa5083882), new Long(0xa9c39430, 0xaaaaaaaa), new Long(0x9fa9faaa, 0x1aaa7eaa),
new Long(0x1420c308, 0x824820d0), new Long(0x84d94d64, 0x7184d371), new Long(0x1b7136d3, 0x34c24d07), new Long(0x1534d34d, 0x99093642),
new Long(0x30c20530, 0x8340508), new Long(0x53592092, 0x34dc6136), new Long(0x4db4dc61, 0xa479c6dc), new Long(0x4924924a, 0x920a9f92),
new Long(0x8192a82a, 0x72c22030), new Long(0x30930920, 0x724b24a), new Long(0x920e2422, 0xd72025c), new Long(0xc9082247, 0x92d70975),
new Long(0x24e0892c, 0x880c2049), new Long(0xc2481cb0, 0x2c928c24), new Long(0x89088749, 0x80a52488), new Long(0xaac74394, 0x6a861b2a),
new Long(0xab27b278, 0x81b2ca6), new Long(0x072c2203, 0xa3093092), new Long(0x6915ce5c, 0xd76985d3), new Long(0x771b6936, 0x5d74c25c),
new Long(0x892d74d7, 0x724e0973), new Long(0x0880c205, 0x4c2481cb), new Long(0x739728c2, 0x6174da45), new Long(0xda4db5da, 0x4aa175c6),
new Long(0x86486186, 0x6a869b27), new Long(0x308186ca, 0xcb14510), new Long(0x44205102, 0x220e2c51), new Long(0x38210e2c, 0xcb0d70c5),
new Long(0x51421452, 0x14514208), new Long(0x4b085085, 0x51440c20), new Long(0x1440832c, 0xcb145108), new Long(0x488b0888, 0x94316208),
new Long(0x9f7e79c3, 0xfaaa7dfa), new Long(0x7ea7df7d, 0x30819ea), new Long(0x20d01451, 0x65648558), new Long(0x93698399, 0x96135983),
new Long(0x39071b71, 0xd9653645), new Long(0x96451534, 0x4e09909), new Long(0x051440c2, 0x21560834), new Long(0x60e65959, 0xd660e4da),
new Long(0xc6dc6584, 0x9207e979), new Long(0xdf924820, 0xa82a8207), new Long(0x103081a6, 0x892072c5), new Long(0xb2ca30b2, 0x2c22072c),
new Long(0x0538910e, 0x52c70d72), new Long(0x08e38914, 0x8b2cb2d7), new Long(0x204b24e0, 0x1cb1440c), new Long(0x8c2ca248, 0x874b2cb2),
new Long(0x24488b08, 0x43948162), new Long(0x9b1f7e77, 0x9e786aa6), new Long(0xeca6a9e7, 0x51030819), new Long(0x2892072c, 0x8e38a30b),
new Long(0x83936913, 0x69961759), new Long(0x4538771b, 0x74ce3976), new Long(0x08e38b2d, 0xc204e24e), new Long(0x81cb1440, 0x28c2ca24),
new Long(0xda44e38e, 0x85d660e4), new Long(0x75c6da65, 0x698607e9), new Long(0x99e7864a, 0xa6ca6aa6)
];
const offsetIncrs5 = /*3 bits per value */ [
new Long(0x00080000, 0x30020000), new Long(0x20c060), new Long(0x04000000, 0x1000000), new Long(0x50603018, 0xdb6db6db),
new Long(0x00002db6, 0xa4800002), new Long(0x41241240, 0x12492088), new Long(0x00104120, 0x40000100), new Long(0x92092052, 0x2492c420),
new Long(0x096592d9, 0xc30d800), new Long(0xc36036d8, 0xb01b0c06), new Long(0x6c36db0d, 0x186c0003), new Long(0xb01b6c06, 0xad860361),
new Long(0x5b6dd6dd, 0x360001b7), new Long(0x0db6030c, 0xc412311c), new Long(0xb6e36e06, 0xdb0d), new Long(0xdb01861b, 0x9188e06),
new Long(0x71b72b62, 0x6dd6db), new Long(0x00800920, 0x40240249), new Long(0x904920c2, 0x20824900), new Long(0x40049000, 0x12012480),
new Long(0xa4906120, 0x5524ad4a), new Long(0x02480015, 0x40924020), new Long(0x48409409, 0x92522512), new Long(0x24000820, 0x49201001),
new Long(0x204a04a0, 0x29128924), new Long(0x00055549, 0x900830d2), new Long(0x24c24034, 0x934930c), new Long(0x02682493, 0x4186900),
new Long(0x61201a48, 0x9a498612), new Long(0x355249d4, 0xc348001), new Long(0x940d2402, 0x24c40930), new Long(0x0924e24d, 0x1a40009a),
new Long(0x06920106, 0x6204984a), new Long(0x92712692, 0x92494d54), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924),
new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492),
new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249),
new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924),
new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492),
new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249),
new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924),
new Long(0x49249249, 0x92492492), new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492),
new Long(0x24924924, 0x49249249), new Long(0x92492492, 0x24924924), new Long(0x49249249, 0x92492492), new Long(0x24924924)
];
// state map
// 0 -> [(0, 0)]
// 1 -> [(0, 2)]
// 2 -> [(0, 1)]
// 3 -> [(0, 1), (1, 1)]
// 4 -> [(0, 2), (1, 2)]
// 5 -> [t(0, 2), (0, 2), (1, 2), (2, 2)]
// 6 -> [(0, 2), (2, 1)]
// 7 -> [(0, 1), (2, 2)]
// 8 -> [(0, 2), (2, 2)]
// 9 -> [(0, 1), (1, 1), (2, 1)]
// 10 -> [(0, 2), (1, 2), (2, 2)]
// 11 -> [(0, 1), (2, 1)]
// 12 -> [t(0, 1), (0, 1), (1, 1), (2, 1)]
// 13 -> [(0, 2), (1, 2), (2, 2), (3, 2)]
// 14 -> [t(0, 2), (0, 2), (1, 2), (2, 2), (3, 2)]
// 15 -> [(0, 2), t(1, 2), (1, 2), (2, 2), (3, 2)]
// 16 -> [(0, 2), (2, 1), (3, 1)]
// 17 -> [(0, 1), t(1, 2), (2, 2), (3, 2)]
// 18 -> [(0, 2), (3, 2)]
// 19 -> [(0, 2), (1, 2), t(1, 2), (2, 2), (3, 2)]
// 20 -> [t(0, 2), (0, 2), (1, 2), (3, 1)]
// 21 -> [(0, 1), (1, 1), (3, 2)]
// 22 -> [(0, 2), (2, 2), (3, 2)]
// 23 -> [(0, 2), (1, 2), (3, 1)]
// 24 -> [(0, 2), (1, 2), (3, 2)]
// 25 -> [(0, 1), (2, 2), (3, 2)]
// 26 -> [(0, 2), (3, 1)]
// 27 -> [(0, 1), (3, 2)]
// 28 -> [(0, 2), (2, 1), (4, 2)]
// 29 -> [(0, 2), t(1, 2), (1, 2), (2, 2), (3, 2), (4, 2)]
// 30 -> [(0, 2), (1, 2), (4, 2)]
// 31 -> [(0, 2), (1, 2), (3, 2), (4, 2)]
// 32 -> [(0, 2), (2, 2), (3, 2), (4, 2)]
// 33 -> [(0, 2), (1, 2), t(2, 2), (2, 2), (3, 2), (4, 2)]
// 34 -> [(0, 2), (1, 2), (2, 2), t(2, 2), (3, 2), (4, 2)]
// 35 -> [(0, 2), (3, 2), (4, 2)]
// 36 -> [(0, 2), t(2, 2), (2, 2), (3, 2), (4, 2)]
// 37 -> [t(0, 2), (0, 2), (1, 2), (2, 2), (4, 2)]
// 38 -> [(0, 2), (1, 2), (2, 2), (4, 2)]
// 39 -> [t(0, 2), (0, 2), (1, 2), (2, 2), (3, 2), (4, 2)]
// 40 -> [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2)]
// 41 -> [(0, 2), (4, 2)]
// 42 -> [t(0, 2), (0, 2), (1, 2), (2, 2), t(2, 2), (3, 2), (4, 2)]
// 43 -> [(0, 2), (2, 2), (4, 2)]
// 44 -> [(0, 2), (1, 2), t(1, 2), (2, 2), (3, 2), (4, 2)]
/**
* From org/apache/lucene/util/automaton/Lev2TParametricDescription.java
* @hidden
*/
export class Lev2TParametricDescription extends ParametricDescription {
constructor(w: number) {
super(w, 2, [0, 2, 1, 0, 1, 0, -1, 0, 0, -1, 0, -1, -1, -1, -1, -1, -2, -1, -1, -1, -2, -1, -1, -2, -1, -1, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2]);
}
public transition(absState: number, position: number, vector: number): number {
// null absState should never be passed in
// assert absState != -1;
// decode absState -> state, offset
let state = Math.floor(absState / (this._w + 1));
let offset = absState % (this._w + 1);
// assert offset >= 0;
if (position === this._w) {
if (state < 3) {
const loc = vector * 3 + state;
offset += ParametricDescription.unpack(offsetIncrs0, loc, 1);
state = ParametricDescription.unpack(toStates0, loc, 2) - 1;
}
} else if (position === this._w - 1) {
if (state < 5) {
const loc = vector * 5 + state;
offset += ParametricDescription.unpack(offsetIncrs1, loc, 1);
state = ParametricDescription.unpack(toStates1, loc, 3) - 1;
}
} else if (position === this._w - 2) {
if (state < 13) {
const loc = vector * 13 + state;
offset += ParametricDescription.unpack(offsetIncrs2, loc, 2);
state = ParametricDescription.unpack(toStates2, loc, 4) - 1;
}
} else if (position === this._w - 3) {
if (state < 28) {
const loc = vector * 28 + state;
offset += ParametricDescription.unpack(offsetIncrs3, loc, 2);
state = ParametricDescription.unpack(toStates3, loc, 5) - 1;
}
} else if (position === this._w - 4) {
if (state < 45) {
const loc = vector * 45 + state;
offset += ParametricDescription.unpack(offsetIncrs4, loc, 3);
state = ParametricDescription.unpack(toStates4, loc, 6) - 1;
}
} else {
if (state < 45) {
const loc = vector * 45 + state;
offset += ParametricDescription.unpack(offsetIncrs5, loc, 3);
state = ParametricDescription.unpack(toStates5, loc, 6) - 1;
}
}
if (state === -1) {
// null state
return -1;
} else {
// translate back to abs
return state * (this._w + 1) + offset;
}
}
} | the_stack |
import jwt from 'jsonwebtoken'
import axios from 'axios'
import chalk from 'chalk'
import { ArrayChange, diffArrays } from 'diff'
import enquirer from 'enquirer'
import moment from 'moment'
import R, { compose, concat, contains, curry, head, last, prop, propSatisfies, reduce, split, tail, __ } from 'ramda'
import semverDiff from 'semver-diff'
import { createAppsClient } from '../clients/IOClients/infra/Apps'
import { createRegistryClient } from '../clients/IOClients/infra/Registry'
import { createWorkspacesClient } from '../clients/IOClients/infra/Workspaces'
import { getLastLinkReactDate, getNumberOfReactLinks, saveLastLinkReactDate, saveNumberOfReactLinks } from '../conf'
import { createFlowIssueError } from '../error/utils'
import log from '../logger'
import { ManifestEditor } from '../manifest'
import { SessionManager } from '../session/SessionManager'
import { createTable } from '../table'
import { promptConfirm } from './prompts'
import { reactTermsOfUse } from '../constants/Messages'
const workspaceExampleName = process.env.USER || 'example'
const workspaceMasterAllowedOperations = ['install', 'uninstall']
// It is not allowed to link apps in a production workspace.
const workspaceProductionAllowedOperatios = ['install', 'uninstall']
const builderHubMessagesLinkTimeout = 2000 // 2 seconds
const builderHubMessagesPublishTimeout = 10000 // 10 seconds
export const sleepSec = (sec: number) => new Promise(resolve => setTimeout(resolve, sec * 1000))
export const workspaceMasterMessage = `This action is ${chalk.red('not allowed')} in workspace ${chalk.green(
'master'
)}, please use another workspace.
You can run "${chalk.blue(`vtex use ${workspaceExampleName} -r`)}" to use a workspace named "${chalk.green(
workspaceExampleName
)}"`
export const workspaceProductionMessage = workspace =>
`This action is ${chalk.red('not allowed')} in workspace ${chalk.green(
workspace
)} because it is a production workspace. You can create a ${chalk.yellowBright('dev')} workspace called ${chalk.green(
workspaceExampleName
)} by running ${chalk.blue(`vtex use ${workspaceExampleName} -r`)}`
export const promptWorkspaceMaster = async account => {
const confirm = await promptConfirm(
`Are you sure you want to force this operation on the ${chalk.green(
'master'
)} workspace on the account ${chalk.blue(account)}?`,
false
)
if (!confirm) {
return false
}
log.warn(`Using ${chalk.green('master')} workspace. I hope you know what you're doing. 💥`)
return true
}
export const validateAppAction = async (operation: string, app?): Promise<boolean> => {
const { account, workspace } = SessionManager.getSingleton()
if (workspace === 'master') {
if (!contains(operation, workspaceMasterAllowedOperations)) {
throw createFlowIssueError(workspaceMasterMessage)
} else {
const confirm = await promptWorkspaceMaster(account)
if (!confirm) {
return false
}
}
}
const workspaces = createWorkspacesClient()
const workspaceMeta = await workspaces.get(account, workspace)
if (workspaceMeta.production && !contains(operation, workspaceProductionAllowedOperatios)) {
throw createFlowIssueError(workspaceProductionMessage(workspace))
}
// No app arguments and no manifest file.
const isReadable = await ManifestEditor.isManifestReadable()
if (!app && !isReadable) {
throw createFlowIssueError(
`No app was found, please fix your manifest.json${app ? ' or use <vendor>.<name>[@<version>]' : ''}`
)
}
return true
}
export const wildVersionByMajor = compose<string, string[], string, string>(concat(__, '.x'), head, split('.'))
export const extractVersionFromId = compose<string, string[], string>(last, split('@'))
export const pickLatestVersion = (versions: string[]): string => {
const start = head(versions)
return reduce(
(acc: string, version: string) => {
return semverDiff(acc, version) ? version : acc
},
start,
tail(versions)
)
}
export const handleError = curry((app: string, err: any) => {
if (err.response && err.response.status === 404) {
return Promise.reject(createFlowIssueError(`App ${chalk.green(app)} not found`))
}
return Promise.reject(err)
})
export const appLatestVersion = (app: string, version = 'x'): Promise<string | never> => {
return createRegistryClient()
.getAppManifest(app, version)
.then<string>(prop('id'))
.then<string>(extractVersionFromId)
.catch(handleError(app))
}
export const appLatestMajor = (app: string): Promise<string | never> => {
return appLatestVersion(app).then<string>(wildVersionByMajor)
}
export const appIdFromRegistry = (app: string, majorLocator: string) => {
return createRegistryClient()
.getAppManifest(app, majorLocator)
.then<string>(prop('id'))
.catch(handleError(app))
}
export const getVendorFromApp = (app: string) => {
const [vendor] = app.split('.')
return vendor
}
export async function checkBuilderHubMessage(cliRoute: string): Promise<any> {
const http = axios.create({
baseURL: `https://vtex.myvtex.com`,
timeout: cliRoute === 'link' ? builderHubMessagesLinkTimeout : builderHubMessagesPublishTimeout,
})
try {
const res = await http.get(`/_v/private/builder/0/getmessage/${cliRoute}`)
return res.data
} catch (e) {
return {}
}
}
const promptConfirmName = (msg: string): Promise<string> =>
enquirer
.prompt({
message: msg,
name: 'appName',
type: 'input',
})
.then<string>(prop('appName'))
export async function showBuilderHubMessage(message: string, showPrompt: boolean, manifest: ManifestEditor) {
if (message) {
if (showPrompt) {
const confirmMsg = `Are you absolutely sure?\n${message ||
''}\nPlease type in the name of the app to confirm (ex: vtex.getting-started):`
const appNameInput = await promptConfirmName(confirmMsg)
const AppName = `${manifest.vendor}.${manifest.name}`
if (appNameInput !== AppName) {
throw createFlowIssueError(`${appNameInput} doesn't match with the app name.`)
}
} else {
log.info(message)
}
}
}
export const resolveAppId = (appName: string, appVersion: string): Promise<string> => {
const apps = createAppsClient()
return apps.getApp(`${appName}@${appVersion}`).then(prop('id'))
}
export const isLinked = propSatisfies<string, Manifest>(contains('+build'), 'version')
export const yarnPath = `"${require.resolve('yarn/bin/yarn')}"`
export const formatNano = (nanoseconds: number): string =>
`${(nanoseconds / 1e9).toFixed(0)}s ${((nanoseconds / 1e6) % 1e3).toFixed(0)}ms`
const formatAppId = (appId: string) => {
const [appVendor, appName] = R.split('.', appId)
if (!appName) {
// Then the app is an 'infra' app.
const [infraAppVendor, infraAppName] = R.split(':', appId)
if (!infraAppName) {
return appId
}
return `${chalk.blue(infraAppVendor)}:${infraAppName}`
}
return `${chalk.blue(appVendor)}.${appName}`
}
const cleanVersion = (appId: string) => {
return R.compose<string, string[], string, string>(
(version: string) => {
const [pureVersion, build] = R.split('+build', version)
return build ? `${pureVersion}(linked)` : pureVersion
},
R.last,
R.split('@')
)(appId)
}
export const matchedDepsDiffTable = (title1: string, title2: string, deps1: string[], deps2: string[]) => {
const depsDiff = diffArrays(deps1, deps2)
// Get deduplicated names (no version) of the changed deps.
const depNames = [
...new Set(
R.compose<string[] | Array<ArrayChange<string>>, any[], string[], string[], string[]>(
R.map(k => R.head(R.split('@', k))),
R.flatten,
R.pluck('value'),
R.filter((k: any) => !!k.removed || !!k.added)
)(depsDiff)
),
].sort((strA, strB) => strA.localeCompare(strB))
const produceStartValues = () => R.map(_ => [])(depNames) as any
// Each of the following objects will start as a { `depName`: [] }, ... }-like.
const addedDeps = R.zipObj(depNames, produceStartValues())
const removedDeps = R.zipObj(depNames, produceStartValues())
// Custom function to set the objects values.
const setObjectValues = (obj, formatter, filterFunction) => {
R.compose<void | Array<ArrayChange<string>>, any[], any[], any[], any[]>(
// eslint-disable-next-line array-callback-return
R.map(k => {
const index = R.head(R.split('@', k))
obj[index].push(formatter(k))
}),
R.flatten,
R.pluck('value'),
R.filter(filterFunction)
)(depsDiff)
R.mapObjIndexed((_, index) => {
obj[index] = obj[index].join(',')
})(obj)
}
// Setting the objects values.
setObjectValues(
removedDeps,
k => chalk.red(`${cleanVersion(k)}`),
(k: any) => !!k.removed
)
setObjectValues(
addedDeps,
k => chalk.green(`${cleanVersion(k)}`),
(k: any) => !!k.added
)
const table = createTable() // Set table headers.
table.push(['', chalk.bold.yellow(title1), chalk.bold.yellow(title2)])
const formattedDepNames = R.map(formatAppId, depNames)
// Push array of changed dependencies pairs to the table.
Array.prototype.push.apply(
table,
R.map((k: any[]) => R.flatten(k))(
R.zip(
// zipping 3 arrays.
R.zip(formattedDepNames, R.values(removedDeps)),
R.values(addedDeps)
)
)
)
return table
}
const REACT_BUILDER = 'react'
const EMAIL_KEY = 'sub'
const I_VTEX_ACCOUNT = '@vtex.com'
const BR_VTEX_ACCOUNT = '@vtex.com.br'
export const continueAfterReactTermsAndConditions = async (manifest: ManifestEditor): Promise<boolean> => {
const session = SessionManager.getSingleton()
const { token } = session
const decodedToken = jwt.decode(token)
const userEmail = decodedToken?.[EMAIL_KEY] as string
if (userEmail && (userEmail.endsWith(I_VTEX_ACCOUNT) || userEmail.endsWith(BR_VTEX_ACCOUNT))) {
return true
}
if (!Object.keys(manifest.builders).includes(REACT_BUILDER)) {
return true
}
const count = getNumberOfReactLinks()
if (count && count > 1) {
return true
}
saveNumberOfReactLinks(count + 1)
const now = moment()
const lastShowDateString = getLastLinkReactDate()
if (lastShowDateString) {
const lastShowDate = moment(lastShowDateString)
console.log('lastShow', lastShowDate.toISOString())
const elapsedTime = moment.duration(now.diff(lastShowDate))
if (elapsedTime.asHours() < 24 && now.day() === lastShowDate.day()) {
return true
}
}
log.warn(reactTermsOfUse())
const confirm = await promptConfirm(`Do you want to continue?`, false)
if (confirm) {
saveLastLinkReactDate(now.toISOString())
}
return confirm
} | the_stack |
import React, { useCallback, useContext, useEffect, useMemo, useRef } from 'react';
import appContext from '../stores/appContext';
import { dailyNotesService, globalStateService, locationService, memoService, resourceService } from '../services';
import utils from '../helpers/utils';
import { storage } from '../helpers/storage';
import Editor, { EditorRefActions } from './Editor/Editor';
import '../less/memo-editor.less';
import '../less/select-date-picker.less';
import Tag from '../icons/tag.svg?component';
import ImageSvg from '../icons/image.svg?component';
import JournalSvg from '../icons/journal.svg?component';
import TaskSvg from '../icons/checkbox-active.svg?component';
import showEditorSvg from '../icons/show-editor.svg';
import { usePopper } from 'react-popper';
import useState from 'react-usestateref';
import DatePicker from './common/DatePicker';
import { moment, Notice, Platform } from 'obsidian';
import { DefaultEditorLocation, DefaultPrefix, FocusOnEditor, InsertDateFormat, UseButtonToShowEditor } from '../memos';
import useToggle from '../hooks/useToggle';
import { MEMOS_VIEW_TYPE } from '../constants';
import { t } from '../translations/helper';
const getCursorPostion = (input: HTMLTextAreaElement) => {
const {
offsetLeft: inputX,
offsetTop: inputY,
offsetHeight: inputH,
offsetWidth: inputW,
selectionEnd: selectionPoint,
} = input;
const div = document.createElement('div');
const copyStyle = window.getComputedStyle(input);
for (const item of copyStyle) {
div.style.setProperty(item, copyStyle.getPropertyValue(item));
}
div.style.position = 'fixed';
div.style.visibility = 'hidden';
div.style.whiteSpace = 'pre-wrap';
// we need a character that will replace whitespace when filling our dummy element if it's a single line <input/>
const swap = '.';
const inputValue = input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value;
div.textContent = inputValue.substring(0, selectionPoint || 0);
if (input.tagName === 'TEXTAREA') {
div.style.height = 'auto';
}
const span = document.createElement('span');
span.textContent = inputValue.substring(selectionPoint || 0) || '.';
div.appendChild(span);
document.body.appendChild(div);
const { offsetLeft: spanX, offsetTop: spanY, offsetHeight: spanH, offsetWidth: spanW } = span;
document.body.removeChild(div);
return {
x: inputX + spanX,
y: inputY + spanY,
h: inputH + spanH,
w: inputW + spanW,
};
};
interface Props {}
let isList: boolean;
let isEditor = false as boolean;
let isEditorGo = false as boolean;
let positionX: number;
const MemoEditor: React.FC<Props> = () => {
const { globalState } = useContext(appContext);
const { app } = dailyNotesService.getState();
const [isListShown, toggleList] = useToggle(false);
const [isEditorShown, toggleEditor] = useState(false);
const editorRef = useRef<EditorRefActions>(null);
const prevGlobalStateRef = useRef(globalState);
// const [selected, setSelected] = useState<Date>();
const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);
const popperRef = useRef<HTMLDivElement>(null);
const [popperElement, setPopperElement] = useState(null);
const [currentDateStamp] = useState(parseInt(moment().format('x')));
// const [showDatePicker, toggleShowDatePicker] = useToggle(false);
useEffect(() => {
if (!editorRef.current) {
return;
}
if (DefaultPrefix === 'List') {
isList = false;
toggleList(false);
} else {
isList = true;
toggleList(true);
}
isEditor = false;
// editorRef.current?.focus();
}, []);
useEffect(() => {
if (!editorRef.current) {
return;
}
const leaves = app.workspace.getLeavesOfType(MEMOS_VIEW_TYPE);
let memosWidth;
// let leafView;
if (leaves.length > 0) {
const leaf = leaves[0];
// leafView = leaf.view.containerEl;
memosWidth = leaf.width > 0 ? leaf.width : window.outerWidth;
} else {
// leafView = document;
memosWidth = window.outerWidth;
}
if ((Platform.isMobile === true || memosWidth < 875) && UseButtonToShowEditor) {
// if (isEditorGo === false) {
toggleEditor(true);
// }
}
if (FocusOnEditor) {
editorRef.current?.focus();
}
}, []);
useEffect(() => {
if (!editorRef.current) {
return;
}
if (
UseButtonToShowEditor === true &&
DefaultEditorLocation === 'Bottom' &&
Platform.isMobile === true &&
window.innerWidth < 875
) {
const leaves = app.workspace.getLeavesOfType(MEMOS_VIEW_TYPE);
let memosHeight;
let leafView;
if (leaves.length > 0) {
const leaf = leaves[0];
leafView = leaf.view.containerEl;
memosHeight = leafView.offsetHeight;
} else {
leafView = document;
memosHeight = window.innerHeight;
}
const divThis = document.createElement('img');
const memoEditorDiv = leafView.querySelector(
"div[data-type='memos_view'] .view-content .memo-editor-wrapper",
) as HTMLElement;
divThis.src = `${showEditorSvg}`;
if (isEditorShown) {
divThis.className = 'memo-show-editor-button hidden';
} else {
divThis.className = 'memo-show-editor-button';
}
const buttonTop = memosHeight - 200;
const buttonLeft = window.innerWidth / 2 - 25;
divThis.style.top = buttonTop + 'px';
divThis.style.left = buttonLeft + 'px';
divThis.onclick = function () {
const scaleElementAni = divThis.animate(
[
// keyframes
{ transform: 'rotate(0deg) scale(1)' },
{ transform: 'rotate(60deg) scale(1.5)' },
],
{
// timing options
duration: 300,
iterations: Infinity,
},
);
setTimeout(() => {
divThis.className = 'memo-show-editor-button hidden';
if (isEditor) {
handleShowEditor(false);
editorRef.current?.focus();
scaleElementAni.reverse();
// return;
} else {
handleShowEditor();
editorRef.current?.focus();
scaleElementAni.reverse();
}
// rotateElementAni.pause();
}, 300);
};
leafView.querySelector('.content-wrapper').prepend(divThis);
const memolistScroll = leafView.querySelector('.memolist-wrapper') as HTMLElement;
memolistScroll.onscroll = function () {
if (isEditor && !isEditorGo) {
isEditorGo = true;
const scaleEditorElementAni = memoEditorDiv.animate(
[
// keyframes
{ transform: 'scale(1)', opacity: 1 },
{ transform: 'scale(0.4)', opacity: 0 },
],
{
// timing options
duration: 300,
iterations: 1,
},
);
let scaleOneElementAni: Animation;
setTimeout(() => {
scaleOneElementAni = divThis.animate(
[
// keyframes
{ transform: 'rotate(20deg) scale(1.5)' },
{ transform: 'rotate(0deg) scale(1)' },
],
{
// timing options
duration: 100,
iterations: 1,
},
);
}, 300);
setTimeout(() => {
handleShowEditor(true);
divThis.className = 'memo-show-editor-button';
}, 300);
setTimeout(() => {
scaleOneElementAni.cancel();
scaleEditorElementAni.reverse();
}, 700);
}
};
} else if (
UseButtonToShowEditor === false &&
DefaultEditorLocation === 'Bottom' &&
Platform.isMobile === true &&
window.innerWidth < 875
) {
handleShowEditor(false);
if (FocusOnEditor) {
editorRef.current?.focus();
}
} else {
if (!isEditor) {
handleShowEditor(false);
}
if (FocusOnEditor) {
editorRef.current?.focus();
}
}
}, []);
// Change Date Picker Popper Position
const setPopper = () => {
let popperTemp;
if (!Platform.isMobile) {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'right-end',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['bottom'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
],
});
} else if (Platform.isMobile && DefaultEditorLocation !== 'Bottom') {
const seletorPopupWidth = 280;
if (window.innerWidth - positionX > seletorPopupWidth * 1.2) {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'right-end',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['left-end'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
} else if (window.innerWidth - positionX < seletorPopupWidth && window.innerWidth > seletorPopupWidth * 1.5) {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'left-end',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['right-end'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
} else {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'bottom',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['bottom'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
}
} else if (Platform.isMobile && DefaultEditorLocation === 'Bottom') {
const seletorPopupWidth = 280;
if (window.innerWidth - positionX > seletorPopupWidth * 1.2) {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'top-end',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['top-start'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
} else if (window.innerWidth - positionX < seletorPopupWidth && positionX > seletorPopupWidth) {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'top-start',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['top-end'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
} else {
popperTemp = usePopper(popperRef.current, popperElement, {
placement: 'top',
modifiers: [
{
name: 'flip',
options: {
allowedAutoPlacements: ['top'],
rootBoundary: 'document', // by default, all the placements are allowed
},
},
{
name: 'preventOverflow',
options: {
rootBoundary: 'document',
},
},
],
});
}
}
return popperTemp;
};
const popper = setPopper();
const closePopper = () => {
setIsDatePickerOpen(false);
// buttonRef?.current?.focus();
};
useEffect(() => {
if (globalState.markMemoId) {
const editorCurrentValue = editorRef.current?.getContent();
const memoLinkText = `${editorCurrentValue ? '\n' : ''}${t('MARK')}: [@MEMO](${globalState.markMemoId})`;
editorRef.current?.insertText(memoLinkText);
globalStateService.setMarkMemoId('');
}
if (globalState.editMemoId && globalState.editMemoId !== prevGlobalStateRef.current.editMemoId) {
const editMemo = memoService.getMemoById(globalState.editMemoId);
if (editMemo) {
editorRef.current?.setContent(editMemo.content.replace(/<br>/g, '\n').replace(/ \^\S{6}$/, '') ?? '');
editorRef.current?.focus();
}
}
prevGlobalStateRef.current = globalState;
}, [globalState.markMemoId, globalState.editMemoId]);
useEffect(() => {
if (!editorRef.current) {
return;
}
// new TagsSuggest(app, editorRef.current.element);
const handlePasteEvent = async (event: ClipboardEvent) => {
if (event.clipboardData && event.clipboardData.files.length > 0) {
event.preventDefault();
const file = event.clipboardData.files[0];
const url = await handleUploadFile(file);
if (url) {
editorRef.current?.insertText(url);
}
}
};
const handleDropEvent = async (event: DragEvent) => {
if (event.dataTransfer && event.dataTransfer.files.length > 0) {
event.preventDefault();
const file = event.dataTransfer.files[0];
const url = await handleUploadFile(file);
if (url) {
editorRef.current?.insertText(url);
}
}
};
const handleClickEvent = () => {
handleContentChange(editorRef.current?.element.value ?? '');
};
const handleKeyDownEvent = () => {
setTimeout(() => {
handleContentChange(editorRef.current?.element.value ?? '');
});
};
editorRef.current.element.addEventListener('paste', handlePasteEvent);
editorRef.current.element.addEventListener('drop', handleDropEvent);
editorRef.current.element.addEventListener('click', handleClickEvent);
editorRef.current.element.addEventListener('keydown', handleKeyDownEvent);
return () => {
editorRef.current?.element.removeEventListener('paste', handlePasteEvent);
editorRef.current?.element.removeEventListener('drop', handleDropEvent);
};
}, [editorRef.current]);
const handleUploadFile = useCallback(async (file: File) => {
const { type } = file;
if (!type.startsWith('image')) {
return;
}
try {
const image = await resourceService.upload(file);
return `${image}`;
} catch (error: any) {
new Notice(error);
}
}, []);
const handleSaveBtnClick = useCallback(async (content: string) => {
if (content === '') {
new Notice(t('Content cannot be empty'));
return;
}
const { editMemoId } = globalStateService.getState();
content = content.replaceAll(' ', ' ');
setEditorContentCache('');
try {
if (editMemoId) {
const prevMemo = memoService.getMemoById(editMemoId);
content = content + (prevMemo.hasId === '' ? '' : ' ^' + prevMemo.hasId);
if (prevMemo && prevMemo.content !== content) {
const editedMemo = await memoService.updateMemo(
prevMemo.id,
prevMemo.content,
content,
prevMemo.memoType,
prevMemo.path,
);
editedMemo.updatedAt = utils.getDateTimeString(Date.now());
memoService.editMemo(editedMemo);
}
globalStateService.setEditMemoId('');
} else {
const newMemo = await memoService.createMemo(content, isList);
memoService.pushMemo(newMemo);
// memoService.fetchAllMemos();
locationService.clearQuery();
}
} catch (error: any) {
new Notice(error.message);
}
setEditorContentCache('');
}, []);
const handleCancelBtnClick = useCallback(() => {
globalStateService.setEditMemoId('');
editorRef.current?.setContent('');
setEditorContentCache('');
}, []);
const handleContentChange = useCallback((content: string) => {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = content;
if (tempDiv.innerText.trim() === '') {
content = '';
}
setEditorContentCache(content);
if (!editorRef.current) {
return;
}
const currentValue = editorRef.current.getContent();
const selectionStart = editorRef.current.element.selectionStart;
const prevString = currentValue.slice(0, selectionStart);
const nextString = currentValue.slice(selectionStart);
if ((prevString.endsWith('@') || prevString.endsWith('📆')) && nextString.startsWith(' ')) {
updateDateSelectorPopupPosition();
setIsDatePickerOpen(true);
} else if ((prevString.endsWith('@') || prevString.endsWith('📆')) && nextString === '') {
updateDateSelectorPopupPosition();
setIsDatePickerOpen(true);
} else {
setIsDatePickerOpen(false);
}
setTimeout(() => {
editorRef.current?.focus();
});
}, []);
// const handleKeyPress = () => {
// console.log(handleKeyPress);
// };
const handleDateInsertTrigger = (date: number) => {
if (!editorRef.current) {
return;
}
if (date) {
closePopper();
isList = true;
toggleList(true);
}
const currentValue = editorRef.current.getContent();
const selectionStart = editorRef.current.element.selectionStart;
const prevString = currentValue.slice(0, selectionStart);
const nextString = currentValue.slice(selectionStart);
const todayMoment = moment(date);
if (!prevString.endsWith('@')) {
editorRef.current.element.value =
//eslint-disable-next-line
prevString + todayMoment.format('YYYY-MM-DD') + nextString;
editorRef.current.element.setSelectionRange(selectionStart + 10, selectionStart + 10);
editorRef.current.focus();
handleContentChange(editorRef.current.element.value);
return;
} else {
switch (InsertDateFormat) {
case 'Dataview':
editorRef.current.element.value =
//eslint-disable-next-line
currentValue.slice(0, editorRef.current.element.selectionStart - 1) +
'[due::' +
todayMoment.format('YYYY-MM-DD') +
']' +
nextString;
editorRef.current.element.setSelectionRange(selectionStart + 17, selectionStart + 17);
editorRef.current.focus();
handleContentChange(editorRef.current.element.value);
break;
case 'Tasks':
editorRef.current.element.value =
//eslint-disable-next-line
currentValue.slice(0, editorRef.current.element.selectionStart - 1) +
'📆' +
todayMoment.format('YYYY-MM-DD') +
nextString;
editorRef.current.element.setSelectionRange(selectionStart + 11, selectionStart + 11);
editorRef.current.focus();
handleContentChange(editorRef.current.element.value);
}
}
};
// Toggle List OR TASK
const handleChangeStatus = () => {
if (!editorRef.current) {
return;
}
if (isList) {
isList = false;
toggleList(false);
} else {
isList = true;
toggleList(true);
}
};
const handleShowEditor = (flag?: boolean) => {
if (!editorRef.current) {
return;
}
// Use flag to toggle editor show/hide
if (isEditor || flag === true) {
isEditor = false;
toggleEditor(true);
} else {
isEditor = true;
isEditorGo = false;
toggleEditor(false);
}
};
const handleTagTextBtnClick = useCallback(() => {
if (!editorRef.current) {
return;
}
const currentValue = editorRef.current.getContent();
const selectionStart = editorRef.current.element.selectionStart;
const prevString = currentValue.slice(0, selectionStart);
const nextString = currentValue.slice(selectionStart);
let nextValue = prevString + '# ' + nextString;
let cursorIndex = prevString.length + 1;
if (prevString.endsWith('#') && nextString.startsWith(' ')) {
nextValue = prevString.slice(0, prevString.length - 1) + nextString.slice(1);
cursorIndex = prevString.length - 1;
}
editorRef.current.element.value = nextValue;
editorRef.current.element.setSelectionRange(cursorIndex, cursorIndex);
editorRef.current.focus();
handleContentChange(editorRef.current.element.value);
}, []);
const updateDateSelectorPopupPosition = useCallback(() => {
if (!editorRef.current || !popperRef.current) {
return;
}
const leaves = app.workspace.getLeavesOfType(MEMOS_VIEW_TYPE);
const leaf = leaves[0];
const leafView = leaf.view.containerEl;
const seletorPopupWidth = 280;
const editorWidth = leafView.clientWidth;
// positionX = editorWidth;
const { x, y } = getCursorPostion(editorRef.current.element);
// const left = x + seletorPopupWidth + 16 > editorWidth ? editorWidth + 20 - seletorPopupWidth : x + 2;
let left: number;
let top: number;
if (!Platform.isMobile) {
left = x + seletorPopupWidth + 16 > editorWidth ? x + 18 : x + 18;
top = y + 34;
} else {
if (window.innerWidth - x > seletorPopupWidth) {
left = x + seletorPopupWidth + 16 > editorWidth ? x + 18 : x + 18;
} else if (window.innerWidth - x < seletorPopupWidth) {
left = x + seletorPopupWidth + 16 > editorWidth ? x + 34 : x + 34;
} else {
left = editorRef.current.element.clientWidth / 2;
}
if (DefaultEditorLocation === 'Bottom' && window.innerWidth > 875) {
top = y + 4;
} else if (DefaultEditorLocation === 'Bottom' && window.innerWidth <= 875) {
top = y + 19;
} else if (DefaultEditorLocation === 'Top' && window.innerWidth <= 875) {
top = y + 36;
}
}
positionX = x;
popperRef.current.style.left = `${left}px`;
popperRef.current.style.top = `${top}px`;
}, []);
const handleUploadFileBtnClick = useCallback(() => {
const inputEl = document.createElement('input');
document.body.appendChild(inputEl);
inputEl.type = 'file';
inputEl.multiple = false;
inputEl.accept = 'image/png, image/gif, image/jpeg';
inputEl.onchange = async () => {
if (!inputEl.files || inputEl.files.length === 0) {
return;
}
const file = inputEl.files[0];
const url = await handleUploadFile(file);
if (url) {
editorRef.current?.insertText(url);
}
document.body.removeChild(inputEl);
};
inputEl.click();
}, []);
const showEditStatus = Boolean(globalState.editMemoId);
const editorConfig = useMemo(
() => ({
className: 'memo-editor',
inputerType: 'memo',
initialContent: getEditorContentCache(),
placeholder: t('What do you think now...'),
showConfirmBtn: true,
showCancelBtn: showEditStatus,
showTools: true,
onConfirmBtnClick: handleSaveBtnClick,
onCancelBtnClick: handleCancelBtnClick,
onContentChange: handleContentChange,
}),
[showEditStatus],
);
return (
<div className={`memo-editor-wrapper ${showEditStatus ? 'edit-ing' : ''} ${isEditorShown ? 'hidden' : ''}`}>
<p className={`tip-text ${showEditStatus ? '' : 'hidden'}`}>Modifying...</p>
<Editor
ref={editorRef}
{...editorConfig}
tools={
<>
{/*<img className="action-btn add-tag" src={tag} />*/}
<Tag className="action-btn add-tag" onClick={handleTagTextBtnClick} />
{/*<img className="action-btn file-upload" src={imageSvg} onClick={handleUploadFileBtnClick} />*/}
<ImageSvg className="action-btn file-upload" onClick={handleUploadFileBtnClick} />
{/*<img*/}
{/* className="action-btn list-or-task"*/}
{/* src={`${!isListShown ? journalSvg : taskSvg}`}*/}
{/* onClick={handleChangeStatus}*/}
{/*/>*/}
{!isListShown ? (
<JournalSvg className="action-btn list-or-task" onClick={handleChangeStatus} />
) : (
<TaskSvg className="action-btn list-or-task" onClick={handleChangeStatus} />
)}
{/* <img className={`action-btn ${isListShown ? "" : "hidden"}`} src={taskSvg} onClick={handleChangeStatus} /> */}
</>
}
/>
<div ref={popperRef} className="date-picker">
{isDatePickerOpen && (
// <FocusTrap
// active
// focusTrapOptions={{
// initialFocus: false,
// allowOutsideClick: true,
// clickOutsideDeactivates: true,
// onDeactivate: closePopper,
// }}
// >
<div
tabIndex={-1}
style={popper.styles.popper}
{...popper.attributes.popper}
ref={setPopperElement}
role="dialog"
>
<DatePicker
className={`editor-date-picker ${isDatePickerOpen ? '' : 'hidden'}`}
datestamp={currentDateStamp}
handleDateStampChange={handleDateInsertTrigger}
/>
{/* <DayPicker
initialFocus={isPopperOpen}
mode="single"
defaultMonth={selected}
selected={selected}
onSelect={handleDateInsertTrigger}
onKeyPress={handleKeyPress}
/> */}
</div>
// </FocusTrap>
)}
</div>
</div>
);
};
function getEditorContentCache(): string {
return storage.get(['editorContentCache']).editorContentCache ?? '';
}
function setEditorContentCache(content: string) {
storage.set({
editorContentCache: content,
});
}
export default MemoEditor; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_resourcerequirement_Information {
interface Tabs {
}
interface Body {
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
}
class Formmsdyn_resourcerequirement_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_resourcerequirement_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_resourcerequirement_Information */
Body: DevKit.Formmsdyn_resourcerequirement_Information.Body;
}
namespace FormInfomation {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** Select the allocation method to be used for creating requirement distribution over a time period. */
msdyn_allocationmethod: DevKit.Controls.OptionSet;
/** Duration of total minutes required */
msdyn_duration: DevKit.Controls.Integer;
msdyn_fromdate: DevKit.Controls.Date;
/** The latitude to use for the location of a requirement. */
msdyn_Latitude: DevKit.Controls.Double;
/** The longitude to use for the location of a requirement. */
msdyn_Longitude: DevKit.Controls.Double;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Enter the percentage of the calendar capacity required. */
msdyn_percentage: DevKit.Controls.Decimal;
msdyn_PoolType: DevKit.Controls.MultiOptionSet;
/** Enter the number of resources required. */
msdyn_quantity: DevKit.Controls.Decimal;
/** Requirement Group */
msdyn_requirementgroupid: DevKit.Controls.Lookup;
msdyn_resourcetype: DevKit.Controls.MultiOptionSet;
/** Requirement Status */
msdyn_Status: DevKit.Controls.Lookup;
/** End date of requirement period */
msdyn_todate: DevKit.Controls.Date;
/** Select the type of resource requirement. */
msdyn_type: DevKit.Controls.OptionSet;
/** The working hours for a requirement. */
msdyn_workhourtemplate: DevKit.Controls.Lookup;
msdyn_WorkLocation: DevKit.Controls.OptionSet;
}
}
class FormInfomation extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Infomation
* @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 Infomation */
Body: DevKit.FormInfomation.Body;
}
class msdyn_resourcerequirementApi {
/**
* DynamicsCrm.DevKit msdyn_resourcerequirementApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Exchange rate for the currency associated with the entity with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Select the allocation method to be used for creating requirement distribution over a time period. */
msdyn_allocationmethod: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Appointment associated with Resource Requirement. */
msdyn_AppointmentRequirementId: DevKit.WebApi.LookupValue;
/** A unique identifier for the booking setup metadata that is associated with a resource requirement. */
msdyn_BookingSetupMetadataId: DevKit.WebApi.LookupValue;
/** The calendar that will be used for a resource requirement */
msdyn_CalendarId: DevKit.WebApi.StringValue;
/** Type the city where the resource is required. */
msdyn_city: DevKit.WebApi.StringValue;
/** Enter the cost price of the resource required. */
msdyn_costprice: DevKit.WebApi.MoneyValue;
/** Value of the Cost Price in base currency. */
msdyn_costprice_Base: DevKit.WebApi.MoneyValueReadonly;
/** Type the country/region where the resource is required. */
msdyn_country: DevKit.WebApi.StringValue;
/** Duration of total minutes required */
msdyn_duration: DevKit.WebApi.IntegerValue;
/** Effort that's required from resource capacity */
msdyn_effort: DevKit.WebApi.DecimalValue;
msdyn_fromdate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** The fulfilled duration, in minutes. */
msdyn_FulfilledDuration: DevKit.WebApi.IntegerValue;
/** Enter the hours fulfilled against requirement when the requirement status is fulfilled. */
msdyn_fulfilledhours: DevKit.WebApi.DecimalValue;
/** Enter the number of hours for which a requirement is required. */
msdyn_hours: DevKit.WebApi.DecimalValue;
/** For internal use only. */
msdyn_InternalFlags: DevKit.WebApi.StringValue;
msdyn_IsPrimary: DevKit.WebApi.BooleanValue;
/** Is template requirement */
msdyn_istemplate: DevKit.WebApi.BooleanValue;
/** The latitude to use for the location of a requirement. */
msdyn_Latitude: DevKit.WebApi.DoubleValue;
/** The longitude to use for the location of a requirement. */
msdyn_Longitude: DevKit.WebApi.DoubleValue;
/** The name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Enter the percentage of the calendar capacity required. */
msdyn_percentage: DevKit.WebApi.DecimalValue;
msdyn_PoolType: DevKit.WebApi.MultiOptionSetValue;
/** Priority of the requirement. To be taken into consideration while scheduling resources */
msdyn_Priority: DevKit.WebApi.LookupValue;
/** Select the project for which the resource is required. */
msdyn_projectid: DevKit.WebApi.LookupValue;
msdyn_ProposedDuration: DevKit.WebApi.IntegerValue;
/** Enter the number of resources required. */
msdyn_quantity: DevKit.WebApi.DecimalValue;
msdyn_RemainingDuration: DevKit.WebApi.IntegerValue;
/** The status of the resource request associated with this requirement. */
msdyn_requeststatus: DevKit.WebApi.StringValue;
/** The requirement group control view id of the resource requirement entity. This field will has value only when the entity is inside the requirement group control. */
msdyn_requirementgroupcontrolviewid: DevKit.WebApi.StringValue;
/** Requirement Group */
msdyn_requirementgroupid: DevKit.WebApi.LookupValue;
/** Requirement Relationship */
msdyn_requirementrelationshipid: DevKit.WebApi.LookupValue;
/** Unique identifier for entity instances */
msdyn_resourcerequirementId: DevKit.WebApi.GuidValue;
msdyn_resourcetype: DevKit.WebApi.MultiOptionSetValue;
/** Select the required role. */
msdyn_roleid: DevKit.WebApi.LookupValue;
/** Unique identifier for Service Appointment associated with Resource Requirement. */
msdyn_serviceappointment: DevKit.WebApi.LookupValue;
/** Sort option string field of resource requirement */
msdyn_sortoptions: DevKit.WebApi.StringValue;
/** Type the state/province where the resource is required. */
msdyn_stateorprovince: DevKit.WebApi.StringValue;
/** Requirement Status */
msdyn_Status: DevKit.WebApi.LookupValue;
/** template requirement id if requirement is created from template */
msdyn_templaterequirementid: DevKit.WebApi.StringValue;
msdyn_Territory: DevKit.WebApi.LookupValue;
/** Enter the starting range of the time promised to the account that incidents will be resolved. */
msdyn_TimeFromPromised_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_TimeGroup: DevKit.WebApi.LookupValue;
/** Enter the ending range of the time promised to the account that incidents will be resolved. */
msdyn_TimeToPromised_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_TimeWindowEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_TimeWindowStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** The Timezone in which the Time windows are defined by the User */
msdyn_timezonefortimewindow: DevKit.WebApi.IntegerValue;
/** End date of requirement period */
msdyn_todate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Select the type of resource requirement. */
msdyn_type: DevKit.WebApi.OptionSetValue;
/** The working hours for a requirement. */
msdyn_workhourtemplate: DevKit.WebApi.LookupValue;
msdyn_WorkLocation: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Work Order associated with Resource Requirement. */
msdyn_WorkOrder: DevKit.WebApi.LookupValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Resource Requirement */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Resource Requirement */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_resourcerequirement {
enum msdyn_allocationmethod {
/** 192350003 */
Distribute_evenly,
/** 192350005 */
Front_load,
/** 192350001 */
Full_capacity,
/** 192350000 */
None,
/** 192350004 */
Percentage_capacity
}
enum msdyn_PoolType {
/** 192350000 */
Account,
/** 192350001 */
Contact,
/** 192350003 */
Equipment,
/** 192350004 */
Facility,
/** 192350002 */
User
}
enum msdyn_resourcetype {
/** 5 */
Account,
/** 2 */
Contact,
/** 6 */
Crew,
/** 4 */
Equipment,
/** 7 */
Facility,
/** 1 */
Generic,
/** 8 */
Pool,
/** 3 */
User
}
enum msdyn_type {
/** 192350001 */
Extend,
/** 192350000 */
New
}
enum msdyn_WorkLocation {
/** 690970001 */
Facility,
/** 690970002 */
Location_Agnostic,
/** 690970000 */
Onsite
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Infomation','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import clsx from "clsx"
import React, { useCallback, useState } from "react"
import { CSSTransition, TransitionGroup } from "react-transition-group"
import Button from "@theme/Button"
import Chevron from "@theme/Chevron"
import PageLayout from "@theme/PageLayout"
import useResizeObserver from "@theme/useResizeObserver"
import caCss from "../css/customers/card.module.css"
import juCss from "../css/customers/jumbotron.module.css"
import quCss from "../css/customers/quote.module.css"
import seCss from "../css/section.module.css"
import _quotes from "../assets/quotes"
// temporary duplication across customer and enterprise page for quote module
const quotes = _quotes.map(({ author, company, logo, role, text }) => {
const Quote = () => (
<div key={company} className={quCss.quote}>
<div className={quCss.quote__symbol} />
<div className={quCss.quote__logo}>
<img
alt={logo.alt}
className="responsive-image"
height={logo.height}
src={logo.src}
width={logo.width}
style={{ top: logo.offset ?? 0 }}
/>
</div>
<p className={quCss.quote__content}>{text}</p>
<p className={quCss.quote__author}>
<span className={quCss.quote__chevron}>></span>
{author}
<br />
{role}
,
{company}
</p>
</div>
)
return Quote
})
type BulletProps = {
index: number
onClick: (index: number) => void
page: number
viewportSize: number
}
const Bullet = ({ index, onClick, page, viewportSize }: BulletProps) => {
const handleClick = useCallback(() => {
onClick(index * viewportSize)
}, [index, onClick, viewportSize])
return (
<span
className={clsx(quCss.controls__pin, {
[quCss["controls__pin--selected"]]: page === index,
})}
onClick={handleClick}
/>
)
}
const QUOTE_WIDTH = 350
const Customer = () => {
const title = "Customers"
const description =
"Discover how QuestDB is powering the core infrastructure of companies dealing with time-series data"
const { ref, width } = useResizeObserver<HTMLDivElement>()
// An "item" is a quote
// Index in the array of quotes of the item that is "focused"
const [index, setIndex] = useState(0)
// How many items we can show on the screen
const viewportSize = Math.max(1, Math.floor((width ?? 0) / QUOTE_WIDTH))
// How many items will actually be displayed (can be smaller than viewportSize)
const viewportCount =
viewportSize === 0 ? 0 : Math.ceil(quotes.length / viewportSize)
// Page number
const page = Math.floor(index / viewportSize)
// The quotes to show
const viewportQuotes = quotes.slice(
page * viewportSize,
(page + 1) * viewportSize,
)
const increaseIndex = useCallback(() => {
setIndex((index) => Math.min(index + viewportSize, quotes.length - 1))
}, [viewportSize])
const decreaseIndex = useCallback(() => {
setIndex((index) => Math.max(index - viewportSize, 0))
}, [viewportSize])
return (
<PageLayout canonical="/customers" description={description} title={title}>
<section className={clsx(seCss.section, seCss["section--odd"])}>
<div className={juCss.jumbotron}>
<div className={juCss.jumbotron__left}>
<h1 className={seCss.section__title}>Success Stories</h1>
<p
className={clsx(
seCss.section__subtitle,
juCss.jumbotron__subtitle,
)}
>
These are some of the most innovative stories from our users
highlighting how QuestDB is powering the core infrastructure of
companies working with time-series data.
</p>
</div>
<div className={juCss.jumbotron__illustration}>
<img
alt="People co-working on a dashboard"
height={274}
src="/img/pages/customers/top.svg"
width={250}
/>
</div>
</div>
</section>
<section
className={clsx(seCss["section--inner"], seCss["section--column"])}
>
<h2 className={quCss.title}>What our users say about QuestDB</h2>
<div className={quCss.carousel} ref={ref}>
<TransitionGroup component={null}>
<CSSTransition key={page} timeout={200} classNames="item">
<div className={quCss.carousel__group}>
{viewportQuotes.map((Quote) => (
<Quote key={quotes.indexOf(Quote)} />
))}
</div>
</CSSTransition>
</TransitionGroup>
</div>
<div className={quCss.controls}>
<div
className={clsx(
quCss["controls__chevron-wrapper"],
quCss["controls__chevron-wrapper--left"],
{
[quCss["controls__chevron-wrapper--hidden"]]: page === 0,
},
)}
onClick={decreaseIndex}
>
<Chevron className={quCss.controls__chevron} side="left" />
</div>
<div className={quCss.controls__middle}>
{Array(viewportCount)
.fill(0)
.map((_, idx) => (
<Bullet
index={idx}
key={idx}
onClick={setIndex}
page={page}
viewportSize={viewportSize}
/>
))}
</div>
<div
className={clsx(
quCss["controls__chevron-wrapper"],
quCss["controls__chevron-wrapper--right"],
{
[quCss["controls__chevron-wrapper--hidden"]]:
page === viewportCount - 1,
},
)}
onClick={increaseIndex}
>
<Chevron className={quCss.controls__chevron} side="right" />
</div>
</div>
</section>
<section className={clsx(seCss.section, seCss["section--inner"])}>
<div className={caCss.card}>
<div className={caCss.card__illustration}>
<img
alt="Yahoo logo"
height={400}
src="/img/pages/case-study/yahoo/summary.jpg"
width={525}
/>
</div>
<p className={caCss.card__summary}>
<img
alt="Yahoo logo"
className={caCss.card__logo}
height={50}
src="/img/pages/customers/cards/yahoo.svg"
width={140}
/>
“We use QuestDB to monitor metrics for autoscaling decisions within
our ML engine that provides search, recommendation, and
personalization via models and aggregations on continuously-changing
data.”
<em className={caCss.card__author}>
- <strong>Jon Bratseth</strong>, Yahoo
</em>
<Button className={caCss.card__cta} to="/case-study/yahoo/">
View full case study
</Button>
</p>
</div>
</section>
<section className={clsx(seCss.section, seCss["section--inner"])}>
<div className={caCss.card}>
<p className={caCss.card__summary}>
<img
alt="Toggle.global logo"
className={caCss.card__logo}
height={50}
src="/img/pages/customers/cards/toggle.svg"
width={140}
/>
“We switched from InfluxDB to QuestDB to get queries that are on
average 300x faster utilizing 1/4 of the hardware, without ever
overtaxing our servers.”
<em className={caCss.card__author}>
- <strong>Armenak Mayalian</strong>, Toggle
</em>
<Button className={caCss.card__cta} to="/case-study/toggle/">
View full case study
</Button>
</p>
<div className={caCss.card__illustration}>
<img
alt="Comparison of AI and chess to investing"
height={453}
src="/img/pages/case-study/toggle/summary.png"
width={600}
/>
</div>
</div>
</section>
<section className={clsx(seCss.section, seCss["section--inner"])}>
<div className={caCss.card}>
<div className={caCss.card__illustration}>
<img
alt="A CNC milling machine built by DATRON"
height={360}
src="/img/pages/case-study/datron/summary.png"
width={640}
/>
</div>
<p className={caCss.card__summary}>
<img
alt="Datron logo"
className={caCss.card__logo}
height={50}
src="/img/pages/customers/cards/datron.svg"
width={140}
/>
“QuestDB offers new possibilities while reducing costs and
simplifying data analysis.”
<em className={caCss.card__author}>
- <strong>Tim Borowski</strong>, DATRON
</em>
<Button className={caCss.card__cta} to="/case-study/datron/">
View full case study
</Button>
</p>
</div>
</section>
<section className={clsx(seCss.section, seCss["section--inner"])}>
<div className={caCss.card}>
<p className={caCss.card__summary}>
<img
alt="Innova logo"
className={caCss.card__logo}
height={50}
src="/img/pages/customers/cards/innova.svg"
width={140}
/>
“QuestDB allows us to query data while writing millions of records.
It is an excellent database for time series analysis, calculation of
aggregates and can efficiently store our data.”
<em className={caCss.card__author}>
- <strong>Erdem Aydemir</strong>, Innova
</em>
<Button className={caCss.card__cta} to="/case-study/innova/">
View full case study
</Button>
</p>
<div className={caCss.card__illustration}>
<img
alt="An illustration of a digital landscape"
height={360}
src="/img/pages/case-study/innova/summary.png"
width={640}
/>
</div>
</div>
</section>
</PageLayout>
)
}
export default Customer | the_stack |
import path from 'path';
import fs from 'fs-extra';
import program from 'commander';
import chalk from 'chalk';
import process from 'process';
import { pad, padStart, padEnd } from 'lodash';
import { FSHTank, RawFSH } from './import';
import { exportFHIR, Package } from './export';
import { IGExporter } from './ig';
import { loadCustomResources } from './fhirdefs';
import { FHIRDefinitions } from './fhirdefs';
import { Configuration } from './fshtypes';
import {
logger,
stats,
isSupportedFHIRVersion,
Type,
ensureInputDir,
findInputDir,
ensureOutputDir,
readConfig,
loadExternalDependencies,
fillTank,
writeFHIRResources,
writePreprocessedFSH,
getRawFSHes,
init,
getRandomPun,
setIgnoredWarnings
} from './utils';
const FSH_VERSION = '1.2.0';
app().catch(e => {
logger.error(`SUSHI encountered the following unexpected error: ${e.message}`);
process.exit(1);
});
async function app() {
let input: string;
program
.name('sushi')
.usage('[path-to-fsh-project] [options]')
.option('-o, --out <out>', 'the path to the output folder')
.option('-d, --debug', 'output extra debugging information')
.option('-p, --preprocessed', 'output FSH produced by preprocessing steps')
.option('-s, --snapshot', 'generate snapshot in Structure Definition output', false)
.option('-i, --init', 'initialize a SUSHI project')
.version(getVersion(), '-v, --version', 'print SUSHI version')
.on('--help', () => {
console.log('');
console.log('Additional information:');
console.log(' [path-to-fsh-project]');
console.log(' Default: "."');
console.log(' -o, --out <out>');
console.log(' Default: "fsh-generated"');
})
.arguments('[path-to-fsh-defs]')
.action(function (pathToFshDefs) {
input = pathToFshDefs;
})
.parse(process.argv);
if (program.init) {
await init();
process.exit(0);
}
if (program.debug) logger.level = 'debug';
input = ensureInputDir(input);
const rootIgnoreWarningsPath = path.join(input, 'sushi-ignoreWarnings.txt');
const nestedIgnoreWarningsPath = path.join(input, 'input', 'sushi-ignoreWarnings.txt');
if (fs.existsSync(rootIgnoreWarningsPath)) {
setIgnoredWarnings(fs.readFileSync(rootIgnoreWarningsPath, 'utf-8'));
if (fs.existsSync(nestedIgnoreWarningsPath)) {
logger.warn(
'Found sushi-ignoreWarnings.txt files in the following locations:\n\n' +
` - ${rootIgnoreWarningsPath}\n` +
` - ${nestedIgnoreWarningsPath}\n\n` +
`Only the file at ${rootIgnoreWarningsPath} will be processed. ` +
'Remove one of these files to avoid this warning.'
);
}
} else if (fs.existsSync(nestedIgnoreWarningsPath)) {
setIgnoredWarnings(fs.readFileSync(nestedIgnoreWarningsPath, 'utf-8'));
}
logger.info(`Running ${getVersion()}`);
logger.info('Arguments:');
if (program.debug) {
logger.info(' --debug');
}
if (program.preprocessed) {
logger.info(' --preprocessed');
}
if (program.snapshot) {
logger.info(' --snapshot');
}
if (program.out) {
logger.info(` --out ${path.resolve(program.out)}`);
}
logger.info(` ${path.resolve(input)}`);
const originalInput = input;
input = findInputDir(input);
// If an input/fsh subdirectory is used, we are in an IG Publisher context
const fshFolder = path.basename(input) === 'fsh';
const inputFshFolder = fshFolder && path.basename(path.dirname(input)) === 'input';
if (!inputFshFolder) {
// Since current supported tank configuration requires input/fsh folder,
// both legacy IG publisher mode and legacy flat tank cases occur when
// there is no input/fsh/ folder.
// If we detect this case, things are about to go very wrong, so exit immediately.
logger.error(
'Migration to current SUSHI project structure is required. See above error message for details. Exiting.'
);
process.exit(1);
}
const outDir = ensureOutputDir(input, program.out);
let tank: FSHTank;
let config: Configuration;
try {
let rawFSH: RawFSH[];
if (!fs.existsSync(input)) {
// If we have a path that ends with input/fsh but that folder does not exist,
// we are in a sushi-config.yaml-only case (current tank configuration with no FSH files)
// so we can safely say there are no FSH files and therefore rawFSH is empty.
rawFSH = [];
} else {
rawFSH = getRawFSHes(input);
}
if (rawFSH.length === 0 && !fs.existsSync(path.join(originalInput, 'sushi-config.yaml'))) {
logger.info('No FSH files or sushi-config.yaml present.');
process.exit(0);
}
config = readConfig(originalInput);
tank = fillTank(rawFSH, config);
} catch {
program.outputHelp();
process.exit(1);
}
// Load dependencies
const defs = new FHIRDefinitions();
await loadExternalDependencies(defs, config);
// Load custom resources. In current tank configuration (input/fsh), resources will be in input/
loadCustomResources(path.join(input, '..'), defs);
// Check for StructureDefinition
const structDef = defs.fishForFHIR('StructureDefinition', Type.Resource);
if (structDef == null || !isSupportedFHIRVersion(structDef.version)) {
logger.error(
'Valid StructureDefinition resource not found. The FHIR package in your local cache' +
' may be corrupt. Local FHIR cache can be found at <home-directory>/.fhir/packages.' +
' For more information, see https://wiki.hl7.org/FHIR_Package_Cache#Location.'
);
process.exit(1);
}
logger.info('Converting FSH to FHIR resources...');
const outPackage = exportFHIR(tank, defs);
writeFHIRResources(outDir, outPackage, defs, program.snapshot);
if (program.preprocessed) {
logger.info('Writing preprocessed FSH...');
writePreprocessedFSH(outDir, input, tank);
}
// If FSHOnly is true in the config, do not generate IG content, otherwise, generate IG content
if (config.FSHOnly) {
logger.info('Exporting FSH definitions only. No IG related content will be exported.');
} else {
const igFilesPath = path.resolve(input, '..', '..');
logger.info('Assembling Implementation Guide sources...');
const igExporter = new IGExporter(outPackage, defs, igFilesPath);
igExporter.export(outDir);
logger.info('Assembled Implementation Guide sources; ready for IG Publisher.');
if (
!fs
.readdirSync(outDir)
.some(file => file.startsWith('_genonce') || file.startsWith('_updatePublisher'))
) {
logger.info(
'The sample-ig located at https://github.com/FHIR/sample-ig contains scripts useful for downloading and running the IG Publisher.'
);
}
}
console.log();
printResults(outPackage);
process.exit(stats.numError);
}
function getVersion(): string {
const packageJSONPath = path.join(__dirname, '..', 'package.json');
if (fs.existsSync(packageJSONPath)) {
const sushiVersion = fs.readJSONSync(packageJSONPath)?.version;
return `SUSHI v${sushiVersion} (implements FHIR Shorthand specification v${FSH_VERSION})`;
}
return 'unknown';
}
function printResults(pkg: Package) {
// NOTE: These variables are creatively names to align well in the strings below while keeping prettier happy
const profileNum = pad(pkg.profiles.length.toString(), 13);
const extentNum = pad(pkg.extensions.length.toString(), 12);
const logiclNum = pad(pkg.logicals.length.toString(), 12);
const resourcNum = pad(pkg.resources.length.toString(), 13);
const valueSetsNumber = pad(pkg.valueSets.length.toString(), 18);
const codeSystemsNum = pad(pkg.codeSystems.length.toString(), 17);
const instancesNumber = pad(pkg.instances.length.toString(), 18);
const errorNumMsg = pad(`${stats.numError} Error${stats.numError !== 1 ? 's' : ''}`, 13);
const wrNumMsg = padStart(`${stats.numWarn} Warning${stats.numWarn !== 1 ? 's' : ''}`, 12);
const aWittyMessageInvolvingABadFishPun = padEnd(getRandomPun(stats.numError, stats.numWarn), 36);
const clr =
stats.numError > 0 ? chalk.red : stats.numWarn > 0 ? chalk.rgb(179, 98, 0) : chalk.green;
// NOTE: Doing some funky things w/ strings on some lines to keep overall alignment in the code
const results = [
clr('╔' + '════════════════════════ SUSHI RESULTS ══════════════════════════' + '' + '╗'),
clr('║') + ' ╭───────────────┬──────────────┬──────────────┬───────────────╮ ' + clr('║'),
clr('║') + ' │ Profiles │ Extensions │ Logicals │ Resources │ ' + clr('║'),
clr('║') + ' ├───────────────┼──────────────┼──────────────┼───────────────┤ ' + clr('║'),
clr('║') + ` │ ${profileNum} │ ${extentNum} │ ${logiclNum} │ ${resourcNum} │ ` + clr('║'),
clr('║') + ' ╰───────────────┴──────────────┴──────────────┴───────────────╯ ' + clr('║'),
clr('║') + ' ╭────────────────────┬───────────────────┬────────────────────╮ ' + clr('║'),
clr('║') + ' │ ValueSets │ CodeSystems │ Instances │ ' + clr('║'),
clr('║') + ' ├────────────────────┼───────────────────┼────────────────────┤ ' + clr('║'),
clr('║') + ` │ ${valueSetsNumber} │ ${codeSystemsNum} │ ${instancesNumber} │ ` + clr('║'),
clr('║') + ' ╰────────────────────┴───────────────────┴────────────────────╯ ' + clr('║'),
clr('║' + ' ' + '' + '║'),
clr('╠' + '═════════════════════════════════════════════════════════════════' + '' + '╣'),
clr('║') + ` ${aWittyMessageInvolvingABadFishPun} ${errorNumMsg} ${wrNumMsg} ` + clr('║'),
clr('╚' + '═════════════════════════════════════════════════════════════════' + '' + '╝')
];
const convertChars = !supportsFancyCharacters();
results.forEach(r => {
if (convertChars) {
r = r
.replace(/[╔╝╚╗╠╣═]/g, '=')
.replace(/[╭╯╰╮]/g, ' ')
.replace(/[─┬┼┴]/g, '-')
.replace(/[║│├┤]/g, '|');
}
console.log(r);
});
}
function supportsFancyCharacters(): boolean {
// There is no sure-fire way, but we know that most problems are when running in the IG Publisher,
// so try to detect that situation (which is still actually pretty tricky and not guaranteed).
// 1. Many JVM will insert an environment variable indicating the main Java class being run.
// E.g., JAVA_MAIN_CLASS_25538=org.hl7.fhir.igtools.publisher.Publisher
// We won't check the actual class; we'll just assume that if it's run in Java, best not take chances.
if (Object.keys(process.env).some(k => /^JAVA_MAIN_CLASS/.test(k))) {
return false;
}
// 2. It appears that in a Java-launched process, certain aspects of stdout aren't available, so
// use that to test if it's likely the fancy chars will be supported.
if (process.stdout.hasColors === undefined) {
return false;
}
// Otherwise, I guess (?) we're OK. Worst case scenario: user gets rubbish characters in the summary
return true;
} | the_stack |
import { fromFileUrl, html, join, marked, hljs } from '../deps_cli.ts';
import { Page } from './page.ts';
import { computeBreadcrumbs, SidebarNode } from './sidebar.ts';
import { SiteConfig, SiteSearchConfig } from './site_config.ts';
import { replaceSuffix } from './site_model.ts';
import { computeToc, Heading, TocNode } from './toc.ts';
export async function computeHtml(opts: { page: Page, path: string, contentRepoPath: string, config: SiteConfig, sidebar: SidebarNode, contentUpdateTime: number, inputDir: string,
manifestPath: string | undefined, localOrigin: string | undefined, verbose?: boolean, dumpEnv?: boolean }): Promise<string> {
const { page, path, contentRepoPath, config, sidebar, contentUpdateTime, verbose, inputDir, manifestPath, localOrigin } = opts;
const { markdown } = page;
const { siteMetadata, themeColor, themeColorDark, product, productRepo, contentRepo, productSvg, search } = config;
const { twitterUsername, image, imageAlt, faviconIco, faviconSvg, faviconMaskSvg, faviconMaskColor } = siteMetadata;
const title = `${page.titleResolved} · ${siteMetadata.title}`;
const description = page.frontmatter.summary || siteMetadata.description;
const origin = localOrigin || siteMetadata.origin || 'https://NO-ORIGIN';
const url = origin + path;
const imageUrl = typeof image === 'string' && image.startsWith('/') ? `${origin}${image}` : image;
let outputHtml = html`<!DOCTYPE html>
<html lang="en" theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
<meta name="description" content="${description}">
<meta property="og:title" content="${title}">
<meta property="og:description" content="${description}">
${ imageUrl ? html`<meta property="og:image" content="${imageUrl}">` : '' }
${ imageUrl && imageAlt ? html`<meta property="og:image:alt" content="${imageAlt}">` : '' }
<meta property="og:locale" content="en_US">
<meta property="og:type" content="website">
${ imageUrl ? html`<meta name="twitter:card" content="summary_large_image">` : '' }
${ twitterUsername ? html`<meta name="twitter:site" content="${twitterUsername}">` : '' }
<meta property="og:url" content="${url}">
<link rel="canonical" href="${url}">
${ faviconIco ? html`<link rel="icon" href="${faviconIco}">` : '' }
${ faviconSvg ? html`<link rel="icon" href="${faviconSvg}" type="image/svg+xml">` : '' }
${ faviconMaskSvg && faviconMaskColor ? html`<link rel="mask-icon" href="${faviconMaskSvg}" color="${faviconMaskColor}">` : '' }
${ manifestPath ? html`<link rel="manifest" href="${manifestPath}">` : '' }
${ themeColorDark ? html`<meta name="theme-color" content="${themeColorDark}" media="(prefers-color-scheme: dark)">` : '' }
${ themeColor ? html`<meta name="theme-color" content="${themeColor}">` : '' }
`.toString();
const designHtml = await computeDesignHtml();
const startMarker = '<!-- start -->';
outputHtml += designHtml.substring(designHtml.indexOf(startMarker) + startMarker.length);
// hide the organization stuff for now
outputHtml = outputHtml.replace('<div class="mobile-header">', '<div class="mobile-header" style="visibility:hidden;">');
outputHtml = outputHtml.replace('<div class="sidebar-section sidebar-header-section">', '<div class="sidebar-section sidebar-header-section" style="visibility:hidden;">');
// set product
outputHtml = outputHtml.replaceAll(/<!-- start: product -->.*?<!-- end: product -->/sg, escape(product));
// set product link
outputHtml = outputHtml.replaceAll(/ href="#product-link"/sg, ` href="/"`);
// set product logo
const productSvgContents = await readSvg(inputDir, productSvg);
outputHtml = outputHtml.replaceAll(/<!-- start: product logo -->(.*?)<!-- end: product logo -->/sg, (_, g1) => {
return computeProductLogoHtml(g1, productSvgContents);
});
// product github
outputHtml = outputHtml.replace(/<!-- start: product github -->(.*?)<!-- end: product github -->/s, (_, g1) => {
return computeProductGithubHtml(g1, productRepo);
});
// docsearch css
outputHtml = outputHtml.replace(/<!-- start: docsearch css -->(.*?)<!-- end: docsearch css -->/s, (_, g1) => {
return search ? g1 : '';
});
// docsearch script
outputHtml = outputHtml.replace(/<!-- start: docsearch script -->(.*?)<!-- end: docsearch script -->/s, (_, g1) => {
return search ? computeDocsearchScript(g1, search) : '';
});
// choose page type template
const isDocument = (page.frontmatter.type || 'document') === 'document';
if (isDocument) {
outputHtml = outputHtml.replace(/<!-- start: page-type="overview" -->.*?<!-- end: page-type="overview" -->/s, '');
} else {
outputHtml = outputHtml.replace(/<!-- start: page-type="document" -->.*?<!-- end: page-type="document" -->/s, '');
outputHtml = outputHtml.replace(` style="display:none;"`, '');
}
// render sidebar
outputHtml = outputHtml.replace(/<!-- start: sidebar -->.*?<!-- end: sidebar -->/s, (substr) => {
return computeSidebarHtml(substr, sidebar, path);
});
// render breadcrumbs
outputHtml = outputHtml.replace(/<!-- start: breadcrumb -->(.*?)<!-- end: breadcrumb -->/s, (_, g1) => {
return computeBreadcrumbsHtml(g1, sidebar, path);
});
// render markdown
const markdownResolved = markdown
// simple $ENV_VAR replacements
.replaceAll(/\$([_A-Z0-9]+)/g, (_, g1) => Deno.env.get(g1) || '')
// primary buttons
.replaceAll(/<Button\s+type="primary"\s+href="(.*?)"\s*>(.*?)<\/Button>/g, (_, g1, g2) => computePrimaryButtonHtml(g1, g2))
;
const tokens = marked.lexer(markdownResolved);
if (verbose) console.log(tokens);
const headings: Heading[] = [];
const renderer = new class extends marked.Renderer {
link(href: string | null, title: string | null, text: string): string {
if (typeof href === 'string' && /^https?:\/\//.test(href)) {
return computeExternalAnchorHtml(href, text);
}
let a = `<a class="markdown-link"`;
if (typeof href === 'string') a += ` href="${escape(href)}"`;
if (typeof title === 'string') a += ` title="${escape(title)}"`;
a += `><span class="markdown-link-content">${escape(text)}</span></a>`;
return a;
}
heading(text: string, level: 1 | 2 | 3 | 4 | 5 | 6, _raw: string, slugger: marked.Slugger): string {
const textEscaped = escape(text);
if (level === 1) return `<h1>${textEscaped}</h1>`;
const id = slugger.slug(text);
headings.push({ level, text, id });
const idEscaped = escape(id);
return '' +
`<h${level} id="${idEscaped}">
<span class="markdown-header-anchor-positioner">
<a class="markdown-header-anchor link link-without-underline" href="#${idEscaped}" aria-hidden="true"></a>
</span>
<span>${textEscaped}</span>
</h${level}>`;
}
code(code: string, language: string | undefined, _isEscaped: boolean): string {
if ((language || '').length === 0) {
return `<pre class="code-block code-block-scrolls-horizontally"><code>${escape(code)}</code></pre>`;
}
language = language === 'jsonc' ? 'json' : language; // highlight.js does not support jsonc
const highlightedCodeHtml = hljs.highlight(code, { language }).value;
return `<pre class="code-block code-block-scrolls-horizontally"><code>${highlightedCodeHtml}</code></pre>`;
}
codespan(code: string): string {
return `<code class="inline-code">${code}</code>`;
}
}();
const markdownHtml = marked.parser(tokens, { renderer });
outputHtml = outputHtml.replace(/<!-- start: markdown -->.*?<!-- end: markdown -->/s, markdownHtml);
// render toc
if (isDocument) {
const toc = computeToc(headings);
outputHtml = outputHtml.replace(/<!-- start: toc -->.*?<!-- end: toc -->/s, (substr) => {
return computeTocHtml(substr, toc);
});
}
// content github
outputHtml = outputHtml.replace(/<!-- start: content github -->(.*?)<!-- end: content github -->/s, (_, g1) => {
return computeContentGithubHtml(g1, contentRepoPath, contentRepo);
});
// content time
outputHtml = outputHtml.replace(/<!-- start: content time -->(.*?)<!-- end: content time -->/s, (_, g1) => {
return computeContentUpdateTimeHtml(g1, contentUpdateTime);
});
return outputHtml;
}
//
let _designHtml: string | undefined;
async function computeDesignHtml(): Promise<string> {
if (!_designHtml) {
const readOrFetchDesignHtml = async function() {
const designHtmlUrl = replaceSuffix(import.meta.url, '.ts', '.html', { required: false });
if (designHtmlUrl.startsWith('file://')) {
const path = fromFileUrl(designHtmlUrl);
return await Deno.readTextFile(path);
}
return await (await fetch(designHtmlUrl)).text();
}
_designHtml = await readOrFetchDesignHtml();
}
return _designHtml!;
}
function computeBreadcrumbsHtml(designHtml: string, sidebar: SidebarNode, path: string): string {
const breadcrumbs = computeBreadcrumbs(sidebar, path);
return breadcrumbs.map(v => computeBreadcrumbHtml(v, designHtml)).join('\n');
}
function computeBreadcrumbHtml(node: SidebarNode, designHtml: string): string {
return designHtml
.replaceAll(/<!-- start: breadcrumb-text -->(.*?)<!-- end: breadcrumb-text -->/g, escape(node.title))
.replace(/ href=".*?"/, ` href="${escape(node.path)}"`)
}
function computeSidebarHtml(designHtml: string, sidebar: SidebarNode, path: string): string {
let navItemWithChildrenTemplate = '';
let outputHtml = designHtml.replace(/<!-- start: sidebar-nav-item-with-children -->(.*?)<!-- end: sidebar-nav-item-with-children -->/s, (_, g1) => {
navItemWithChildrenTemplate = g1;
return '';
});
outputHtml = outputHtml.replace(/<!-- start: sidebar-nav-item -->(.*?)<!-- end: sidebar-nav-item -->/s, (_, g1) => {
const navItemTemplate: string = g1;
const pieces: string[] = [];
pieces.push(computeSidebarItemHtml(sidebar, path, navItemTemplate));
for (const child of sidebar.children) {
appendSidebarNodeHtml(child, path, navItemTemplate, navItemWithChildrenTemplate, pieces, 1);
}
return pieces.join('');
});
return outputHtml;
}
function appendSidebarNodeHtml(node: SidebarNode, path: string, navItemTemplate: string, navItemWithChildrenTemplate: string, pieces: string[], depth: number) {
if (node.children.length === 0) {
pieces.push(computeSidebarItemHtml(node, path, navItemTemplate));
} else {
let rt = computeSidebarItemHtml(node, path, navItemWithChildrenTemplate, depth);
rt = rt.replace(/<!-- start: children -->(.*?)<!-- end: children -->/s, () => {
const subpieces: string[] = [];
for (const child of node.children) {
appendSidebarNodeHtml(child, path, navItemTemplate, navItemWithChildrenTemplate, subpieces, depth + 1);
}
return subpieces.join('');
});
pieces.push(rt);
}
}
function computeSidebarItemHtml(node: SidebarNode, path: string, template: string, depth?: number): string {
let rt = template
.replaceAll(/<!-- start: sidebar-nav-item-text -->(.*?)<!-- end: sidebar-nav-item-text -->/g, escape(node.title))
.replace(/ href=".*?"/, ` href="${escape(node.path)}"`)
.replaceAll(`depth="1" style="--depth:1"`, `depth="${depth}" style="--depth:${depth}"`)
;
const active = node.path === path || (node.path + '/') === path;
if (!active) {
rt = rt.replaceAll(' is-active=""', '');
}
return rt;
}
const ENTITIES: { [char: string]: string } = {
"<": "<",
">": ">",
"&": "&",
"'": "'", // "'" is shorter than "'"
'"': """, // """ is shorter than """
};
function escape(text: string): string {
return text.replaceAll(/[&<>"']/g, (char) => {
return ENTITIES[char];
});
}
function computeTocHtml(designHtml: string, toc: TocNode[]): string {
if (toc.length === 0) return '';
let tocItemWithChildrenTemplate = '';
let outputHtml = designHtml.replace(/<!-- start: toc-item-with-children -->(.*?)<!-- end: toc-item-with-children -->/s, (_, g1) => {
tocItemWithChildrenTemplate = g1;
return '';
});
outputHtml = outputHtml.replace(/<!-- start: toc-item -->(.*?)<!-- end: toc-item -->/s, (_, g1) => {
const tocItemTemplate: string = g1;
const pieces: string[] = [];
for (const tocItem of toc) {
appendTocNodeHtml(tocItem, tocItemTemplate, tocItemWithChildrenTemplate, pieces);
}
return pieces.join('');
});
return outputHtml;
}
function appendTocNodeHtml(node: TocNode, tocItemTemplate: string, tocItemWithChildrenTemplate: string, pieces: string[]) {
const children = node.children || [];
if (children.length === 0) {
pieces.push(computeTocItemHtml(node, tocItemTemplate));
} else {
let rt = computeTocItemHtml(node, tocItemWithChildrenTemplate);
rt = rt.replace(/<!-- start: toc-children -->(.*?)<!-- end: toc-children -->/s, () => {
const subpieces: string[] = [];
for (const child of children) {
appendTocNodeHtml(child, tocItemTemplate, tocItemWithChildrenTemplate, subpieces);
}
return subpieces.join('');
});
pieces.push(rt);
}
}
function computeTocItemHtml(node: TocNode, template: string): string {
return template
.replaceAll(/<!-- start: toc-item-text -->(.*?)<!-- end: toc-item-text -->/g, escape(node.title))
.replace(/ href=".*?"/, ` href="#${escape(node.anchorId)}"`);
}
function computeProductGithubHtml(designHtml: string, productRepo: string | undefined): string {
if (!productRepo) return '';
return designHtml.replace(/ href=".*?"/, ` href="https://github.com/${escape(productRepo)}"`);
}
function computeContentGithubHtml(designHtml: string, contentRepoPath: string, contentRepo: string | undefined): string {
if (!contentRepo) return '';
return designHtml.replace(/ href=".*?"/, ` href="https://github.com/${escape(contentRepo)}/blob/HEAD${escape(contentRepoPath)}"`);
}
function computeContentUpdateTimeHtml(_designHtml: string, contentUpdateTime: number): string {
const instant = new Date(contentUpdateTime).toISOString();
return html`<time datetime="${instant}" title="${instant}">${instant}</time>`.toString();
}
function computeExternalAnchorHtml(href: string, text: string): string {
return html
`<a href="${href}" class="markdown-link">
<span class="markdown-link-content">${text}</span><span class="markdown-link-external-icon" aria-hidden="true">
<svg fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 16 16" role="img" aria-labelledby="title-for-external-link-icon" xmlns="http://www.w3.org/2000/svg"><title id="title-for-external-link-icon">External link icon</title><path d="M6.75,1.75h-5v12.5h12.5v-5m0,-4v-3.5h-3.5M8,8l5.5-5.5"></path></svg>
<span is-visually-hidden="">Open external link</span>
</span>
</a>`.toString();
}
function computeProductLogoHtml(designHtml: string, productSvgContents: string | undefined): string {
return productSvgContents || designHtml;
}
async function readSvg(inputDir: string, svgPath: string | undefined): Promise<string | undefined> {
if (!svgPath) return undefined;
const path = join(inputDir, svgPath);
const contents = await Deno.readTextFile(path);
const i = contents.indexOf('<svg');
return i < 0 ? contents : contents.substring(i);
}
function computePrimaryButtonHtml(href: string, text: string): string {
return html
`<p>
<a href="${href}" class="button button-is-primary">${text}</a>
</p>`.toString();
}
function computeDocsearchScript(designHtml: string, search: SiteSearchConfig): string {
return designHtml
.replace('${appId}', search.appId)
.replace('${apiKey}', search.apiKey)
.replace('${indexName}', search.indexName);
} | the_stack |
import { CstNode, IToken } from 'chevrotain';
import {
Condition,
ConditionWithValueQuery,
DateLiteral,
DateNLiteral,
Field,
FieldFunctionExpression,
FieldRelationship,
FieldRelationshipWithAlias,
FieldSubquery,
FieldType,
FieldTypeOf,
FieldTypeOfCondition,
FieldWithAlias,
FunctionExp,
GroupByClause,
HavingClause,
HavingClauseWithRightCondition,
LiteralType,
NullsOrder,
OrderByClause,
OrderByCriterion,
OrderByFnClause,
Query,
Subquery,
ValueCondition,
ValueFunctionCondition,
ValueQueryCondition,
ValueWithDateNLiteralCondition,
WhereClause,
WhereClauseWithRightCondition,
WithDataCategoryCondition,
} from '../api/api-models';
import {
ApexBindVariableExpressionContext,
ApexBindVariableFunctionArrayAccessorContext,
ApexBindVariableFunctionCallContext,
ApexBindVariableFunctionParamsContext,
ApexBindVariableGenericContext,
ApexBindVariableIdentifierContext,
ApexBindVariableNewInstantiationContext,
ArrayExpressionWithType,
AtomicExpressionContext,
BooleanContext,
ConditionExpressionContext,
DateNLiteralContext,
ExpressionContext,
ExpressionOperatorContext,
ExpressionTree,
FieldFunctionContext,
FieldsFunctionContext,
FromClauseContext,
FunctionExpressionContext,
GeoLocationFunctionContext,
GroupByClauseContext,
HavingClauseContext,
LiteralTypeWithSubquery,
LocationFunctionContext,
OperatorContext,
OrderByClauseContext,
OrderByExpressionContext,
OrderByGroupingFunctionExpressionContext,
OrderBySpecialFunctionExpressionContext,
SelectClauseContext,
SelectClauseFunctionIdentifierContext,
SelectClauseIdentifierContext,
SelectClauseSubqueryIdentifierContext,
SelectClauseTypeOfContext,
SelectClauseTypeOfElseContext,
SelectClauseTypeOfThenContext,
SelectStatementContext,
usingScopeClauseContext,
ValueContext,
WhereClauseContext,
WhereClauseSubqueryContext,
WithClauseContext,
WithDateCategoryContext,
} from '../models';
import { isString, isSubqueryFromFlag, isToken } from '../utils';
import { parse, ParseQueryConfig, SoqlParser } from './parser';
const parser = new SoqlParser();
const BaseSoqlVisitor = parser.getBaseCstVisitorConstructor();
const BOOLEANS = ['TRUE', 'FALSE'];
const DATE_LITERALS: DateLiteral[] = [
'YESTERDAY',
'TODAY',
'TOMORROW',
'LAST_WEEK',
'THIS_WEEK',
'NEXT_WEEK',
'LAST_MONTH',
'THIS_MONTH',
'NEXT_MONTH',
'LAST_90_DAYS',
'NEXT_90_DAYS',
'THIS_QUARTER',
'LAST_QUARTER',
'NEXT_QUARTER',
'THIS_YEAR',
'LAST_YEAR',
'NEXT_YEAR',
'THIS_FISCAL_QUARTER',
'LAST_FISCAL_QUARTER',
'NEXT_FISCAL_QUARTER',
'THIS_FISCAL_YEAR',
'LAST_FISCAL_YEAR',
'NEXT_FISCAL_YEAR',
];
const DATE_N_LITERALS: DateNLiteral[] = [
'NEXT_N_DAYS',
'LAST_N_DAYS',
'N_DAYS_AGO',
'NEXT_N_WEEKS',
'LAST_N_WEEKS',
'N_WEEKS_AGO',
'NEXT_N_MONTHS',
'LAST_N_MONTHS',
'N_MONTHS_AGO',
'NEXT_N_QUARTERS',
'LAST_N_QUARTERS',
'N_QUARTERS_AGO',
'NEXT_N_YEARS',
'LAST_N_YEARS',
'N_YEARS_AGO',
'NEXT_N_FISCAL_QUARTERS',
'LAST_N_FISCAL_QUARTERS',
'N_FISCAL_QUARTERS_AGO',
'NEXT_N_FISCAL_YEARS',
'LAST_N_FISCAL_YEARS',
'N_FISCAL_YEARS_AGO',
];
class SOQLVisitor extends BaseSoqlVisitor {
constructor() {
super();
this.validateVisitor();
}
private helpers = {
$_getFieldFunction: (ctx: FieldFunctionContext, isAggregateFn = false, includeType = true): FunctionExp | FieldFunctionExpression => {
const args = ctx.functionExpression
? ctx.functionExpression.map((node: any) => this.visit(ctx.functionExpression, { includeType })).flat()
: [];
const output: any = {};
if (includeType) {
output.type = 'FieldFunctionExpression';
}
output.functionName = ctx.fn[0].tokenType.name;
output.parameters = args;
if (includeType && isAggregateFn) {
output.isAggregateFn = isAggregateFn;
}
output.rawValue = `${ctx.fn[0].image}(${args.map((arg: any) => (typeof arg === 'string' ? arg : arg.rawValue)).join(', ')})`;
return output;
},
$_getLiteralTypeFromTokenType: (tokenTypeName: string | DateLiteral | DateNLiteral): LiteralType => {
if (tokenTypeName === 'REAL_NUMBER') {
return 'DECIMAL';
} else if (tokenTypeName === 'CURRENCY_PREFIXED_DECIMAL') {
return 'DECIMAL_WITH_CURRENCY_PREFIX';
} else if (tokenTypeName === 'CURRENCY_PREFIXED_INTEGER') {
return 'INTEGER_WITH_CURRENCY_PREFIX';
} else if (tokenTypeName === 'SIGNED_DECIMAL') {
return 'DECIMAL';
} else if (tokenTypeName === 'UNSIGNED_DECIMAL') {
return 'DECIMAL';
} else if (tokenTypeName === 'UNSIGNED_INTEGER') {
return 'INTEGER';
} else if (tokenTypeName === 'SIGNED_INTEGER') {
return 'INTEGER';
} else if (tokenTypeName === 'DATETIME') {
return 'DATETIME';
} else if (tokenTypeName === 'DATE') {
return 'DATE';
} else if (tokenTypeName === 'NULL') {
return 'NULL';
} else if (tokenTypeName === 'StringIdentifier') {
return 'STRING';
} else if (tokenTypeName === 'Identifier') {
return 'STRING';
} else if (BOOLEANS.includes(tokenTypeName)) {
return 'BOOLEAN';
} else if (DATE_LITERALS.includes(tokenTypeName as DateLiteral)) {
return 'DATE_LITERAL';
} else if (DATE_N_LITERALS.includes(tokenTypeName as DateNLiteral)) {
return 'DATE_N_LITERAL';
} else {
return 'STRING';
}
},
};
/**
* This is the only public entry point for the parser
* @param ctx
* @param options
*/
selectStatement(ctx: SelectStatementContext, options?: { isSubquery: boolean }): Query | Subquery {
const { isSubquery } = options || { isSubquery: false };
const output: Partial<Query | Subquery> = {};
output.fields = this.visit(ctx.selectClause);
if (isSubqueryFromFlag(output, isSubquery)) {
const { sObject, alias, sObjectPrefix } = this.visit(ctx.fromClause);
output.relationshipName = sObject;
if (alias) {
output.sObjectAlias = alias;
}
if (sObjectPrefix) {
output.sObjectPrefix = sObjectPrefix;
}
} else {
const { sObject, alias } = this.visit(ctx.fromClause);
(output as Query).sObject = sObject;
if (alias) {
output.sObjectAlias = alias;
}
}
if (!!output.sObjectAlias) {
output.fields.forEach((field: any) => {
if (field.relationships && field.relationships[0] === output.sObjectAlias) {
field.relationships = field.relationships.slice(1);
field.objectPrefix = output.sObjectAlias;
}
if (field.relationships && field.relationships.length === 0) {
delete field.relationships;
field.type = 'Field';
}
});
}
if (ctx.usingScopeClause && !ctx.usingScopeClause[0].recoveredNode) {
output.usingScope = this.visit(ctx.usingScopeClause);
}
if (ctx.whereClause && !ctx.whereClause[0].recoveredNode) {
output.where = this.visit(ctx.whereClause);
}
if (ctx.withClause) {
ctx.withClause
.filter(item => !item.recoveredNode)
.forEach(item => {
const { withSecurityEnforced, withDataCategory } = this.visit(item);
if (withSecurityEnforced) {
output.withSecurityEnforced = withSecurityEnforced;
}
if (withDataCategory) {
output.withDataCategory = withDataCategory;
}
});
}
if (ctx.groupByClause && !ctx.groupByClause[0].recoveredNode) {
output.groupBy = this.visit(ctx.groupByClause);
}
if (ctx.havingClause && !ctx.havingClause[0].recoveredNode) {
output.having = this.visit(ctx.havingClause);
}
if (ctx.orderByClause && !ctx.orderByClause[0].recoveredNode) {
output.orderBy = this.visit(ctx.orderByClause);
}
if (ctx.limitClause && !ctx.limitClause[0].recoveredNode) {
output.limit = Number(this.visit(ctx.limitClause));
}
if (ctx.offsetClause && !ctx.offsetClause[0].recoveredNode) {
output.offset = Number(this.visit(ctx.offsetClause));
}
if (ctx.forViewOrReference && !ctx.forViewOrReference[0].recoveredNode) {
output.for = this.visit(ctx.forViewOrReference);
}
if (ctx.updateTrackingViewstat && !ctx.updateTrackingViewstat[0].recoveredNode) {
output.update = this.visit(ctx.updateTrackingViewstat);
}
return output as Query | Subquery;
}
selectClause(ctx: SelectClauseContext): string[] {
if (ctx.field) {
return ctx.field.map(item => {
if (isToken(item)) {
const field: string = item.image;
let output: FieldType;
if (!field.includes('.')) {
output = {
type: 'Field',
field: field,
// objectPrefix: undefined, // TODO: we cannot add this until the very und when we see if the sobject is aliased
};
} else {
const splitFields = field.split('.');
output = {
type: 'FieldRelationship',
field: splitFields[splitFields.length - 1],
relationships: splitFields.slice(0, splitFields.length - 1),
// objectPrefix: undefined, // TODO: we cannot add this until the very und when we see if the sobject is aliased
rawValue: field,
};
}
return output;
} else {
return this.visit(item);
}
});
}
return [];
}
selectClauseFunctionIdentifier(ctx: SelectClauseFunctionIdentifierContext): FieldRelationship | FieldRelationshipWithAlias {
let output: FieldRelationship | FieldRelationshipWithAlias = {
...this.visit(ctx.fn),
};
if (ctx.alias) {
(output as FieldRelationshipWithAlias).alias = ctx.alias[0].image;
}
return output;
}
selectClauseSubqueryIdentifier(ctx: SelectClauseSubqueryIdentifierContext): FieldSubquery {
return {
type: 'FieldSubquery',
subquery: this.visit(ctx.selectStatement, { isSubquery: true }),
};
}
selectClauseTypeOf(ctx: SelectClauseTypeOfContext): FieldTypeOf {
let conditions: FieldTypeOfCondition[] = ctx.selectClauseTypeOfThen.map((item: any) => this.visit(item));
if (ctx.selectClauseTypeOfElse) {
conditions.push(this.visit(ctx.selectClauseTypeOfElse));
}
return {
type: 'FieldTypeof',
field: ctx.typeOfField[0].image,
conditions,
};
}
selectClauseIdentifier(ctx: SelectClauseIdentifierContext): Field | FieldRelationship {
const item = ctx.field[0];
const alias = !!ctx.alias ? ctx.alias[0].image : undefined;
const field: string = item.image;
let output: FieldType;
if (!field.includes('.')) {
output = {
type: 'Field',
field: field,
// objectPrefix: undefined, // TODO: we cannot add this until the very und when we see if the sobject is aliased
};
} else {
const splitFields = field.split('.');
output = {
type: 'FieldRelationship',
field: splitFields[splitFields.length - 1],
relationships: splitFields.slice(0, splitFields.length - 1),
// objectPrefix: undefined, // TODO: we cannot add this until the very und when we see if the sobject is aliased
rawValue: field,
};
}
if (alias) {
(output as FieldWithAlias | FieldRelationshipWithAlias).alias = alias;
}
return output;
}
selectClauseTypeOfThen(ctx: SelectClauseTypeOfThenContext): FieldTypeOfCondition {
return {
type: 'WHEN',
objectType: ctx.typeOfField[0].image,
fieldList: ctx.field.map((item: any) => item.image),
};
}
selectClauseTypeOfElse(ctx: SelectClauseTypeOfElseContext): FieldTypeOfCondition {
return {
type: 'ELSE',
fieldList: ctx.field.map((item: any) => item.image),
};
}
fromClause(ctx: FromClauseContext) {
let sObject: string = ctx.Identifier[0].image;
let output: any;
if (sObject.includes('.')) {
const sObjectPrefix = sObject.split('.');
output = {
sObjectPrefix: sObjectPrefix.slice(0, sObjectPrefix.length - 1),
sObject: sObjectPrefix[sObjectPrefix.length - 1],
};
} else {
output = {
sObject,
};
}
if (ctx.alias && ctx.alias[0]) {
output.alias = ctx.alias[0].image;
}
return output;
}
usingScopeClause(ctx: usingScopeClauseContext) {
return ctx.UsingScopeEnumeration[0].image;
}
whereClauseSubqueryIdentifier(ctx: WhereClauseSubqueryContext) {
return this.visit(ctx.selectStatement, { isSubquery: false });
}
whereClause(ctx: WhereClauseContext): WhereClause {
const where = ctx.conditionExpression.reduce(
(expressions: ExpressionTree<WhereClause>, currExpression: any) => {
if (!expressions.expressionTree) {
const tempExpression: WhereClauseWithRightCondition = this.visit(currExpression);
expressions.expressionTree = tempExpression;
expressions.prevExpression = tempExpression.right ? tempExpression.right : tempExpression;
} else {
const tempExpression: WhereClauseWithRightCondition = this.visit(currExpression, { prevExpression: expressions.prevExpression });
(expressions.prevExpression as WhereClauseWithRightCondition).right = tempExpression;
expressions.prevExpression = tempExpression.right ? tempExpression.right : tempExpression;
}
return expressions;
},
{ prevExpression: undefined, expressionTree: undefined },
);
return where.expressionTree;
}
conditionExpression(ctx: ConditionExpressionContext, options?: { prevExpression?: any }) {
options = options || {};
if (options.prevExpression && ctx.logicalOperator) {
options.prevExpression.operator = ctx.logicalOperator[0].tokenType.name;
}
let baseExpression: Partial<WhereClause> = {};
let currExpression: Partial<WhereClause> = baseExpression;
if (Array.isArray(ctx.expressionNegation)) {
baseExpression = this.visit(ctx.expressionNegation);
currExpression = (baseExpression as WhereClauseWithRightCondition).right;
}
currExpression.left = this.visit(ctx.expression);
return baseExpression;
}
withClause(ctx: WithClauseContext) {
if (ctx.withSecurityEnforced) {
return {
withSecurityEnforced: true,
};
} else {
return {
withDataCategory: {
conditions: this.visit(ctx.withDataCategory),
},
};
}
}
withDataCategory(ctx: WithDateCategoryContext): WithDataCategoryCondition[] {
return ctx.withDataCategoryArr.map(item => this.visit(item));
}
withDataCategoryArr(ctx: any): WithDataCategoryCondition {
return {
groupName: ctx.dataCategoryGroupName[0].image,
selector: ctx.filteringSelector[0].image,
parameters: ctx.dataCategoryName.map((item: any) => item.image),
};
}
groupByClause(ctx: GroupByClauseContext): GroupByClause | GroupByClause[] {
return ctx.groupBy.map(
(groupBy): GroupByClause => (isToken(groupBy) ? { field: groupBy.image } : { fn: this.visit(groupBy, { includeType: false }) }),
);
}
havingClause(ctx: HavingClauseContext): HavingClause {
// expressionWithAggregateFunction
const having = ctx.conditionExpression.reduce(
(expressions: ExpressionTree<HavingClause>, currExpression: any) => {
if (!expressions.expressionTree) {
expressions.expressionTree = this.visit(currExpression);
expressions.prevExpression = expressions.expressionTree;
} else {
(expressions.prevExpression as HavingClauseWithRightCondition).right = this.visit(currExpression, {
prevExpression: expressions.prevExpression,
});
expressions.prevExpression = (expressions.prevExpression as HavingClauseWithRightCondition).right;
}
return expressions;
},
{ prevExpression: undefined, expressionTree: undefined },
);
return having.expressionTree;
}
orderByClause(ctx: OrderByClauseContext): OrderByClause | OrderByClause[] {
return ctx.orderByExpressionOrFn.map(item => this.visit(item));
}
orderByExpression(ctx: OrderByExpressionContext): OrderByClause {
const orderByClause: OrderByClause = {
field: ctx.Identifier[0].image,
};
if (ctx.order && ctx.order[0]) {
orderByClause.order = ctx.order[0].tokenType.name as OrderByCriterion;
}
if (ctx.nulls && ctx.nulls[0]) {
orderByClause.nulls = ctx.nulls[0].tokenType.name as NullsOrder;
}
return orderByClause;
}
orderByGroupingFunctionExpression(ctx: OrderByGroupingFunctionExpressionContext): OrderByClause {
const orderByClause: OrderByClause = {
fn: this.helpers.$_getFieldFunction(ctx, false, false),
};
if (ctx.order && ctx.order[0]) {
orderByClause.order = ctx.order[0].tokenType.name as OrderByCriterion;
}
if (ctx.nulls && ctx.nulls[0]) {
orderByClause.nulls = ctx.nulls[0].tokenType.name as NullsOrder;
}
return orderByClause;
}
orderBySpecialFunctionExpression(ctx: OrderBySpecialFunctionExpressionContext): OrderByClause {
const orderByClause: Partial<OrderByClause> = {};
if (ctx.aggregateFunction) {
(orderByClause as OrderByFnClause).fn = this.visit(ctx.aggregateFunction, { includeType: false });
} else if (ctx.dateFunction) {
(orderByClause as OrderByFnClause).fn = this.visit(ctx.dateFunction, { includeType: false });
} else if (ctx.locationFunction) {
(orderByClause as OrderByFnClause).fn = this.visit(ctx.locationFunction, { includeType: false });
}
if (ctx.order && ctx.order[0]) {
orderByClause.order = ctx.order[0].tokenType.name as OrderByCriterion;
}
if (ctx.nulls && ctx.nulls[0]) {
orderByClause.nulls = ctx.nulls[0].tokenType.name as NullsOrder;
}
return orderByClause as OrderByClause;
}
limitClause(ctx: ValueContext) {
return ctx.value[0].image;
}
offsetClause(ctx: ValueContext) {
return ctx.value[0].image;
}
dateFunction(ctx: FieldFunctionContext, options: { includeType: boolean } = { includeType: true }) {
return this.helpers.$_getFieldFunction(ctx, false, options.includeType);
}
aggregateFunction(ctx: FieldFunctionContext, options: { includeType: boolean } = { includeType: true }) {
return this.helpers.$_getFieldFunction(ctx, true, options.includeType);
}
fieldsFunction(ctx: FieldsFunctionContext, options: { includeType: boolean } = { includeType: true }) {
let output: any = {};
if (options.includeType) {
output.type = 'FieldFunctionExpression';
}
output = {
...output,
...{
functionName: 'FIELDS',
parameters: [ctx.params[0].image],
},
};
output.rawValue = `FIELDS(${output.parameters[0]})`;
return output;
}
otherFunction(ctx: FieldFunctionContext, options: { includeType: boolean } = { includeType: true }) {
return this.helpers.$_getFieldFunction(ctx, false, options.includeType);
}
cubeFunction(ctx: FieldFunctionContext) {
return this.helpers.$_getFieldFunction(ctx, false, false);
}
rollupFunction(ctx: FieldFunctionContext) {
return this.helpers.$_getFieldFunction(ctx, false, false);
}
locationFunction(ctx: LocationFunctionContext, options: { includeType: boolean } = { includeType: true }) {
let output: any = {};
if (options.includeType) {
output.type = 'FieldFunctionExpression';
}
output = {
...output,
...{
functionName: 'DISTANCE',
parameters: [
ctx.location1[0].image,
isToken(ctx.location2) ? ctx.location2[0].image : this.visit(ctx.location2, options),
ctx.unit[0].image,
],
},
};
if (options.includeType) {
output.isAggregateFn = true;
}
output.rawValue = `DISTANCE(${output.parameters[0]}, ${
isString(output.parameters[1]) ? output.parameters[1] : output.parameters[1].rawValue
}, ${output.parameters[2]})`;
return output;
}
geolocationFunction(ctx: GeoLocationFunctionContext, options: { includeType: boolean } = { includeType: true }) {
let output: any = {};
if (options.includeType) {
output.type = 'FieldFunctionExpression';
}
output = {
...output,
...{
functionName: 'GEOLOCATION',
parameters: [ctx.latitude[0].image, ctx.longitude[0].image],
rawValue: `GEOLOCATION(${ctx.latitude[0].image}, ${ctx.longitude[0].image})`,
},
};
return output;
}
functionExpression(ctx: FunctionExpressionContext, options: { includeType: boolean } = { includeType: true }): string[] {
if (ctx.params) {
return ctx.params.map((item: any) => {
if (item.image) {
return item.image;
}
return this.visit(item, options);
});
}
return [];
}
expression(ctx: ExpressionContext): ConditionWithValueQuery {
// const { value, literalType, dateLiteralVariable } = this.visit(ctx.rhs, { returnLiteralType: true });
const { value, literalType, dateLiteralVariable, operator } = this.visit(ctx.operator, { returnLiteralType: true });
const output: Partial<ConditionWithValueQuery> = {};
if (isToken(ctx.lhs)) {
(output as ValueCondition).field = ctx.lhs[0].image;
} else {
(output as ValueFunctionCondition).fn = this.visit(ctx.lhs, { includeType: false });
}
// output.operator = this.visit(ctx.relationalOperator) || this.visit(ctx.setOperator);
(output as ValueCondition).operator = operator;
if (literalType === 'SUBQUERY') {
(output as ValueQueryCondition).valueQuery = value;
} else {
(output as ValueCondition).value = value;
(output as ValueCondition).literalType = literalType;
}
if (dateLiteralVariable) {
(output as ValueWithDateNLiteralCondition).dateLiteralVariable = dateLiteralVariable;
}
if (ctx.L_PAREN) {
output.openParen = ctx.L_PAREN.length;
}
if (ctx.R_PAREN) {
(output as ValueCondition).closeParen = ctx.R_PAREN.length;
}
return output as Condition;
}
expressionPartWithNegation(ctx: any) {
const output: Partial<WhereClauseWithRightCondition> = {
left: ctx.L_PAREN ? { openParen: ctx.L_PAREN.length } : null,
operator: 'NOT',
right: {
left: {} as ValueCondition,
},
};
return output;
}
expressionWithRelationalOperator(ctx: ExpressionOperatorContext): Condition {
return {
operator: this.visit(ctx.relationalOperator) || this.visit(ctx.setOperator),
...this.visit(ctx.rhs, { returnLiteralType: true }),
};
}
expressionWithSetOperator(ctx: ExpressionOperatorContext): Condition {
return {
operator: this.visit(ctx.relationalOperator) || this.visit(ctx.setOperator),
...this.visit(ctx.rhs, { returnLiteralType: true }),
};
}
atomicExpression(ctx: AtomicExpressionContext, options?: { returnLiteralType?: boolean }) {
options = options || {};
let value;
let literalType: LiteralTypeWithSubquery;
let dateLiteralVariable;
if (ctx.apexBindVariableExpression) {
value = this.visit(ctx.apexBindVariableExpression);
literalType = 'APEX_BIND_VARIABLE';
} else if (ctx.NumberIdentifier) {
value = ctx.NumberIdentifier[0].image;
literalType = this.helpers.$_getLiteralTypeFromTokenType(ctx.NumberIdentifier[0].tokenType.name);
} else if (ctx.UnsignedInteger) {
value = ctx.UnsignedInteger[0].image;
literalType = 'INTEGER';
} else if (ctx.SignedInteger) {
value = ctx.SignedInteger[0].image;
literalType = 'INTEGER';
} else if (ctx.RealNumber) {
value = ctx.RealNumber[0].image;
literalType = 'DECIMAL';
} else if (ctx.DateIdentifier) {
value = ctx.DateIdentifier[0].image;
literalType = this.helpers.$_getLiteralTypeFromTokenType(ctx.DateIdentifier[0].tokenType.name);
} else if (ctx.CurrencyPrefixedInteger) {
value = ctx.CurrencyPrefixedInteger[0].image;
literalType = 'INTEGER_WITH_CURRENCY_PREFIX';
} else if (ctx.CurrencyPrefixedDecimal) {
value = ctx.CurrencyPrefixedDecimal[0].image;
literalType = 'DECIMAL_WITH_CURRENCY_PREFIX';
} else if (ctx.DateTime) {
value = ctx.DateTime[0].image;
literalType = 'DATETIME';
} else if (ctx.date) {
value = ctx.DateToken[0].image;
literalType = 'DATE';
} else if (ctx.NULL) {
value = 'NULL';
literalType = 'NULL';
} else if (ctx.StringIdentifier) {
value = ctx.StringIdentifier[0].image;
literalType = 'STRING';
} else if (ctx.Identifier) {
value = ctx.Identifier[0].image;
literalType = 'STRING';
} else if (ctx.booleanValue) {
value = this.visit(ctx.booleanValue);
literalType = 'BOOLEAN';
} else if (ctx.DateLiteral) {
value = ctx.DateLiteral[0].image;
literalType = 'DATE_LITERAL';
} else if (ctx.dateNLiteral) {
const valueAndVariable = this.visit(ctx.dateNLiteral);
value = valueAndVariable.value;
dateLiteralVariable = valueAndVariable.variable;
literalType = 'DATE_N_LITERAL';
} else if (ctx.arrayExpression) {
const arrayValues: ArrayExpressionWithType[] = this.visit(ctx.arrayExpression);
value = arrayValues.map((item: any) => item.value);
const dateLiteralTemp = arrayValues.map((item: any) => item.variable || null);
const hasDateLiterals = dateLiteralTemp.some(item => item !== null);
if (new Set(arrayValues.map((item: any) => item.type)).size === 1) {
literalType = this.helpers.$_getLiteralTypeFromTokenType(arrayValues[0].type);
} else {
literalType = arrayValues.map((item: any) => this.helpers.$_getLiteralTypeFromTokenType(item.type));
}
if (hasDateLiterals) {
dateLiteralVariable = dateLiteralTemp;
}
literalType = literalType || 'STRING';
} else if (ctx.whereClauseSubqueryIdentifier) {
value = this.visit(ctx.whereClauseSubqueryIdentifier);
literalType = 'SUBQUERY';
}
if (options.returnLiteralType) {
return {
value,
literalType,
dateLiteralVariable,
};
} else {
return value;
}
}
apexBindVariableExpression(ctx: ApexBindVariableExpressionContext): string {
return ctx.apex.map(item => this.visit(item)).join('.');
}
apexBindVariableIdentifier(ctx: ApexBindVariableIdentifierContext): string {
let output = ctx.Identifier[0].image;
if (ctx.apexBindVariableFunctionArrayAccessor) {
output += this.visit(ctx.apexBindVariableFunctionArrayAccessor[0]);
}
return output;
}
apexBindVariableNewInstantiation(ctx: ApexBindVariableNewInstantiationContext): string {
let output = `new ${ctx.function[0].image}`;
if (ctx.apexBindVariableGeneric) {
output += this.visit(ctx.apexBindVariableGeneric[0]);
}
output += this.visit(ctx.apexBindVariableFunctionParams[0]);
if (ctx.apexBindVariableFunctionArrayAccessor) {
output += this.visit(ctx.apexBindVariableFunctionArrayAccessor[0]);
}
return output;
}
apexBindVariableFunctionCall(ctx: ApexBindVariableFunctionCallContext): string {
let output = `${ctx.function[0].image}${this.visit(ctx.apexBindVariableFunctionParams[0])}`;
if (ctx.apexBindVariableFunctionArrayAccessor) {
output += this.visit(ctx.apexBindVariableFunctionArrayAccessor[0]);
}
return output;
}
apexBindVariableGeneric(ctx: ApexBindVariableGenericContext): string {
return `<${ctx.parameter.map(item => item.image).join(', ')}>`;
}
apexBindVariableFunctionParams(ctx: ApexBindVariableFunctionParamsContext): string {
const params = Array.isArray(ctx.parameter) ? ctx.parameter : [];
return `(${params.map(item => item.image).join(', ')})`;
}
apexBindVariableFunctionArrayAccessor(ctx: ApexBindVariableFunctionArrayAccessorContext): string {
return `[${ctx.value[0].image}]`;
}
arrayExpression(ctx: ValueContext): ArrayExpressionWithType[] {
return ctx.value.map((item: any) => {
if (isToken(item)) {
return {
type: (item as IToken).tokenType.name,
value: (item as IToken).image,
};
} else {
return this.visit(item, { includeType: true });
}
});
}
relationalOperator(ctx: OperatorContext) {
return ctx.operator[0].image;
}
setOperator(ctx: OperatorContext) {
return ctx.operator[0].tokenType.name.replace('_', ' ');
}
booleanValue(ctx: BooleanContext) {
return ctx.boolean[0].tokenType.name;
}
dateNLiteral(ctx: DateNLiteralContext, options?: { includeType: true }) {
const output: any = {
value: `${ctx.dateNLiteral[0].image}:${ctx.variable[0].image}`,
variable: Number(ctx.variable[0].image),
};
if (options && options.includeType) {
output.type = ctx.dateNLiteral[0].tokenType.name;
}
return output;
}
forViewOrReference(ctx: ValueContext) {
return ctx.value[0].tokenType.name;
}
updateTrackingViewstat(ctx: ValueContext) {
return ctx.value[0].tokenType.name;
}
}
// Our visitor has no state, so a single instance is sufficient.
const visitor = new SOQLVisitor();
/**
* Parse query and process results
* @param soql
*/
export function parseQuery(soql: string, options?: ParseQueryConfig): Query {
const { cst } = parse(soql, options);
const query: Query = visitor.visit(cst);
return query;
}
/**
* Lex and parse query (without walking parsed results) to determine if query is valid.
* options.ignoreParseErrors will not be honored
* @param soql
*/
export function isQueryValid(soql: string, options?: ParseQueryConfig): boolean {
try {
const { parseErrors } = parse(soql, options);
return parseErrors.length === 0 ? true : false;
} catch (ex) {
return false;
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export const ResourceProviderOperationList: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ResourceProviderOperationList",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ResourceProviderOperation"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const ResourceProviderOperation: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ResourceProviderOperation",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
isDataAction: {
serializedName: "isDataAction",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "ResourceProviderOperationDisplay"
}
}
}
}
};
export const ResourceProviderOperationDisplay: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ResourceProviderOperationDisplay",
modelProperties: {
provider: {
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
serializedName: "resource",
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
type: {
name: "String"
}
},
description: {
serializedName: "description",
type: {
name: "String"
}
}
}
}
};
export const ErrorResponse: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorDefinition"
}
}
}
}
};
export const ErrorDefinition: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorDefinition",
modelProperties: {
code: {
serializedName: "code",
readOnly: true,
type: {
name: "Number"
}
},
message: {
serializedName: "message",
readOnly: true,
type: {
name: "String"
}
},
details: {
serializedName: "details",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorDefinition"
}
}
}
}
}
}
};
export const Dashboard: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Dashboard",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
},
location: {
serializedName: "location",
required: true,
type: {
name: "String"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
},
lenses: {
serializedName: "properties.lenses",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DashboardLens"
}
}
}
},
metadata: {
serializedName: "properties.metadata",
type: {
name: "Dictionary",
value: {
type: { name: "Dictionary", value: { type: { name: "any" } } }
}
}
}
}
}
};
export const DashboardLens: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DashboardLens",
modelProperties: {
order: {
serializedName: "order",
required: true,
type: {
name: "Number"
}
},
parts: {
serializedName: "parts",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DashboardParts"
}
}
}
},
metadata: {
serializedName: "metadata",
type: {
name: "Dictionary",
value: {
type: { name: "Dictionary", value: { type: { name: "any" } } }
}
}
}
}
}
};
export const DashboardParts: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DashboardParts",
modelProperties: {
position: {
serializedName: "position",
type: {
name: "Composite",
className: "DashboardPartsPosition"
}
},
metadata: {
serializedName: "metadata",
type: {
name: "Composite",
className: "DashboardPartMetadata"
}
}
}
}
};
export const DashboardPartsPosition: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DashboardPartsPosition",
modelProperties: {
x: {
serializedName: "x",
required: true,
type: {
name: "Number"
}
},
y: {
serializedName: "y",
required: true,
type: {
name: "Number"
}
},
rowSpan: {
serializedName: "rowSpan",
required: true,
type: {
name: "Number"
}
},
colSpan: {
serializedName: "colSpan",
required: true,
type: {
name: "Number"
}
},
metadata: {
serializedName: "metadata",
type: {
name: "Dictionary",
value: {
type: { name: "Dictionary", value: { type: { name: "any" } } }
}
}
}
}
}
};
export const DashboardPartMetadata: coreClient.CompositeMapper = {
serializedName: "DashboardPartMetadata",
type: {
name: "Composite",
className: "DashboardPartMetadata",
uberParent: "DashboardPartMetadata",
additionalProperties: { type: { name: "Object" } },
polymorphicDiscriminator: {
serializedName: "type",
clientName: "type"
},
modelProperties: {
type: {
serializedName: "type",
required: true,
type: {
name: "String"
}
}
}
}
};
export const PatchableDashboard: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "PatchableDashboard",
modelProperties: {
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
},
lenses: {
serializedName: "properties.lenses",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DashboardLens"
}
}
}
},
metadata: {
serializedName: "properties.metadata",
type: {
name: "Dictionary",
value: {
type: { name: "Dictionary", value: { type: { name: "any" } } }
}
}
}
}
}
};
export const DashboardListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "DashboardListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Dashboard"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const ConfigurationList: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ConfigurationList",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Configuration"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const Resource: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const ViolationsList: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ViolationsList",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Violation"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const Violation: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Violation",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
userId: {
serializedName: "userId",
readOnly: true,
type: {
name: "String"
}
},
errorMessage: {
serializedName: "errorMessage",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const MarkdownPartMetadataSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MarkdownPartMetadataSettings",
modelProperties: {
content: {
serializedName: "content",
type: {
name: "Composite",
className: "MarkdownPartMetadataSettingsContent"
}
}
}
}
};
export const MarkdownPartMetadataSettingsContent: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MarkdownPartMetadataSettingsContent",
modelProperties: {
settings: {
serializedName: "settings",
type: {
name: "Composite",
className: "MarkdownPartMetadataSettingsContentSettings"
}
}
}
}
};
export const MarkdownPartMetadataSettingsContentSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MarkdownPartMetadataSettingsContentSettings",
modelProperties: {
content: {
serializedName: "content",
type: {
name: "String"
}
},
title: {
serializedName: "title",
type: {
name: "String"
}
},
subtitle: {
serializedName: "subtitle",
type: {
name: "String"
}
},
markdownSource: {
serializedName: "markdownSource",
type: {
name: "Number"
}
},
markdownUri: {
serializedName: "markdownUri",
type: {
name: "String"
}
}
}
}
};
export const MarkdownPartMetadata: coreClient.CompositeMapper = {
serializedName: "Extension/HubsExtension/PartType/MarkdownPart",
type: {
name: "Composite",
className: "MarkdownPartMetadata",
uberParent: "DashboardPartMetadata",
additionalProperties: { type: { name: "Object" } },
polymorphicDiscriminator:
DashboardPartMetadata.type.polymorphicDiscriminator,
modelProperties: {
...DashboardPartMetadata.type.modelProperties,
inputs: {
serializedName: "inputs",
type: {
name: "Sequence",
element: {
type: {
name: "Dictionary",
value: { type: { name: "any" } }
}
}
}
},
settings: {
serializedName: "settings",
type: {
name: "Composite",
className: "MarkdownPartMetadataSettings"
}
}
}
}
};
export const ProxyResource: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ProxyResource",
modelProperties: {
...Resource.type.modelProperties
}
}
};
export const Configuration: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Configuration",
modelProperties: {
...ProxyResource.type.modelProperties,
enforcePrivateMarkdownStorage: {
serializedName: "properties.enforcePrivateMarkdownStorage",
type: {
name: "Boolean"
}
}
}
}
};
export let discriminators = {
DashboardPartMetadata: DashboardPartMetadata,
"DashboardPartMetadata.Extension/HubsExtension/PartType/MarkdownPart": MarkdownPartMetadata
}; | the_stack |
import warning from 'warning';
import { LineClient } from 'messaging-api-line';
import { mocked } from 'ts-jest/utils';
import LineConnector, { GetSessionKeyPrefixFunction } from '../LineConnector';
import LineContext from '../LineContext';
import LineEvent from '../LineEvent';
import { LineRequestBody } from '../LineTypes';
jest.mock('messaging-api-line');
jest.mock('warning');
const ACCESS_TOKEN = 'FAKE_TOKEN';
const CHANNEL_SECRET = 'FAKE_SECRET';
const requestBody: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
},
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'follow',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
},
],
};
const webhookVerifyRequestBody: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: '00000000000000000000000000000000',
type: 'message',
mode: 'active',
timestamp: 1513065174862,
source: {
type: 'user',
userId: 'Udeadbeefdeadbeefdeadbeefdeadbeef',
},
message: {
id: '100001',
type: 'text',
text: 'Hello, world',
},
},
{
replyToken: 'ffffffffffffffffffffffffffffffff',
type: 'message',
mode: 'active',
timestamp: 1513065174862,
source: {
type: 'user',
userId: 'Udeadbeefdeadbeefdeadbeefdeadbeef',
},
message: {
id: '100002',
type: 'sticker',
packageId: '1',
stickerId: '1',
},
},
],
};
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
mocked(LineClient).mockClear();
});
function setup({
sendMethod,
skipLegacyProfile,
getSessionKeyPrefix,
}: {
sendMethod?: string;
skipLegacyProfile?: boolean;
getSessionKeyPrefix?: GetSessionKeyPrefixFunction;
} = {}) {
const connector = new LineConnector({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
sendMethod,
skipLegacyProfile,
getSessionKeyPrefix,
});
const client = mocked(LineClient).mock.instances[0];
return {
client,
connector,
};
}
describe('#platform', () => {
it('should be line', () => {
const { connector } = setup();
expect(connector.platform).toBe('line');
});
});
describe('#client', () => {
it('should be the client', () => {
const { connector, client } = setup();
expect(connector.client).toBe(client);
});
it('support using custom client', () => {
const client = new LineClient({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
});
const connector = new LineConnector({
client,
channelSecret: CHANNEL_SECRET,
});
expect(connector.client).toBe(client);
});
});
describe('#getUniqueSessionKey', () => {
it('extract userId from the HTTP body', () => {
const { connector } = setup();
const senderId = connector.getUniqueSessionKey(requestBody);
expect(senderId).toBe('U206d25c2ea6bd87c17655609a1c37cb8');
});
it('extract userId from user source', () => {
const { connector } = setup();
const senderId = connector.getUniqueSessionKey(
new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
})
);
expect(senderId).toBe('U206d25c2ea6bd87c17655609a1c37cb8');
});
it('extract groupId from the group source', () => {
const { connector } = setup();
const senderId = connector.getUniqueSessionKey(
new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'group',
groupId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
})
);
expect(senderId).toBe('U206d25c2ea6bd87c17655609a1c37cb8');
});
it('extract roomId from the room source', () => {
const { connector } = setup();
const senderId = connector.getUniqueSessionKey(
new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'room',
roomId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
})
);
expect(senderId).toBe('U206d25c2ea6bd87c17655609a1c37cb8');
});
it('should add the prefix to the session key when getSessionKeyPrefix exists', () => {
const getSessionKeyPrefix: GetSessionKeyPrefixFunction = jest.fn(
(_, requestContext) => {
if (requestContext) {
return `${requestContext.params.channelId}:`;
}
throw new Error('no request context');
}
);
const { connector } = setup({
getSessionKeyPrefix,
});
const requestContext = {
method: 'post',
path: '/webhooks/line/CHANNEL_ID',
query: {},
headers: {},
rawBody: '{}',
body: {},
params: {
channelId: 'CHANNEL_ID',
},
url: 'https://www.example.com/webhooks/line/CHANNEL_ID',
};
const senderId = connector.getUniqueSessionKey(
new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
}),
requestContext
);
expect(senderId).toBe('CHANNEL_ID:U206d25c2ea6bd87c17655609a1c37cb8');
expect(getSessionKeyPrefix).toBeCalledWith(
expect.any(LineEvent),
requestContext
);
});
});
describe('#updateSession', () => {
it('update session with data needed', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const user = {
id: 'U206d25c2ea6bd87c17655609a1c37cb8',
displayName: 'LINE taro',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
pictureUrl: 'http://obs.line-apps.com/...',
statusMessage: 'Hello, LINE!',
_updatedAt: expect.any(String),
};
mocked(client).getUserProfile.mockResolvedValue(user);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, requestBody);
expect(client.getUserProfile).toBeCalledWith(
'U206d25c2ea6bd87c17655609a1c37cb8'
);
expect(session).toEqual({
type: 'user',
user,
});
expect(Object.isFrozen(session.user)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'user')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.user,
});
});
it('update session if session.user exists', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const user = {
id: 'U206d25c2ea6bd87c17655609a1c37cb8',
displayName: 'LINE taro',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
pictureUrl: 'http://obs.line-apps.com/...',
statusMessage: 'Hello, LINE!',
_updatedAt: expect.any(String),
};
const session = { type: 'user', user };
await connector.updateSession(session, requestBody);
expect(client.getUserProfile).not.toBeCalled();
expect(session).toEqual({
type: 'user',
user,
});
expect(Object.isFrozen(session.user)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'user')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.user,
});
});
it('update session with group type message', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const body: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'group',
groupId: 'Ca56f94637cc4347f90a25382909b24b9',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
},
],
};
const user = {
id: body.events[0].source.userId,
displayName: 'LINE taro',
userId: body.events[0].source.userId,
pictureUrl: 'http://obs.line-apps.com/...',
statusMessage: 'Hello, LINE!',
_updatedAt: expect.any(String),
};
const memberIds = [
'Uxxxxxxxxxxxxxx...1',
'Uxxxxxxxxxxxxxx...2',
'Uxxxxxxxxxxxxxx...3',
];
mocked(client).getGroupMemberProfile.mockResolvedValue(user);
mocked(client).getAllGroupMemberIds.mockResolvedValue(memberIds);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, body);
expect(client.getGroupMemberProfile).toBeCalledWith(
'Ca56f94637cc4347f90a25382909b24b9',
'U206d25c2ea6bd87c17655609a1c37cb8'
);
expect(client.getAllGroupMemberIds).toBeCalledWith(
'Ca56f94637cc4347f90a25382909b24b9'
);
expect(session).toEqual({
type: 'group',
group: {
id: 'Ca56f94637cc4347f90a25382909b24b9',
members: [
{ id: 'Uxxxxxxxxxxxxxx...1' },
{ id: 'Uxxxxxxxxxxxxxx...2' },
{ id: 'Uxxxxxxxxxxxxxx...3' },
],
_updatedAt: expect.any(String),
},
user,
});
expect(Object.isFrozen(session.group)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'group')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.group,
});
});
it('update session with group type event without userId', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const body: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'join',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'group',
groupId: 'Ca56f94637cc4347f90a25382909b24b9',
},
},
],
};
const user = null;
const memberIds = [
'Uxxxxxxxxxxxxxx...1',
'Uxxxxxxxxxxxxxx...2',
'Uxxxxxxxxxxxxxx...3',
];
mocked(client).getAllGroupMemberIds.mockResolvedValue(memberIds);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, body);
expect(client.getGroupMemberProfile).not.toBeCalled();
expect(client.getAllGroupMemberIds).toBeCalledWith(
'Ca56f94637cc4347f90a25382909b24b9'
);
expect(session).toEqual({
type: 'group',
group: {
id: 'Ca56f94637cc4347f90a25382909b24b9',
members: [
{ id: 'Uxxxxxxxxxxxxxx...1' },
{ id: 'Uxxxxxxxxxxxxxx...2' },
{ id: 'Uxxxxxxxxxxxxxx...3' },
],
_updatedAt: expect.any(String),
},
user,
});
expect(Object.isFrozen(session.group)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'group')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.group,
});
});
it('update session with room type message', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const body: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'room',
roomId: 'Ra8dbf4673c4c812cd491258042226c99',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
},
],
};
const user = {
id: body.events[0].source.userId,
displayName: 'LINE taro',
userId: body.events[0].source.userId,
pictureUrl: 'http://obs.line-apps.com/...',
statusMessage: 'Hello, LINE!',
_updatedAt: expect.any(String),
};
const memberIds = [
'Uxxxxxxxxxxxxxx...1',
'Uxxxxxxxxxxxxxx...2',
'Uxxxxxxxxxxxxxx...3',
];
mocked(client).getRoomMemberProfile.mockResolvedValue(user);
mocked(client).getAllRoomMemberIds.mockResolvedValue(memberIds);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, body);
expect(client.getRoomMemberProfile).toBeCalledWith(
'Ra8dbf4673c4c812cd491258042226c99',
'U206d25c2ea6bd87c17655609a1c37cb8'
);
expect(client.getAllRoomMemberIds).toBeCalledWith(
'Ra8dbf4673c4c812cd491258042226c99'
);
expect(session).toEqual({
type: 'room',
room: {
id: 'Ra8dbf4673c4c812cd491258042226c99',
members: [
{ id: 'Uxxxxxxxxxxxxxx...1' },
{ id: 'Uxxxxxxxxxxxxxx...2' },
{ id: 'Uxxxxxxxxxxxxxx...3' },
],
_updatedAt: expect.any(String),
},
user,
});
expect(Object.isFrozen(session.room)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'room')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.room,
});
});
it('update session with room type event without userId', async () => {
const { connector, client } = setup({
skipLegacyProfile: false,
});
const body: LineRequestBody = {
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [
{
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'join',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'room',
roomId: 'Ra8dbf4673c4c812cd491258042226c99',
},
},
],
};
const user = null;
const memberIds = [
'Uxxxxxxxxxxxxxx...1',
'Uxxxxxxxxxxxxxx...2',
'Uxxxxxxxxxxxxxx...3',
];
mocked(client).getAllRoomMemberIds.mockResolvedValue(memberIds);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, body);
expect(client.getRoomMemberProfile).not.toBeCalled();
expect(client.getAllRoomMemberIds).toBeCalledWith(
'Ra8dbf4673c4c812cd491258042226c99'
);
expect(session).toEqual({
type: 'room',
room: {
id: 'Ra8dbf4673c4c812cd491258042226c99',
members: [
{ id: 'Uxxxxxxxxxxxxxx...1' },
{ id: 'Uxxxxxxxxxxxxxx...2' },
{ id: 'Uxxxxxxxxxxxxxx...3' },
],
_updatedAt: expect.any(String),
},
user,
});
expect(Object.isFrozen(session.room)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'room')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.room,
});
});
it('update userId without calling any api while skipLegacyProfile set to true', async () => {
const { connector, client } = setup();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const session: any = {};
await connector.updateSession(session, requestBody);
expect(client.getUserProfile).not.toBeCalled();
expect(session).toEqual({
type: 'user',
user: {
id: 'U206d25c2ea6bd87c17655609a1c37cb8',
_updatedAt: expect.any(String),
},
});
expect(Object.isFrozen(session.user)).toBe(true);
expect(Object.getOwnPropertyDescriptor(session, 'user')).toEqual({
configurable: false,
enumerable: true,
writable: false,
value: session.user,
});
});
});
describe('#mapRequestToEvents', () => {
it('should map the HTTP body to the LineEvents', () => {
const { connector } = setup();
const events = connector.mapRequestToEvents(requestBody);
expect(events).toHaveLength(2);
expect(events[0]).toBeInstanceOf(LineEvent);
expect(events[1]).toBeInstanceOf(LineEvent);
expect(events[0].destination).toBe('Uea8667adaf43586706170ff25ff47ae6');
expect(events[1].destination).toBe('Uea8667adaf43586706170ff25ff47ae6');
});
});
describe('#createContext', () => {
it('should create a LineContext', async () => {
const { connector } = setup();
const event = new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
});
const session = {};
const context = await connector.createContext({
event,
session,
});
expect(context).toBeDefined();
expect(context).toBeInstanceOf(LineContext);
});
it('should create a LineContext using the config from getConfig', async () => {
const getConfig = jest.fn();
getConfig.mockResolvedValue({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
});
const connector = new LineConnector({
getConfig,
});
const event = new LineEvent({
replyToken: 'nHuyWiB7yP5Zw52FIkcQobQuGDXCTA',
type: 'message',
mode: 'active',
timestamp: 1462629479859,
source: {
type: 'user',
userId: 'U206d25c2ea6bd87c17655609a1c37cb8',
},
message: {
id: '325708',
type: 'text',
text: 'Hello, world',
},
});
const session = {};
await connector.createContext({
event,
session,
requestContext: {
path: '/webhooks/line/11111111111',
params: {
channelId: '11111111111',
},
url: `https://www.example.com/webhooks/line/11111111111`,
method: 'post',
headers: {
'x-line-signature': '5+SUnXZ8+G1ErXUewxeZ0T9j4yD6cmwYn5XCO4tBFic',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
},
});
expect(getConfig).toBeCalledWith({ params: { channelId: '11111111111' } });
expect(LineClient).toBeCalledWith({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
origin: undefined,
});
});
});
describe('#verifySignature', () => {
it('should return true if signature is equal app secret after crypto', () => {
const { connector } = setup();
const result = connector.verifySignature(
'rawBody',
'XtFE4w+/e5cw8ys6BSALGj3ZCYgRtBdCBxyEfrkgLPc=',
{ channelSecret: CHANNEL_SECRET }
);
expect(result).toBe(true);
});
});
it('should warning if sendMethod is not one of `reply`, `push`', () => {
setup({ sendMethod: 'xxx' });
expect(warning).toBeCalledWith(false, expect.any(String));
});
describe('#isWebhookVerifyRequest', () => {
it('check if the HTTP body is for webhook verification', async () => {
const { connector } = setup();
expect(connector.isWebhookVerifyRequest(webhookVerifyRequestBody)).toEqual(
true
);
expect(
connector.isWebhookVerifyRequest({
destination: 'Uea8667adaf43586706170ff25ff47ae6',
events: [],
})
).toEqual(false);
});
});
describe('#preprocess', () => {
it('should return shouldNext: true if the method is get', async () => {
const { connector } = setup();
expect(
await connector.preprocess({
path: '/webhooks/line',
params: {},
url: `https://www.example.com/webhooks/line`,
method: 'get',
headers: {
'x-line-signature': 'abc',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
})
).toEqual({
shouldNext: true,
});
});
it('should return shouldNext: true if the signature match', async () => {
const { connector } = setup();
expect(
await connector.preprocess({
path: '/webhooks/line',
params: {},
url: `https://www.example.com/webhooks/line`,
method: 'post',
headers: {
'x-line-signature': '5+SUnXZ8+G1ErXUewxeZ0T9j4yD6cmwYn5XCO4tBFic',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
})
).toEqual({
shouldNext: true,
});
});
it('should return shouldNext: true if the signature match (using getConfig)', async () => {
const getConfig = jest.fn();
getConfig.mockResolvedValue({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
});
const connector = new LineConnector({
getConfig,
});
expect(
await connector.preprocess({
path: '/webhooks/line/11111111111',
params: {
channelId: '11111111111',
},
url: `https://www.example.com/webhooks/line/11111111111`,
method: 'post',
headers: {
'x-line-signature': '5+SUnXZ8+G1ErXUewxeZ0T9j4yD6cmwYn5XCO4tBFic',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
})
).toEqual({
shouldNext: true,
});
expect(getConfig).toBeCalledWith({ params: { channelId: '11111111111' } });
});
it('should return shouldNext: false and 200 OK if the HTTP body is for webhook verification', async () => {
const { connector } = setup();
expect(
await connector.preprocess({
path: '/webhooks/line',
params: {},
url: `https://www.example.com/webhooks/line`,
method: 'post',
headers: {
'x-line-signature': 'VYLhgSyybnkWRb9qqCreJSTQTkbS6KtXVuw55BcAS7o',
},
query: {},
rawBody: JSON.stringify(webhookVerifyRequestBody),
body: webhookVerifyRequestBody,
})
).toEqual({
shouldNext: false,
response: {
status: 200,
body: 'OK',
},
});
});
it('should return shouldNext: false and the error if the signature does not match', async () => {
const { connector } = setup();
expect(
await connector.preprocess({
path: '/webhooks/line',
params: {},
url: `https://www.example.com/webhooks/line`,
method: 'post',
headers: {
'x-line-signature': 'XtFE4w+/e5cw8ys6BSALGj3ZCYgRtBdCBxyEfrkgLPc=',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
})
).toEqual({
shouldNext: false,
response: {
status: 400,
body: {
error: {
message: 'LINE Signature Validation Failed!',
request: {
headers: {
'x-line-signature':
'XtFE4w+/e5cw8ys6BSALGj3ZCYgRtBdCBxyEfrkgLPc=',
},
rawBody: JSON.stringify(requestBody),
},
},
},
},
});
});
it('should return shouldNext: false and the error if the signature does not match (using getConfig)', async () => {
const getConfig = jest.fn();
getConfig.mockResolvedValue({
accessToken: ACCESS_TOKEN,
channelSecret: CHANNEL_SECRET,
});
const connector = new LineConnector({
getConfig,
});
expect(
await connector.preprocess({
path: '/webhooks/line/11111111111',
params: {
channelId: '11111111111',
},
url: `https://www.example.com/webhooks/line/11111111111`,
method: 'post',
headers: {
'x-line-signature': 'XtFE4w+/e5cw8ys6BSALGj3ZCYgRtBdCBxyEfrkgLPc=',
},
query: {},
rawBody: JSON.stringify(requestBody),
body: requestBody,
})
).toEqual({
shouldNext: false,
response: {
status: 400,
body: {
error: {
message: 'LINE Signature Validation Failed!',
request: {
headers: {
'x-line-signature':
'XtFE4w+/e5cw8ys6BSALGj3ZCYgRtBdCBxyEfrkgLPc=',
},
rawBody: JSON.stringify(requestBody),
},
},
},
},
});
expect(getConfig).toBeCalledWith({ params: { channelId: '11111111111' } });
});
}); | the_stack |
import { default as base } from './default.basic';
import { innerScaleFont, innerScaleSize } from './responsive';
/*
* components
*/
const MDComponentsThemes: { [key: string]: any } = {
// button
button: {
primaryFill: base.colors.primary,
defaultFill: base.colors.bgInverse,
disabledFill: base.colors.bgDisabled,
warningFill: base.colors.textError,
primaryActiveFill: '#2A78DC',
defaultActiveFill: base.colors.bg,
warningActiveFill: '#E9424F',
primaryPlainActiveFill: '#E1E9F6',
defaultPlainActiveFill: 'rgba(0, 0, 0, .08)',
warningPlainActiveFill: '#FAC3C6',
defaultColor: base.colors.textBody,
primaryColor: base.colors.textBaseInverse,
disabledColor: base.colors.textBaseInverse,
warningColor: base.colors.textBaseInverse,
width: innerScaleSize(750),
height: innerScaleSize(100),
fontSize: base.fontSize.captionLarge,
fontWeight: base.fontWeight.medium,
smallWidth: innerScaleSize(264),
smallHeight: innerScaleSize(64),
smallFontSize: base.fontSize.bodyLarge,
radius: base.radius.normal,
},
// actionBar
actionBar: {
width: '100%',
height: innerScaleSize(100),
paddingVertical: base.gapSize.vMid,
paddingHorizontal: base.gapSize.hSuperLarge,
buttonGap: innerScaleSize(22),
slotHeight: innerScaleSize(100),
zIndex: 100,
},
// actionSheet
actionSheet: {
height: innerScaleSize(120),
paddingHorizontal: base.gapSize.hSuperLarge,
color: base.colors.textBody,
colorHighlight: base.colors.primary,
colorCancel: base.colors.textMinor,
fontSize: base.fontSize.captionNormal,
bg: base.colors.bgInverse,
disabledOpacity: base.opacity.disabled,
cancelGapBg: base.colors.bgBase,
zIndex: 1101,
},
// progress
progress: {
upperColor: '#4392F6',
underColor: '#CCC',
height: 5,
},
// agree
agree: {
fill: base.colors.primary,
fillInverse: base.colors.bgDisabled,
disabledOpacity: base.opacity.disabled,
},
// bill
bill: {
bg: base.colors.bgBase,
paddingTop: innerScaleSize(28),
paddingLeft: innerScaleSize(32),
paddingBottom: innerScaleSize(8),
nameFontSize: base.fontSize.captionLarge,
nameColor: base.colors.textBody,
noFontSize: base.fontSize.minorLarge,
noColor: base.colors.textPlaceholder,
height: innerScaleSize(18),
neckPadding: innerScaleSize(10),
conBottom: innerScaleSize(20),
detailBottom: innerScaleSize(40),
descriptionFontSize: base.fontSize.minorLarge,
descriptionColor: base.colors.textCaption,
},
// captcha
captcha: {
zIndex: 1301,
titleColor: base.colors.textBase,
titleFontSize: base.fontSize.headingNormal,
color: base.colors.textCaption,
fontSize: base.fontSize.bodyLarge,
footerFontSize: base.fontSize.minorLarge,
errorColor: base.colors.textError,
briefColor: base.colors.textCaption,
countbtnGap: base.gapSize.hLarge,
btnColor: base.colors.primary,
},
// cashier
cashier: {
bg: base.colors.bgInverse,
chooseTitleFontSize: base.fontSize.bodyLarge, // - 支付标题
chooseTitleColor: base.colors.textMinor,
chooseAmountFontSize: innerScaleFont(80), // - 支付金额
chooseAmountFontFamily: base.fontFamily.number,
chooseAmountLineHeight: innerScaleSize(120),
chooseAmountColor: base.colors.textBase,
chooseDescribeFontSize: base.fontSize.minorNormal, // - 支付描述
chooseDescribeColor: base.colors.textMinor,
chooseChannelTitleFontSize: innerScaleFont(30), // - 支付渠道标题
chooseChannelTitleColor: base.colors.textBody,
chooseChannelTitleActionFontSize: base.fontSize.bodyLarge, // - 支付渠道动作标题
chooseChannelTitleActionColor: base.colors.primary,
chooseChannelDescFontSize: base.fontSize.minorLarge, // - 支付渠道备注
chooseChannelDescColor: base.colors.textCaption,
chooseChannelIconColor: base.colors.primary,
chooseMoreFontSize: base.fontSize.minorLarge, // - 更多支付方式
chooseMoreColor: base.colors.textMinor,
resultContentHeight: innerScaleSize(550),
resultTextFontSize: innerScaleFont(24),
resultTextColor: base.colors.textMinor,
loadingContentHeight: innerScaleSize(420),
},
// chart
chart: {
width: innerScaleSize(480),
height: innerScaleSize(320),
lineColor: '#ccc',
pathColor: base.colors.primary,
textColor: base.colors.textMinor,
labelFontSize: innerScaleFont(22),
valueFontSize: innerScaleFont(20),
},
// codebox
codebox: {
fontSize: innerScaleFont(50),
width: innerScaleSize(66),
height: innerScaleSize(70),
gutter: innerScaleSize(18),
borderWidth: base.borderWidth.base,
borderColor: base.colors.borderElement,
borderActiveColor: base.colors.textBase,
color: base.colors.textBase,
blinkColor: base.colors.textBase,
dotColor: base.colors.textBase,
holderSpace: base.gapSize.hSmall,
disabledColor: base.colors.textDisabled,
},
// picker
datePicker: {
fontSize: base.fontSize.captionNormal,
timeFontSize: base.fontSize.bodyLarge,
},
// dialog
dialog: {
width: innerScaleSize(606),
radius: innerScaleSize(8),
titleFontSize: innerScaleFont(40),
titleColor: base.colors.textBase,
textFontSize: base.fontSize.bodyLarge,
textColor: base.colors.textMinor,
height: innerScaleSize(100),
fontSize: base.fontSize.captionLarge,
borderColor: base.colors.borderBase,
closeColor: base.colors.textCaption,
highlightColor: base.colors.primary,
iconSize: innerScaleFont(100),
iconFill: base.colors.textCaption,
closeWidth: innerScaleSize(30),
actionFontSize: base.fontSize.captionLarge,
actionColor: base.colors.textMinor,
actionHightColor: base.colors.textHighlight,
zIndex: 1500,
},
// overlay
overlay: {
bg: base.colors.bgInverse,
zIndex: 1501,
},
// dropMenu
dropMenu: {
height: innerScaleSize(110),
zIndex: 1200,
bg: base.colors.bgInverse,
borderColor: base.colors.borderBase,
listBg: base.colors.bgInverse,
highLightColor: base.colors.textHighlight,
normalColor: base.colors.textMinor,
fontSize: base.fontSize.captionNormal,
fontWeight: base.fontWeight.medium,
disabledOpacity: base.opacity.disabled,
},
// field
field: {
paddingHorizontal: base.gapSize.hSuperLarge,
paddingVertical: base.gapSize.vSuperLarge,
bgColor: base.colors.bgInverse,
headerGap: base.gapSize.vLarge,
footerGap: base.gapSize.vMid,
titleColor: base.colors.textBase,
titleFontSize: base.fontSize.captionLarge,
titleFontWeight: base.fontWeight.normal,
briefColor: base.colors.textCaption,
briefFontSize: base.fontSize.bodyLarge,
color: base.colors.textMinor,
fontSize: base.fontSize.bodyLarge,
},
// item
fieldItem: {
minHeight: innerScaleSize(108),
paddingVertical: innerScaleSize(30),
titleWidth: innerScaleSize(160),
titleGap: innerScaleSize(10),
color: base.colors.textBase,
fontSize: base.fontSize.captionNormal,
fontWeight: base.fontWeight.medium,
placeholderColor: base.colors.textPlaceholder,
addonColor: base.colors.textCaption,
addonFontSize: base.fontSize.bodyLarge,
borderColor: base.colors.borderBase,
childrenFontSize: base.fontSize.minorLarge,
},
// cellItem
cellItem: {
minHeight: innerScaleSize(100),
paddingVertical: innerScaleSize(32),
multilinesPaddingVertical: innerScaleSize(36),
titleColor: base.colors.textBase,
titleFontSize: base.fontSize.captionNormal,
briefColor: base.colors.textCaption,
briefFontSize: base.fontSize.minorLarge,
rightColor: base.colors.textCaption,
rightFontSize: base.fontSize.bodyLarge,
borderColor: base.colors.borderBase,
},
// detailItem
detailItem: {
fontSize: base.fontSize.bodyLarge,
titleColor: base.colors.textCaption,
contentColor: base.colors.textBody,
gap: base.gapSize.vSmall,
},
// icon
icon: {
smaller: innerScaleFont(20),
small: innerScaleFont(24),
medium: innerScaleFont(32),
large: innerScaleFont(42),
},
// imageViewer
imageViewer: {
zIndex: 1001,
indexFontSize: innerScaleFont(32),
indexBottom: innerScaleSize(100),
},
// inputItem
inputItem: {
height: innerScaleSize(100),
fontSize: base.fontSize.captionNormal,
fontWeight: base.fontWeight.medium,
titleLatentFontSize: base.fontSize.bodyNormal,
fontSizeLarge: base.fontSize.headingLarge,
fontSizeError: base.fontSize.minorLarge,
fontSizeBrief: base.fontSize.minorLarge,
color: base.colors.textBase,
titleLatentColor: base.colors.textMinor,
colorDisabled: base.opacity.disabled,
colorError: base.colors.textError,
colorBrief: base.colors.textMinor,
placeholder: base.colors.textPlaceholder,
placeholderHighlight: base.colors.primary,
icon: base.colors.textPlaceholder, // - delete icon,
},
// slider
slider: {
height: innerScaleSize(120),
progressBarHeight: innerScaleSize(5),
bg: base.colors.bg,
bgHandler: base.colors.primary,
bgHandlerDisabled: 'rgba(47, 134, 246, 0.44)',
circleBorderColor: base.colors.borderElement,
circleBorderWidth: innerScaleSize(1),
formatColor: base.colors.textMinor,
},
// landscape
landscape: {
width: innerScaleSize(540),
radius: base.radius.normal,
fullscreenBg: base.colors.bgInverse,
zIndex: 1700,
},
// noticeBar
noticeBar: {
fill: 'rgba(89, 158, 248, .08)',
fontSize: base.fontSize.bodyNormal,
color: base.colors.primary,
zIndex: 1301,
borderRadius: innerScaleSize(32),
height: innerScaleSize(64),
paddingRight: innerScaleSize(24),
marginRight: innerScaleSize(12),
fillWarning: '#FFEEEF',
colorWarning: '#FF5B60',
fillActivity: '#FFEDDE',
colorActivity: '#FF843D',
},
// number-keyboard
numberKeyboard: {
width: '100%',
height: innerScaleSize(428),
bg: base.colors.bgBase,
keyHeight: innerScaleSize(107),
keyBg: base.colors.bgInverse,
keyBgTap: base.colors.bgBase,
keyConfirmBg: base.colors.primary,
keyConfirmBgTap: '#2A78DC',
keyFontSize: base.fontSize.headingMedium,
keyFontWeight: base.fontWeight.medium,
keyColor: base.colors.textBase,
keyConfirmColor: base.colors.textBaseInverse,
keyBordrColor: base.colors.borderBase,
zIndex: 1302,
},
// picker
picker: {
paddingH: base.gapSize.hSuperLarge,
fontSize: base.fontSize.captionNormal,
disabledOpacity: 0.5,
color: base.colors.textDisabled,
colorActive: base.colors.textHighlight,
fontWeightActive: base.fontWeight.medium,
borderColor: base.colors.borderBase,
zIndex: 1100,
},
// popup
popup: {
titleBarBg: base.colors.bgBase,
titleBarHeight: innerScaleSize(120),
titleBarHeightLarge: innerScaleSize(180),
titleBarRadius: innerScaleSize(8),
titleBarFontSizeButton: base.fontSize.captionLarge,
titleBarFontWeightButton: base.fontWeight.medium,
titleBarFontSizeTitle: innerScaleFont(40),
titleBarFontSizeDescribe: base.fontSize.bodyLarge,
titleBarColorTitle: base.colors.textBase,
titleBarColorDescribe: base.colors.textCaption,
titleBarColorButtonLeft: base.colors.textMinor,
titleBarColorButtonRight: base.colors.textHighlight,
maskBg: base.colors.mask,
zIndex: 1000,
},
// radio
radio: {
color: base.colors.textHighlight,
disabledColor: base.colors.textDisabled,
},
// check
check: {
color: base.colors.textHighlight,
disabledColor: base.colors.textDisabled,
},
// checkbox
checkbox: {
color: base.colors.textBase,
fontSize: base.fontSize.captionNormal,
disabledColor: base.colors.textDisabled,
activeColor: base.colors.primary,
activeBorderColor: base.colors.primary,
activeBg: `${base.colors.primary}0D`, // - alpha 5%
borderColor: base.colors.borderElement,
borderRadius: base.radius.normal,
},
// checklist
checklist: {
activeColor: base.colors.primary,
},
// resultPage
resultPage: {
imageSize: innerScaleSize(260),
titleFontSize: base.fontSize.captionNormal,
describeFontSize: base.fontSize.bodyLarge,
titleColor: base.colors.textBase,
describeColor: base.colors.textCaption,
},
// selector
selector: {
disabledOpacity: 0.2,
activeColor: base.colors.primary,
zIndex: 1102,
},
// stepper
stepper: {
fill: base.colors.bgBase,
disabledOpacity: base.opacity.disabled,
color: base.colors.textBase,
fontSize: base.fontSize.bodyLarge,
inputFontSize: base.fontSize.bodyNormal,
height: innerScaleSize(50),
widthButton: innerScaleSize(54),
widthInput: innerScaleSize(68),
radiusButton: 0,
radiusInput: 0,
marginLeftInput: innerScaleSize(4),
marginRightInput: innerScaleSize(4),
widthIcon: innerScaleSize(24),
},
// steps
steps: {
color: '#ccc',
colorActive: base.colors.primary,
borderSize: innerScaleSize(2),
iconSize: innerScaleSize(32), // - icon size
iconFontSize: innerScaleFont(32), // - icon size
textColor: base.colors.textBody,
descColor: base.colors.textCaption,
textFontSize: base.fontSize.bodyLarge,
textGapHorizontal: innerScaleSize(20),
textGapVertical: innerScaleSize(40),
descFontSize: base.fontSize.bodyNormal,
transitionDelay: 150, // - .15s
},
// switches
switchs: {
fill: base.colors.primary,
fillInverse: base.colors.bgDisabled,
handleColor: '#FFF',
itemColorDisabled: base.opacity.disabled,
width: innerScaleSize(80),
height: innerScaleSize(48),
thumbWidth: innerScaleSize(40),
thumbHeight: innerScaleSize(40),
thumbRadius: innerScaleSize(20),
thumbTop: innerScaleSize(4),
thumbLeft: innerScaleSize(4),
thumbX: innerScaleSize(36),
},
// swiper
swiper: {
indicatorFill: base.colors.primary,
},
// tabs
tabs: {
fontSize: base.fontSize.bodyLarge,
textColor: base.colors.textMinor,
fontWeight: base.fontWeight.medium,
activeColor: base.colors.primary,
disabledColor: base.colors.textDisabled,
bg: base.colors.bgBase,
height: innerScaleSize(80),
inkHeight: innerScaleSize(3),
offset: base.gapSize.hSuperLarge,
itemGap: base.gapSize.hMid,
},
// picker
tabPicker: {
height: innerScaleSize(400),
hGap: base.gapSize.hSuperLarge,
bg: base.colors.bgInverse,
zIndex: 1102,
},
// tag
tag: {
color: base.colors.primary,
filletRadius: base.radius.normal,
largeFontSize: base.fontSize.bodyNormal,
smallFontSize: base.fontSize.minorNormal,
tinyFontSize: innerScaleFont(12),
viewHeight: {
tiny: innerScaleSize(26.66667),
small: innerScaleSize(40.66667),
large: innerScaleSize(51.33333),
},
},
// tip
tip: {
maxWidth: innerScaleSize(160),
maxWidth2: innerScaleSize(100),
color: base.colors.textBaseInverse,
fontSize: base.fontSize.minorLarge,
borderRadius: 1000,
zIndex: 1303,
bottom: -5,
right: -4,
rightWeb: -3,
left: 4,
marginLeft: -5,
borderWidthL: 5,
borderWidthR: 6,
tipFill: 'rgba(74, 76, 91, 0.8)',
tipTransp: 'transparent',
boxShadow: '0 5px 20px rgba(0, 0, 0, .08)',
fill: '#41485D',
fillOpacity: 0.8,
radius: 1000,
paddingVertical: innerScaleSize(15),
paddingHorizontal: innerScaleSize(32),
paddingHorizontal2: innerScaleSize(60),
closeSize: innerScaleSize(32),
closeRight: innerScaleSize(16),
closeTop: innerScaleSize(-13),
marginTop: innerScaleSize(2),
},
// toast
toast: {
fill: 'rgba(65, 72, 93, .77)',
fontSize: base.fontSize.bodyLarge,
color: '#fff',
radius: base.radius.normal,
paddingVertical: innerScaleSize(20),
paddingHorizontal: innerScaleSize(30),
zIndex: 1600,
},
};
function customComponentsThemes () {
// @ts-ignore
const themes = global.MD_CUSTOM_COMPONENTS_THEMES;
if (!themes) {
return;
}
for (const key in themes) {
if (themes.hasOwnProperty(key) && MDComponentsThemes.hasOwnProperty(key)) {
MDComponentsThemes[key] = {
...MDComponentsThemes[key],
...themes[key],
};
}
}
}
customComponentsThemes();
export let button = MDComponentsThemes.button;
export let actionBar = MDComponentsThemes.actionBar;
export let actionSheet = MDComponentsThemes.actionSheet;
export let progress = MDComponentsThemes.progress;
export let agree = MDComponentsThemes.agree;
export let bill = MDComponentsThemes.bill;
export let captcha = MDComponentsThemes.captcha;
export let cashier = MDComponentsThemes.cashier;
export let chart = MDComponentsThemes.chart;
export let codebox = MDComponentsThemes.codebox;
export let datePicker = MDComponentsThemes.datePicker;
export let dialog = MDComponentsThemes.dialog;
export let overlay = MDComponentsThemes.overlay;
export let dropMenu = MDComponentsThemes.dropMenu;
export let field = MDComponentsThemes.field;
export let fieldItem = MDComponentsThemes.fieldItem;
export let cellItem = MDComponentsThemes.cellItem;
export let detailItem = MDComponentsThemes.detailItem;
export let icon = MDComponentsThemes.icon;
export let imageViewer = MDComponentsThemes.imageViewer;
export let inputItem = MDComponentsThemes.inputItem;
export let slider = MDComponentsThemes.slider;
export let landscape = MDComponentsThemes.landscape;
export let noticeBar = MDComponentsThemes.noticeBar;
export let numberKeyboard = MDComponentsThemes.numberKeyboard;
export let picker = MDComponentsThemes.picker;
export let popup = MDComponentsThemes.popup;
export let radio = MDComponentsThemes.radio;
export let check = MDComponentsThemes.check;
export let checkbox = MDComponentsThemes.checkbox;
export let checklist = MDComponentsThemes.checklist;
export let resultPage = MDComponentsThemes.resultPage;
export let selector = MDComponentsThemes.selector;
export let stepper = MDComponentsThemes.stepper;
export let steps = MDComponentsThemes.steps;
export let switchs = MDComponentsThemes.switchs;
export let swiper = MDComponentsThemes.swiper;
export let tabs = MDComponentsThemes.tabs;
export let tabPicker = MDComponentsThemes.tabPicker;
export let tag = MDComponentsThemes.tag;
export let viewHeight = MDComponentsThemes.viewHeight;
export let tip = MDComponentsThemes.tip;
export let toast = MDComponentsThemes.toast; | the_stack |
import { nestList, toggleList } from './lists';
import { jsx, makeEditor } from './tests/utils';
test('ordered list shortcut', () => {
let editor = makeEditor(
<editor>
<paragraph>
<text>
1.
<cursor />
</text>
</paragraph>
</editor>
);
editor.insertText(' ');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('unordered list shortcut - ', () => {
let editor = makeEditor(
<editor>
<paragraph>
<text>
-
<cursor />
</text>
</paragraph>
</editor>
);
editor.insertText(' ');
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('unordered list shortcut * ', () => {
let editor = makeEditor(
<editor>
<paragraph>
<text>
*
<cursor />
</text>
</paragraph>
</editor>
);
editor.insertText(' ');
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('direct sibling lists of the same type are merged', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
</unordered-list>
<unordered-list>
<list-item>
<list-item-content>
<text>some more text</text>
</list-item-content>
</list-item>
</unordered-list>
<ordered-list>
<list-item>
<list-item-content>
<text>some more text</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
<cursor />
</text>
</paragraph>
</editor>,
{ normalization: 'normalize' }
);
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
some more text
</text>
</list-item-content>
</list-item>
</unordered-list>
<ordered-list>
<list-item>
<list-item-content>
<text>
some more text
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
<cursor />
</text>
</paragraph>
</editor>
`);
});
test('inserting a break on end of list in empty list item exits list', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
editor.insertBreak();
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
<cursor />
</text>
</paragraph>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('inserting a break in empty list item in the middle of a list splits and exits', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
editor.insertBreak();
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
<cursor />
</text>
</paragraph>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle list on empty line', () => {
let editor = makeEditor(
<editor>
<paragraph>
<text>
<cursor />
</text>
</paragraph>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle list on line with text', () => {
let editor = makeEditor(
<editor>
<paragraph>
<text>
some text
<cursor />
</text>
</paragraph>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
some text
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle ordered-list inside of ordered-list', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
some text
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<paragraph>
<text>
some text
<cursor />
</text>
</paragraph>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle ordered-list inside of multi-item ordered-list', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
some more text
<cursor />
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>even more text</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
some more text
<cursor />
</text>
</paragraph>
<ordered-list>
<list-item>
<list-item-content>
<text>
even more text
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle unordered-list inside of single item in multi-item ordered-list', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
some more text
<cursor />
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>even more text</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'unordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</ordered-list>
<unordered-list>
<list-item>
<list-item-content>
<text>
some more text
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<ordered-list>
<list-item>
<list-item-content>
<text>
even more text
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('toggle unordered-list for all items in multi-item ordered-list', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
<anchor />
some text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>some more text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
even more text
<focus />
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'unordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
<anchor />
some text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
some more text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
even more text
<focus />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('backspace at start of list only unwraps the first item', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
<cursor />
some text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>some more text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>even more text</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
editor.deleteBackward('character');
expect(editor).toMatchInlineSnapshot(`
<editor>
<paragraph>
<text>
<cursor />
some text
</text>
</paragraph>
<ordered-list>
<list-item>
<list-item-content>
<text>
some more text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
even more text
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('nested list as direct child of list is moved to last list-item', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
</unordered-list>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>,
{ normalization: 'normalize' }
);
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</ordered-list>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('nest list', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
content
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
nestList(editor);
// all these extra nest calls should do nothing
nestList(editor);
nestList(editor);
nestList(editor);
nestList(editor);
nestList(editor);
nestList(editor);
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>
content
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('nest list when previous thing is nested', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>some more text</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
<list-item>
<list-item-content>
<text>
content
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
nestList(editor);
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>
some more text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
content
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('inserting a break on end of list non-empty list item adds a new list item', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
editor.insertBreak();
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('changing the type of a nested list', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>some text</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>
inner text
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
some text
</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>
inner text
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('changing the type of a nested list to something which it is nested inside', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>top text</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>middle text</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>
inner text
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</ordered-list>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'ordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
top text
</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>
middle text
</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>
inner text
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
</list-item>
</ordered-list>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
test('nesting a list item in an ordered list into an unordered list makes the item unordered', () => {
let editor = makeEditor(
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>first</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>second</text>
</list-item-content>
</list-item>
</ordered-list>
</list-item>
<list-item>
<list-item-content>
<text>
third
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
nestList(editor);
expect(editor).toMatchInlineSnapshot(`
<editor>
<unordered-list>
<list-item>
<list-item-content>
<text>
first
</text>
</list-item-content>
<ordered-list>
<list-item>
<list-item-content>
<text>
second
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
third
<cursor />
</text>
</list-item-content>
</list-item>
</ordered-list>
</list-item>
</unordered-list>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
// TODO: fix this(the snapshot shows the correct output)
// eslint-disable-next-line jest/no-disabled-tests
test.skip('toggling unordered-list in a nested unordered-list moves the list item out of the list', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>first</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>
second
<cursor />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
toggleList(editor, 'unordered-list');
expect(editor).toMatchInlineSnapshot(`
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>
first
</text>
</list-item-content>
</list-item>
</ordered-list>
<paragraph>
<text>
second
<cursor />
</text>
</paragraph>
<paragraph>
<text>
</text>
</paragraph>
</editor>
`);
});
// TODO: fix this
// eslint-disable-next-line jest/no-disabled-tests
test.skip('nesting multiple items at the same time works', () => {
let editor = makeEditor(
<editor>
<ordered-list>
<list-item>
<list-item-content>
<text>text</text>
</list-item-content>
<unordered-list>
<list-item>
<list-item-content>
<text>text</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
<anchor />
text
</text>
</list-item-content>
</list-item>
<list-item>
<list-item-content>
<text>
text
<focus />
</text>
</list-item-content>
</list-item>
</unordered-list>
</list-item>
</ordered-list>
<paragraph>
<text />
</paragraph>
</editor>
);
nestList(editor);
expect(editor).toMatchInlineSnapshot(``);
}); | the_stack |
import * as React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import uniq from 'lodash/uniq'
import UAParser from 'ua-parser-js'
import { useConditionalConfirm } from '@opentrons/components'
import { selectors as uiLabwareSelectors } from '../ui/labware'
import * as timelineWarningSelectors from '../top-selectors/timelineWarnings'
import { selectors as labwareIngredSelectors } from '../labware-ingred/selectors'
import { selectors as dismissSelectors } from '../dismiss'
import { selectors as stepFormSelectors } from '../step-forms'
import {
actions as stepsActions,
getCollapsedSteps,
getHoveredStepId,
getHoveredSubstep,
getIsMultiSelectMode,
getMultiSelectItemIds,
getMultiSelectLastSelected,
getSelectedStepId,
HoverOnStepAction,
HoverOnSubstepAction,
ToggleStepCollapsedAction,
SelectMultipleStepsAction,
} from '../ui/steps'
import { selectors as fileDataSelectors } from '../file-data'
import {
StepItem,
StepItemContents,
StepItemContentsProps,
StepItemProps,
} from '../components/steplist/StepItem'
import {
CLOSE_BATCH_EDIT_FORM,
CLOSE_STEP_FORM_WITH_CHANGES,
CLOSE_UNSAVED_STEP_FORM,
ConfirmDeleteModal,
DeleteModalType,
} from '../components/modals/ConfirmDeleteModal'
import { SubstepIdentifier } from '../steplist/types'
import { StepIdType } from '../form-types'
import { ThunkAction } from '../types'
interface Props {
stepId: StepIdType
stepNumber: number
onStepContextMenu?: () => void
}
const nonePressed = (keysPressed: boolean[]): boolean =>
keysPressed.every(keyPress => keyPress === false)
const getUserOS = (): string | undefined => new UAParser().getOS().name
const getMouseClickKeyInfo = (
event: React.MouseEvent
): { isShiftKeyPressed: boolean; isMetaKeyPressed: boolean } => {
const isMac: boolean = getUserOS() === 'Mac OS'
const isShiftKeyPressed: boolean = event.shiftKey
const isMetaKeyPressed: boolean =
(isMac && event.metaKey) || (!isMac && event.ctrlKey)
return { isShiftKeyPressed, isMetaKeyPressed }
}
export const ConnectedStepItem = (props: Props): JSX.Element => {
const { stepId, stepNumber } = props
const step = useSelector(stepFormSelectors.getSavedStepForms)[stepId]
const argsAndErrors = useSelector(stepFormSelectors.getArgsAndErrorsByStepId)[
stepId
]
const errorStepId = useSelector(fileDataSelectors.getErrorStepId)
const hasError = errorStepId === stepId || argsAndErrors.errors !== undefined
const hasTimelineWarningsPerStep = useSelector(
timelineWarningSelectors.getHasTimelineWarningsPerStep
)
const hasFormLevelWarningsPerStep = useSelector(
dismissSelectors.getHasFormLevelWarningsPerStep
)
const hasWarnings =
hasTimelineWarningsPerStep[stepId] || hasFormLevelWarningsPerStep[stepId]
const collapsed = useSelector(getCollapsedSteps)[stepId]
const hoveredSubstep = useSelector(getHoveredSubstep)
const hoveredStep = useSelector(getHoveredStepId)
const selectedStepId = useSelector(getSelectedStepId)
const orderedStepIds = useSelector(stepFormSelectors.getOrderedStepIds)
const multiSelectItemIds = useSelector(getMultiSelectItemIds)
const lastMultiSelectedStepId = useSelector(getMultiSelectLastSelected)
const isMultiSelectMode = useSelector(getIsMultiSelectMode)
const selected: boolean = multiSelectItemIds?.length
? multiSelectItemIds.includes(stepId)
: selectedStepId === stepId
const substeps = useSelector(fileDataSelectors.getSubsteps)[stepId]
const ingredNames = useSelector(labwareIngredSelectors.getLiquidNamesById)
const labwareNicknamesById = useSelector(
uiLabwareSelectors.getLabwareNicknamesById
)
const currentFormIsPresaved = useSelector(
stepFormSelectors.getCurrentFormIsPresaved
)
const singleEditFormHasUnsavedChanges = useSelector(
stepFormSelectors.getCurrentFormHasUnsavedChanges
)
const batchEditFormHasUnsavedChanges = useSelector(
stepFormSelectors.getBatchEditFormHasUnsavedChanges
)
// Actions
const dispatch = useDispatch()
const highlightSubstep = (payload: SubstepIdentifier): HoverOnSubstepAction =>
dispatch(stepsActions.hoverOnSubstep(payload))
const selectStep = (): ThunkAction<any> =>
dispatch(stepsActions.selectStep(stepId))
const selectMultipleSteps = (
steps: StepIdType[],
lastSelected: StepIdType
): ThunkAction<SelectMultipleStepsAction> =>
dispatch(stepsActions.selectMultipleSteps(steps, lastSelected))
const toggleStepCollapsed = (): ToggleStepCollapsedAction =>
dispatch(stepsActions.toggleStepCollapsed(stepId))
const highlightStep = (): HoverOnStepAction =>
dispatch(stepsActions.hoverOnStep(stepId))
const unhighlightStep = (): HoverOnStepAction =>
dispatch(stepsActions.hoverOnStep(null))
const handleStepItemSelection = (event: React.MouseEvent): void => {
const { isShiftKeyPressed, isMetaKeyPressed } = getMouseClickKeyInfo(event)
let stepsToSelect: StepIdType[] = []
// if user clicked on the last multi-selected step, shift/meta keys don't matter
const toggledLastSelected = stepId === lastMultiSelectedStepId
const noModifierKeys =
nonePressed([isShiftKeyPressed, isMetaKeyPressed]) || toggledLastSelected
if (noModifierKeys) {
if (multiSelectItemIds) {
const alreadySelected = multiSelectItemIds.includes(stepId)
if (alreadySelected) {
stepsToSelect = multiSelectItemIds.filter(id => id !== stepId)
} else {
stepsToSelect = [...multiSelectItemIds, stepId]
}
} else {
selectStep()
}
} else if (
(isMetaKeyPressed || isShiftKeyPressed) &&
currentFormIsPresaved
) {
// current form is presaved, enter batch edit mode with only the clicked
stepsToSelect = [stepId]
} else {
if (isShiftKeyPressed) {
stepsToSelect = getShiftSelectedSteps(
selectedStepId,
orderedStepIds,
stepId,
multiSelectItemIds,
lastMultiSelectedStepId
)
} else if (isMetaKeyPressed) {
stepsToSelect = getMetaSelectedSteps(
multiSelectItemIds,
stepId,
selectedStepId
)
}
}
if (stepsToSelect.length) {
selectMultipleSteps(stepsToSelect, stepId)
}
}
// step selection is gated when showConfirmation is true
const { confirm, showConfirmation, cancel } = useConditionalConfirm(
handleStepItemSelection,
isMultiSelectMode
? batchEditFormHasUnsavedChanges
: currentFormIsPresaved || singleEditFormHasUnsavedChanges
)
const stepItemProps: StepItemProps = {
description: step.stepDetails,
rawForm: step,
stepNumber,
stepType: step.stepType,
title: step.stepName,
collapsed,
error: hasError,
warning: hasWarnings,
selected,
isLastSelected: lastMultiSelectedStepId === stepId,
// no double-highlighting: whole step is only "hovered" when
// user is not hovering on substep.
hovered: hoveredStep === stepId && !hoveredSubstep,
highlightStep,
handleClick: confirm,
toggleStepCollapsed,
unhighlightStep,
isMultiSelectMode,
}
const stepItemContentsProps: StepItemContentsProps = {
rawForm: step,
stepType: step.stepType,
substeps,
ingredNames,
labwareNicknamesById,
highlightSubstep,
hoveredSubstep,
}
const getModalType = (): DeleteModalType => {
if (isMultiSelectMode) {
return CLOSE_BATCH_EDIT_FORM
} else if (currentFormIsPresaved) {
return CLOSE_UNSAVED_STEP_FORM
} else {
return CLOSE_STEP_FORM_WITH_CHANGES
}
}
return (
<>
{showConfirmation && (
<ConfirmDeleteModal
modalType={getModalType()}
onContinueClick={confirm}
onCancelClick={cancel}
/>
)}
<StepItem {...stepItemProps} onStepContextMenu={props.onStepContextMenu}>
{/* @ts-expect-error(sa, 2021-6-21): StepItemContents might return a list of JSX elements */}
<StepItemContents {...stepItemContentsProps} />
</StepItem>
</>
)
}
export function getMetaSelectedSteps(
multiSelectItemIds: StepIdType[] | null,
stepId: StepIdType,
selectedStepId: StepIdType | null
): StepIdType[] {
let stepsToSelect: StepIdType[]
if (multiSelectItemIds?.length) {
// already have a selection, add/remove the meta-clicked item
stepsToSelect = multiSelectItemIds.includes(stepId)
? multiSelectItemIds.filter(id => id !== stepId)
: [...multiSelectItemIds, stepId]
} else if (selectedStepId && selectedStepId === stepId) {
// meta-clicked on the selected single step
stepsToSelect = [selectedStepId]
} else if (selectedStepId) {
// meta-clicked on a different step, multi-select both
stepsToSelect = [selectedStepId, stepId]
} else {
// meta-clicked on a step when a terminal item was selected
stepsToSelect = [stepId]
}
return stepsToSelect
}
function getShiftSelectedSteps(
selectedStepId: StepIdType | null,
orderedStepIds: StepIdType[],
stepId: StepIdType,
multiSelectItemIds: StepIdType[] | null,
lastMultiSelectedStepId: StepIdType | null
): StepIdType[] {
let stepsToSelect: StepIdType[]
if (selectedStepId) {
stepsToSelect = getOrderedStepsInRange(
selectedStepId,
stepId,
orderedStepIds
)
} else if (multiSelectItemIds?.length && lastMultiSelectedStepId) {
const potentialStepsToSelect = getOrderedStepsInRange(
lastMultiSelectedStepId,
stepId,
orderedStepIds
)
const allSelected: boolean = potentialStepsToSelect
.slice(1)
.every(stepId => multiSelectItemIds.includes(stepId))
if (allSelected) {
// if they're all selected, deselect them all
if (multiSelectItemIds.length - potentialStepsToSelect.length > 0) {
stepsToSelect = multiSelectItemIds.filter(
(id: StepIdType) => !potentialStepsToSelect.includes(id)
)
} else {
// unless deselecting them all results in none being selected
stepsToSelect = [potentialStepsToSelect[0]]
}
} else {
stepsToSelect = uniq([...multiSelectItemIds, ...potentialStepsToSelect])
}
} else {
stepsToSelect = [stepId]
}
return stepsToSelect
}
function getOrderedStepsInRange(
lastSelectedStepId: StepIdType,
stepId: StepIdType,
orderedStepIds: StepIdType[]
): StepIdType[] {
const prevIndex: number = orderedStepIds.indexOf(lastSelectedStepId)
const currentIndex: number = orderedStepIds.indexOf(stepId)
const [startIndex, endIndex] = [prevIndex, currentIndex].sort((a, b) => a - b)
const orderedSteps = orderedStepIds.slice(startIndex, endIndex + 1)
return orderedSteps
} | the_stack |
import * as React from "react";
import { routerShape } from "react-router";
import { I18n } from "@lingui/core";
import { Trans } from "@lingui/macro";
import gql from "graphql-tag";
import { DataLayer, DataLayerType } from "@extension-kid/data-layer";
import { take } from "rxjs/operators";
import { Badge, SpacingBox } from "@dcos/ui-kit";
import set from "lodash.set";
import { Tooltip } from "reactjs-components";
import container from "#SRC/js/container";
import { TYPES } from "#SRC/js/types/containerTypes";
import AdvancedSection from "#SRC/js/components/form/AdvancedSection";
import AdvancedSectionContent from "#SRC/js/components/form/AdvancedSectionContent";
import AdvancedSectionLabel from "#SRC/js/components/form/AdvancedSectionLabel";
import FieldAutofocus from "#SRC/js/components/form/FieldAutofocus";
import FieldInput from "#SRC/js/components/form/FieldInput";
import FieldLabel from "#SRC/js/components/form/FieldLabel";
import FieldHelp from "#SRC/js/components/form/FieldHelp";
import FluidGeminiScrollbar from "#SRC/js/components/FluidGeminiScrollbar";
import FormRow from "#SRC/js/components/form/FormRow";
import FormGroup from "#SRC/js/components/form/FormGroup";
import FormGroupHeading from "#SRC/js/components/form/FormGroupHeading";
import FormGroupHeadingContent from "#SRC/js/components/form/FormGroupHeadingContent";
import FullScreenModal from "#SRC/js/components/modals/FullScreenModal";
import FieldError from "#SRC/js/components/form/FieldError";
import InfoTooltipIcon from "#SRC/js/components/form/InfoTooltipIcon";
import Loader from "#SRC/js/components/Loader";
import MesosStateStore from "#SRC/js/stores/MesosStateStore";
import dcosVersion$ from "#SRC/js/stores/dcos-version";
import { formatQuotaID } from "#PLUGINS/services/src/js/utils/QuotaUtil";
import {
GroupFormData,
GroupFormErrors,
GroupMutationResponse,
} from "#PLUGINS/services/src/js/types/GroupForm";
import GroupModalHeader from "./Header";
import ErrorsPanel from "./ErrorsPanel";
import {
emptyGroupFormData,
errorsFromOvercommitData,
groupFormDataFromGraphql,
getPathFromGroupId,
validateGroupFormData,
} from "./utils";
import { Observable } from "rxjs";
import { OvercommittedQuotaResource } from "#PLUGINS/services/src/js/data/errors/OvercommitQuotaError";
const dl = container.get<DataLayer>(DataLayerType);
const i18n = container.get<I18n>(TYPES.I18n);
const groupCreateMutation = gql`
mutation {
createGroup(data: $data)
}
`;
const groupEditMutation = gql`
mutation {
editGroup(data: $data)
}
`;
function getSaveAction(
data: GroupFormData,
isEdit: boolean
): Observable<{
data: {
createGroup?: GroupMutationResponse;
editGroup: GroupMutationResponse;
};
}> {
if (!isEdit) {
return dl.query(groupCreateMutation, {
data,
});
}
return dl.query(groupEditMutation, {
data,
});
}
function getGroup(id: string) {
return dl.query(
gql`
query {
group(id: $id) {
id
name
quota
}
}
`,
{ id, mesosStateStore: MesosStateStore }
);
}
interface ServiceRootGroupModalState {
isOpen: boolean;
isPending: boolean;
expandAdvancedSettings: boolean;
data: GroupFormData | null;
originalData: GroupFormData | null;
errors: GroupFormErrors;
isEdit: boolean;
error: boolean;
isForce: boolean;
hasValidated: boolean;
showQuotaOptions: boolean;
}
interface ServiceRootGroupModalProps {
id: string;
}
class ServiceRootGroupModal extends React.Component<
ServiceRootGroupModalProps,
ServiceRootGroupModalState
> {
public static contextTypes = {
router: routerShape,
};
public static defaultProps = {
id: "",
};
state = this.getInitialState();
public componentDidMount() {
this.getGroupFormData();
dcosVersion$.subscribe(({ hasQuotaSupport }) => {
this.setState({ showQuotaOptions: hasQuotaSupport });
});
}
public getInitialState(
props: ServiceRootGroupModalProps = this.props
): ServiceRootGroupModalState {
return {
isOpen: true,
isPending: false,
expandAdvancedSettings: false,
data: !!props.id ? null : emptyGroupFormData(),
originalData: null,
errors: {},
isEdit: !!props.id,
error: false,
isForce: false,
hasValidated: false,
showQuotaOptions: false,
};
}
public handleClose = () => {
// Start the animation of the modal by setting isOpen to false
this.setState(
{ isOpen: false, isPending: false, data: emptyGroupFormData() },
() => {
// Once state is set, start a timer for the length of the animation and
// navigate away once the animation is over.
setTimeout(this.context.router.goBack, 300);
}
);
};
public handleSave = () => {
let data: GroupFormData | null = this.state.data;
const { isPending, originalData, isEdit, isForce } = this.state;
if (isPending || data === null) {
return;
}
if (originalData && JSON.stringify(data) === JSON.stringify(originalData)) {
// No changes.
return this.handleClose();
}
const errors = validateGroupFormData(data, isEdit);
if (errors) {
this.setState({ errors, hasValidated: true });
return;
}
this.setState({ isPending: true, hasValidated: true });
if (!isEdit) {
// Format id
const newID = formatQuotaID(data.id);
data = (({ id, ...other }: GroupFormData): GroupFormData => ({
id: newID,
...other,
}))(data);
}
if (isForce) {
data.quota.force = true;
}
getSaveAction(data, isEdit)
.pipe(take(1))
.subscribe({
next: (mutationResponse) => {
let resp: GroupMutationResponse;
if (mutationResponse.data.createGroup) {
resp = mutationResponse.data.createGroup;
} else if (mutationResponse.data.editGroup) {
resp = mutationResponse.data.editGroup;
} else {
resp = {
code: 0,
success: false,
partialSuccess: false,
message: "Unknown response",
};
}
if (resp.success) {
return this.handleClose();
}
if (resp.partialSuccess) {
if (!isEdit) {
// switch to edit mode
const { id, enforceRole } = data as GroupFormData;
this.setState({
isEdit: true,
data,
originalData: {
...emptyGroupFormData(),
id,
enforceRole,
},
});
}
this.handleSaveError(resp.message, true, resp.data || null);
} else {
this.handleSaveError(resp.message);
}
},
error: (e) => {
// Be done after edit mode supported.
this.handleSaveError(e.message);
},
});
};
public handleSaveError = (
message: string,
mesos: boolean = false,
data: null | OvercommittedQuotaResource[] = null
) => {
switch (message) {
case "Conflict":
this.setState({
errors: {
id: <Trans>Name already exists. Try a different name.</Trans>,
form: [
<Trans key="groupIdConflict">
A group with the same name already exists. Try a different name.
</Trans>,
],
},
isPending: false,
});
return;
case "Forbidden":
this.setState({
errors: {
form: [
<Trans key="groupPermission">
You do not have permission to create a group.
</Trans>,
],
},
isPending: false,
});
return;
case "Overcommit":
this.setState({
errors: errorsFromOvercommitData(data),
isPending: false,
isForce: true,
});
return;
default:
const { isEdit } = this.state;
const form: any[] = [];
if (mesos) {
if (isEdit) {
form.push(
<Trans key="quotaError">
Unable to update group's quota: {message}
</Trans>
);
} else {
form.push(
<Trans key="quotaError">
Unable to create group's quota: {message}
</Trans>
);
}
} else if (isEdit) {
form.push(
<Trans key="miscGroup">Unable to update group: {message}</Trans>
);
} else {
form.push(
<Trans key="miscGroup">Unable to create group: {message}</Trans>
);
}
this.setState({
errors: {
form,
},
isPending: false,
});
return;
}
};
public getGroupFormData = (): void => {
const { id } = this.props;
if (!!id) {
getGroup(id)
.pipe(take(1))
.subscribe({
next: (groupData) => {
const data = groupFormDataFromGraphql(groupData.data.group);
this.setState({
data,
originalData: JSON.parse(JSON.stringify(data)),
expandAdvancedSettings: !data.enforceRole,
});
},
error: () => {
this.setState({ error: true });
},
});
}
};
public getModalContent = () => {
const { errors, data, isEdit, error } = this.state;
// If id exists, then we must be editing.
if (error) {
return <Trans>Looks Like Something is Wrong. Please try again.</Trans>;
}
if (!data) {
return <Loader />;
}
return (
<div className="create-service-modal-form__scrollbar-container modal-body-offset gm-scrollbar-container-flex">
<FluidGeminiScrollbar>
<div className="modal-body-padding-surrogate create-service-modal-form-container">
<form className="container" onChange={this.handleFormChange}>
<ErrorsPanel errors={errors.form} />
<Trans render="h1" className="flush-top short-bottom">
General
</Trans>
<FormRow>
<FormGroup
className="column-12 column-medium-4"
showError={Boolean(errors.id)}
>
<FieldLabel>
<FormGroupHeading required={true}>
<Trans
render={<FormGroupHeadingContent primary={true} />}
>
Name
</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldAutofocus>
<FieldInput
name="id"
type="text"
value={data.id}
disabled={isEdit}
/>
</FieldAutofocus>
<FieldError>{errors.id}</FieldError>
</FormGroup>
</FormRow>
<FormRow>
<FormGroup className="column-12">
<FieldLabel>
<FormGroupHeading>
<Trans
render={<FormGroupHeadingContent primary={false} />}
>
Path
</Trans>
</FormGroupHeading>
</FieldLabel>
<div>{getPathFromGroupId(data.id)}</div>
</FormGroup>
</FormRow>
{this.state.showQuotaOptions
? this.renderQuotaOptions(data, errors)
: null}
</form>
</div>
</FluidGeminiScrollbar>
</div>
);
};
public getAdvancedSettings = () => {
const { data, originalData, expandAdvancedSettings, isEdit } = this.state;
const roleEnforcementTooltipContent = (
<Trans>
Select role type that will be enforced to all services added inside this
group
</Trans>
);
if (!data) {
return;
}
const isDisabled = isEdit && originalData && originalData.enforceRole;
return (
<AdvancedSection initialIsExpanded={expandAdvancedSettings}>
<AdvancedSectionLabel>
<Trans>Advanced Settings</Trans>
</AdvancedSectionLabel>
<AdvancedSectionContent>
<FormRow>
<FormGroup className="column-12">
<FieldLabel>
<FormGroupHeading>
<FormGroupHeadingContent>
<Trans>Role Enforcement</Trans>
</FormGroupHeadingContent>
<FormGroupHeadingContent>
<Tooltip
content={roleEnforcementTooltipContent}
interactive={true}
maxWidth={300}
wrapText={true}
>
<InfoTooltipIcon />
</Tooltip>
</FormGroupHeadingContent>
</FormGroupHeading>
</FieldLabel>
<FieldLabel className="text-align-left">
<FieldInput
checked={data.enforceRole}
type="radio"
name="enforceRole"
value={true}
disabled={isDisabled}
/>
<Trans>Use Group Role</Trans>
<SpacingBox side="left" spacingSize="s" tag="span">
<Badge>
<Trans>Recommended</Trans>
</Badge>
</SpacingBox>
<FieldHelp>
<Trans>
Allows Quota to be enforced on all the services in the
group.
</Trans>
</FieldHelp>
</FieldLabel>
<FieldLabel className="text-align-left">
<FieldInput
checked={!data.enforceRole}
type="radio"
name="enforceRole"
value={false}
disabled={isDisabled}
/>
<Trans>Use Legacy Role</Trans>
<FieldHelp>
<Trans>
Will not enforce quota on all services in the group.
</Trans>
</FieldHelp>
</FieldLabel>
</FormGroup>
</FormRow>
</AdvancedSectionContent>
</AdvancedSection>
);
};
public handleFormChange = (event: React.FormEvent<HTMLFormElement>) => {
if (this.state.isPending || !this.state.data) {
return;
}
const target = event.target as HTMLInputElement;
const fieldName = target.getAttribute("name");
if (!fieldName) {
return;
}
let value: string | boolean;
switch (target.type) {
case "checkbox":
value = target.checked;
break;
case "radio":
value = target.value;
if (value === "true" || value === "false") {
value = value === "true";
}
break;
default:
value = target.value;
break;
}
const { data, isEdit, hasValidated } = this.state;
const newData = set(data, fieldName, value);
if (hasValidated) {
const newErrors = validateGroupFormData(newData, isEdit);
this.setState({
data: newData,
errors: newErrors || {},
isForce: false,
});
} else {
this.setState({ data: newData });
}
};
renderQuotaOptions(data, errors) {
return (
<React.Fragment>
<h2 className="short-bottom">
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent primary={true} />}>
Quota
</Trans>
</FormGroupHeading>
</h2>
<Trans render="p">
Define the maximum amount of resources that can be used by services in
this group.
</Trans>
<FormRow>
<FormGroup
className="column-2"
showError={errors.quota && Boolean(errors.quota.cpus)}
>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent />}>CPUs</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldAutofocus>
<FieldInput
name="quota.cpus"
type="text"
value={data.quota.cpus}
/>
<FieldError>
{errors.quota && errors.quota.cpus ? errors.quota.cpus : null}
</FieldError>
</FieldAutofocus>
</FormGroup>
<FormGroup
className="column-2"
showError={errors.quota && Boolean(errors.quota.mem)}
>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent />}>Mem (MiB)</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput name="quota.mem" type="text" value={data.quota.mem} />
<FieldError>
{errors.quota && errors.quota.mem ? errors.quota.mem : null}
</FieldError>
</FormGroup>
<FormGroup
className="column-2"
showError={errors.quota && Boolean(errors.quota.disk)}
>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent />}>Disk (MiB)</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput name="quota.disk" type="text" value={data.quota.disk} />
<FieldError>
{errors.quota && errors.quota.disk ? errors.quota.disk : null}
</FieldError>
</FormGroup>
<FormGroup
className="column-2"
showError={errors.quota && Boolean(errors.quota.gpus)}
>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent />}>GPUs</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput name="quota.gpus" type="text" value={data.quota.gpus} />
<FieldError>
{errors.quota && errors.quota.gpus ? errors.quota.gpus : null}
</FieldError>
</FormGroup>
</FormRow>
{this.getAdvancedSettings()}
</React.Fragment>
);
}
public render() {
const { isEdit, isForce } = this.state;
return (
<FullScreenModal
header={
<GroupModalHeader
i18n={i18n}
mode={isForce ? "force" : isEdit ? "edit" : "create"}
onClose={this.handleClose}
onSave={this.handleSave}
/>
}
useGemini={false}
open={this.state.isOpen}
{...this.props}
>
{this.getModalContent()}
</FullScreenModal>
);
}
}
export default ServiceRootGroupModal; | the_stack |
import {concatByteArrays} from "teamten-ts-utils";
import {Density, FloppyDisk, FloppyDiskGeometry, numberToSide, Side} from "./FloppyDisk.js";
import {toHexByte} from "z80-base";
// Print extra debugging information.
const DEBUG = false;
// Whether to check the high bits of the GAT table entries. I keep seeing floppies with wrong values
// here, so disabling this. Those bits were probably not accessed anyway, so it's probably not out of
// spec to be wrong.
const CHECK_GAT_HIGH_BITS = false;
// Apparently this is constant in TRSDOS.
const BYTES_PER_SECTOR = 256;
// Copyright in the last 16 bytes of each directory sector, for Model III TRSDOS.
const EXPECTED_TANDY = "(c) 1980 Tandy";
// Password value that means "no password".
const NO_PASSWORD = 0xEF5C;
// Password value for "PASSWORD".
const PASSWORD = 0xD38F;
// Various TRSDOS versions, labeled after the model they were made for.
enum TrsdosVersion {
MODEL_1, // TRSDOS 2.3
MODEL_3, // TRSDOS 1.3
MODEL_4, // TRSDOS 6 or LDOS
}
/**
* Represents the position of a directory entry.
*/
class DirEntryPosition {
// Zero-based sector index into the directory track. Sector 0 is GAT, 1 is HIT.
public readonly sectorIndex: number;
// Zero-based index of the directory entry into the sector.
public readonly dirEntryIndex: number;
constructor(sectorIndex: number, dirEntryIndex: number) {
this.sectorIndex = sectorIndex;
this.dirEntryIndex = dirEntryIndex;
}
/**
* Make a string that represents this object, to us as a key in a Map.
*/
public asKey(): string {
return this.sectorIndex + "," + this.dirEntryIndex;
}
}
/**
* The Model III version of TRSDOS is pretty different than the Model I and 4 version.
*/
function isModel3(version: TrsdosVersion): version is TrsdosVersion.MODEL_3 {
return version === TrsdosVersion.MODEL_3;
}
/**
* Decodes binary into an ASCII string. Returns undefined if any non-ASCII value is
* found in the string, where "ASCII" is defined as being in the range 32 to 126 inclusive.
*/
function decodeAscii(binary: Uint8Array, trim: boolean = true): string | undefined {
const parts: string[] = [];
for (const b of binary) {
if (b === 0x0D || b === 0x00) {
// Auto command ends with carriage return, but also support nul.
break;
}
if (b < 32 || b >= 127) {
return undefined;
}
parts.push(String.fromCodePoint(b));
}
let s = parts.join("");
if (trim) {
s = s.trim();
}
return s;
}
/**
* Lowest three bits of the directory entry's flag.
*/
export enum TrsdosProtectionLevel {
// Keep this values in this order, they match the bit values (0 to 7).
FULL,
REMOVE,
RENAME,
WRITE,
UPDATE,
READ,
EXEC,
NO_ACCESS,
}
/**
* Gets the string version of the protection level enum.
*/
export function trsdosProtectionLevelToString(level: TrsdosProtectionLevel, version: TrsdosVersion): string {
switch (level) {
case TrsdosProtectionLevel.FULL:
return "FULL";
case TrsdosProtectionLevel.REMOVE:
return isModel3(version) ? "REMOVE" : "KILL";
case TrsdosProtectionLevel.RENAME:
return "RENAME";
case TrsdosProtectionLevel.WRITE:
return isModel3(version) ? "WRITE" : "UNUSED";
case TrsdosProtectionLevel.UPDATE:
return isModel3(version) ? "UPDATE" : "WRITE";
case TrsdosProtectionLevel.READ:
return "READ";
case TrsdosProtectionLevel.EXEC:
return "EXEC";
case TrsdosProtectionLevel.NO_ACCESS:
return "NO_ACCESS";
default:
return "UNKNOWN";
}
}
/**
* A contiguous number of sectors for storing part of a file.
*/
export class TrsdosExtent {
public readonly trackNumber: number;
public readonly granuleOffset: number;
public readonly granuleCount: number;
constructor(trackNumber: number, granuleOffset: number, granuleCount: number) {
this.trackNumber = trackNumber;
this.granuleOffset = granuleOffset;
this.granuleCount = granuleCount;
}
}
/**
* Decode an array of extents.
*
* @param binary byte we'll be pulling the extents from.
* @param begin index of first extent in binary.
* @param end index past last extent in binary.
* @param geometry the disk geometry, for error checking.
* @param version version of TRSDOS.
* @param trackFirst whether the track comes first or second.
*/
function decodeExtents(binary: Uint8Array, begin: number, end: number,
geometry: FloppyDiskGeometry,
version: TrsdosVersion,
trackFirst: boolean): TrsdosExtent[] | undefined {
const extents: TrsdosExtent[] = [];
for (let i = begin; i < end; i += 2) {
if (binary[i] === 0xFF && binary[i + 1] === 0xFF) {
break;
}
const trackNumber = binary[trackFirst ? i : i + 1];
const granuleByte = binary[trackFirst ? i + 1 : i];
const granuleOffset = granuleByte >> 5;
const granuleCount = (granuleByte & 0x1F) + (isModel3(version) ? 0 : 1);
if (!geometry.isValidTrackNumber(trackNumber)) {
// Not a TRSDOS disk.
if (DEBUG) console.log("Invalid extent: ", i, trackNumber, granuleByte, granuleOffset, granuleCount)
return undefined;
}
extents.push(new TrsdosExtent(trackNumber, granuleOffset, granuleCount));
}
return extents;
}
/**
* The Granule Allocation Table sector info.
*/
export class TrsdosGatInfo {
// One byte for every track. Each bit indicates a free (0) or used (1) granule, with bit 0 corresponding
// to first granule in track, etc. In Model 1/4, higher bits are 1, in Model 3 they're zero.
public readonly gat: Uint8Array;
// All models:
public readonly password: number;
public readonly name: string;
public readonly date: string;
public readonly autoCommand: string;
constructor(gat: Uint8Array, password: number, name: string, date: string, autoCommand: string) {
this.gat = gat;
this.password = password;
this.name = name;
this.date = date;
this.autoCommand = autoCommand;
}
/**
* Check various things about the GAT to see if it's valid.
*/
public isValid(granulesPerTrack: number, version: TrsdosVersion): boolean {
if (CHECK_GAT_HIGH_BITS) {
// The mask for the unused bits in the GAT, and the value we expect to see there.
const mask = (0xFF << granulesPerTrack) & 0xFF;
const expectedValue = isModel3(version) ? 0x00 : mask;
// Top bits don't map to anything, so must be zero (Model 3) or one (Model 1/4).
let trackNumber = 0;
for (const g of this.gat) {
// Skip the first track, I don't think it actually stores granules (it's the boot sector, etc.).
if (trackNumber !== 0 && (g & mask) !== expectedValue) {
if (DEBUG) console.log("GAT: high bits are not correct: 0x" + toHexByte(g) +
" track " + trackNumber + " with " + granulesPerTrack + " granules per track");
return false;
}
trackNumber += 1;
}
}
return true;
}
}
/**
* Extra info for TRSDOS 1 and 4.
*/
export class Trsdos14GatInfo extends TrsdosGatInfo {
// Encoded in hex, e.g., 0x51 means LDOS 5.1.
public readonly osVersion: number;
public readonly cylinderCount: number;
public readonly granulesPerTrack: number;
public readonly sideCount: number;
public readonly density: Density;
constructor(gat: Uint8Array, password: number, name: string, date: string, autoCommand: string,
osVersion: number, cylinderCount: number, granulesPerTrack: number,
sideCount: number, density: Density) {
super(gat, password, name, date, autoCommand);
this.osVersion = osVersion;
this.cylinderCount = cylinderCount;
this.granulesPerTrack = granulesPerTrack;
this.sideCount = sideCount;
this.density = density;
}
}
/**
* Converts a sector to a GAT object, or undefined if we don't think this is a GAT sector.
*/
function decodeGatInfo(binary: Uint8Array, geometry: FloppyDiskGeometry, version: TrsdosVersion): TrsdosGatInfo | undefined {
// One byte for each track. Each bit is a granule, 0 means free and 1 means used.
const gat = binary.subarray(0, geometry.numTracks());
// Assume big endian.
const password = (binary[0xCE] << 8) | binary[0xCF];
const name = decodeAscii(binary.subarray(0xD0, 0xD8));
const date = decodeAscii(binary.subarray(0xD8, 0xE0));
// This is only before version 6. At 6 they moved this elsewhere and put other things here that we ignore.
const autoCommand = decodeAscii(binary.subarray(0xE0));
// Implies that this is not a TRSDOS disk.
if (name === undefined || date === undefined || autoCommand === undefined) {
if (DEBUG) console.log("GAT: critical data is missing");
return undefined;
}
if (isModel3(version)) {
return new TrsdosGatInfo(gat, password, name, date, autoCommand);
} else {
// Additional fields for Model 1 and 4.
const osVersion = binary[0xCB];
const cylinderCount = binary[0xCC] + 35;
const flags = binary[0xCD];
// Docs say granules per cylinder, but VTK treats this as granules per track.
const granulesPerTrack = (flags & 0x07) + 1;
const sideCount = (flags & 0x20) !== 0 ? 2 : 1;
const density = (flags & 0x40) !== 0 ? Density.DOUBLE : Density.SINGLE;
// TODO data disks only reserve 2 entries for system files, not 16. But I don't know which two!
const isDataDisk = osVersion === 0x60 && (flags & 0x80) !== 0;
return new Trsdos14GatInfo(gat, password, name, date, autoCommand,
osVersion, cylinderCount, granulesPerTrack, sideCount, density);
}
}
/**
* The Hash Allocation Table sector info.
*/
export class TrsdosHitInfo {
public readonly hit: Uint8Array;
public readonly systemFiles: TrsdosExtent[];
constructor(hit: Uint8Array, systemFiles: TrsdosExtent[]) {
this.hit = hit;
this.systemFiles = systemFiles;
}
}
/**
* Decode the Hash Index Table sector, or undefined if we don't think this is a TRSDOS disk.
*/
function decodeHitInfo(binary: Uint8Array, geometry: FloppyDiskGeometry, version: TrsdosVersion): TrsdosHitInfo | undefined {
// One byte for each file.
const hit = binary.subarray(0, isModel3(version) ? 80 : 256);
// There are 16 extents to read for the system files.
const systemFiles = isModel3(version)
? decodeExtents(binary, 0xE0, binary.length, geometry, version, false)
: [];
if (systemFiles === undefined) {
if (DEBUG) console.log("Extents in HIT are invalid");
return undefined;
}
return new TrsdosHitInfo(hit, systemFiles);
}
/**
* Single (valid) directory entry for a file.
*/
export class TrsdosDirEntry {
public readonly version: TrsdosVersion;
public readonly flags: number;
public readonly day: number;
public readonly month: number;
public readonly year: number;
public readonly lastSectorSize: number;
// Logical record length.
public readonly lrl: number;
public readonly rawFilename: string;
public readonly updatePassword: number;
public readonly accessPassword: number;
// This is the number of *full* sectors. It doesn't include a possible
// additional partial sector of "lastSectorSize" bytes.
public readonly sectorCount: number;
// HIT entry of the extended directory entry, if any.
public readonly nextHit: number | undefined;
// Link to next (extended) directory entry.
public nextDirEntry: TrsdosDirEntry | undefined = undefined;
public readonly extents: TrsdosExtent[];
constructor(version: TrsdosVersion, flags: number, day: number, month: number, year: number,
lastSectorSize: number, lrl: number,
filename: string, updatePassword: number, accessPassword: number,
sectorCount: number, nextHit: number | undefined, extents: TrsdosExtent[]) {
this.version = version;
this.flags = flags;
this.day = day;
this.month = month;
this.year = year;
this.lastSectorSize = lastSectorSize;
this.lrl = lrl;
this.rawFilename = filename;
this.updatePassword = updatePassword;
this.accessPassword = accessPassword;
this.sectorCount = sectorCount;
this.nextHit = nextHit;
this.extents = extents;
}
/**
* Get the protection level for the file.
*/
public getProtectionLevel(): TrsdosProtectionLevel {
return (this.flags & 0x07) as TrsdosProtectionLevel;
}
/**
* Whether the file is hidden in a directory listing.
*/
public isHidden(): boolean {
return (this.flags & 0x08) !== 0;
}
/**
* Whether the file has an entry in the HIT table. This bit is set to 0 when
* deleting a file.
*/
public isActive(): boolean {
return (this.flags & 0x10) !== 0;
}
/**
* Whether there should be limitations to how many times you can copy this file.
* Other docs (maybe for LDOS) say that this indicates "Partitioned Data Set".
*/
public hasBackupLimitation(): boolean {
return (this.flags & 0x20) !== 0;
}
/**
* Whether this is a system file (as opposed to user file).
*/
public isSystemFile(): boolean {
return (this.flags & 0x40) !== 0;
}
/**
* Whether this is an extended entry (as opposed to primary entry). Each entry has a limited
* number of extents extents, so subsequent extents are stored in extended entries.
*/
public isExtendedEntry(): boolean {
return (this.flags & 0x80) !== 0;
}
/**
* Get a user-visible string version of the flags.
*/
public getFlagsString(): string {
const parts: string[] = [];
parts.push(trsdosProtectionLevelToString(this.getProtectionLevel(), this.version));
if (this.isHidden()) {
parts.push("hidden");
}
if (!this.isActive()) {
// Should never happen.
parts.push("inactive");
}
if (this.hasBackupLimitation()) {
parts.push("limits");
}
if (this.isSystemFile()) {
parts.push("system");
}
if (this.isExtendedEntry()) {
parts.push("extended");
}
return "[" + parts.join(",") + "]";
}
/**
* Get the basename (part before the period) of the filename.
*/
public getBasename(): string {
return this.rawFilename.substr(0, 8).trim();
}
/**
* Get the extension of the filename.
*/
public getExtension(): string {
return this.rawFilename.substr(8).trim();
}
/**
* Get the full filename (without the internal spaces of the raw filename). If the
* file has an extension, it will be preceded by the specified separator.
*/
public getFilename(extensionSeparator: string): string {
const extension = this.getExtension();
return this.getBasename() + (extension === "" ? "" : extensionSeparator + extension);
}
/**
* Return the size of the file in bytes.
*/
public getSize(): number {
let size = this.sectorCount*BYTES_PER_SECTOR + this.lastSectorSize;
// On model 1/4, the last sector size byte represents the size of the last sector. On model 3 it's
// in addition to the sector count.
if (!isModel3(this.version) && this.lastSectorSize > 0) {
size -= BYTES_PER_SECTOR;
}
return size;
}
/**
* Return the date in MM/YY format.
*/
public getDateString(): string {
return this.month.toString().padStart(2, "0") + "/" + (this.year - 1900).toString().padStart(2, "0");
}
/**
* Return the date in DD/MM/YYYY format, where the day might be blank if missing.
*/
public getFullDateString(): string {
return (this.day === 0 ? " " : this.day.toString().padStart(2, "0") + "/") +
(this.month === 0 ? " " : this.month.toString().padStart(2, "0") + "/") +
this.year.toString();
}
/**
* Return the date as an object.
*/
public getDate(): Date {
if (this.day === undefined) {
return new Date(this.year, this.month - 1);
} else {
return new Date(this.year, this.month - 1, this.day);
}
}
}
/**
* Decodes a directory entry from a 32- or 48-byte chunk, or undefined if the directory entry is empty.
*/
function decodeDirEntry(binary: Uint8Array, geometry: FloppyDiskGeometry, version: TrsdosVersion): TrsdosDirEntry | undefined {
const flags = binary[0];
const month = binary[1] & 0x0F;
// binary[1] has a few extra bits on Model 1/4 that we don't care about.
// Date info.
const day = isModel3(version) ? 0 : binary[2] >> 3;
const year = isModel3(version) ? binary[2] + 1900 : (binary[2] & 0x07) + 1980;
// Number of bytes on last sector.
const lastSectorSize = binary[3];
// Logical record length.
const lrl = ((binary[4] - 1) & 0xFF) + 1; // 0 -> 256.
const filename = decodeAscii(binary.subarray(5, 16));
// Not sure how to convert these two into a number. Just use big endian.
const updatePassword = (binary[16] << 8) | binary[17];
const accessPassword = (binary[18] << 8) | binary[19];
// Number of sectors in the file. Little endian.
const sectorCount = (binary[21] << 8) | binary[20];
// Number of extents listed in the directory entry.
const extentsCount = isModel3(version) ? 13 : 4;
// Byte offsets.
const extentsStart = 22;
const extentsEnd = extentsStart + 2*extentsCount; // Two bytes per extent.
const extents = decodeExtents(binary, extentsStart, extentsEnd, geometry, version, true);
// On model 1/4 bytes 30 and 31 point to extended directory entry, if any.
const nextHit = !isModel3(version) && binary[30] === 0xFE ? binary[31] : undefined;
if (filename === undefined || extents === undefined) {
// This signals empty directory, but really should imply a non-TRSDOS disk.
return undefined;
}
return new TrsdosDirEntry(version, flags, day, month, year, lastSectorSize, lrl, filename, updatePassword,
accessPassword, sectorCount, nextHit, extents);
}
/**
* A decoded TRSDOS diskette.
*/
export class Trsdos {
public readonly disk: FloppyDisk;
public readonly version: TrsdosVersion;
public readonly sectorsPerGranule: number;
public readonly gatInfo: TrsdosGatInfo;
public readonly hitInfo: TrsdosHitInfo;
public readonly dirEntries: TrsdosDirEntry[];
constructor(disk: FloppyDisk, version: TrsdosVersion, sectorsPerGranule: number,
gatInfo: TrsdosGatInfo,
hitInfo: TrsdosHitInfo, dirEntries: TrsdosDirEntry[]) {
this.disk = disk;
this.version = version;
this.sectorsPerGranule = sectorsPerGranule;
this.gatInfo = gatInfo;
this.hitInfo = hitInfo;
this.dirEntries = dirEntries;
}
/**
* Guess the name of the operating system.
*/
public getOperatingSystemName(): string {
if (this.gatInfo instanceof Trsdos14GatInfo && (this.gatInfo.osVersion & 0xF0) === 0x50) {
return "LDOS";
} else {
return "TRSDOS";
}
}
/**
* Return a string for the version of TRSDOS or LDOS this is. There's some guesswork here!
*/
public getVersion(): string {
if (this.gatInfo instanceof Trsdos14GatInfo) {
const osVersion = this.gatInfo.osVersion;
return (osVersion >> 4) + "." + (osVersion & 0x0F);
} else {
// Probably Model III, guess 1.3.
return "1.3";
}
}
/**
* Read the binary for a file on the diskette.
*/
public readFile(firstDirEntry: TrsdosDirEntry): Uint8Array {
const sectors: Uint8Array[] = [];
const geometry = this.disk.getGeometry();
const sectorsPerTrack = geometry.lastTrack.numSectors();
// Number of sectors left to read.
const fileSize = firstDirEntry.getSize();
let sectorCount = Math.ceil(fileSize / BYTES_PER_SECTOR);
// Loop through all the directory entries for this file.
let dirEntry: TrsdosDirEntry | undefined = firstDirEntry;
while (dirEntry !== undefined) {
for (const extent of dirEntry.extents) {
let trackNumber = extent.trackNumber;
let trackGeometry = geometry.getTrackGeometry(trackNumber);
const extentSectorCount = extent.granuleCount * this.sectorsPerGranule;
let sectorNumber = trackGeometry.firstSector + extent.granuleOffset * this.sectorsPerGranule;
for (let i = 0; i < extentSectorCount && sectorCount > 0; i++, sectorNumber++, sectorCount--) {
if (sectorNumber > trackGeometry.lastSector) {
// Move to the next track.
trackNumber += 1;
trackGeometry = geometry.getTrackGeometry(trackNumber);
sectorNumber = trackGeometry.firstSector;
}
// TODO not sure how to handle side here. I think sectors just continue off the end, so
// we should really be doing everything with cylinders in this routine, and have twice
// as many max sectors if double-sided.
const sector = this.disk.readSector(trackNumber, Side.FRONT, sectorNumber);
if (sector === undefined) {
console.log(`Sector couldn't be read ${trackNumber}, ${sectorNumber}`);
// TODO
} else {
// TODO check deleted?
if (sector.crcError) {
console.log("Sector has CRC error");
}
if (sector.deleted) {
// console.log("Sector " + sectorNumber + " is deleted");
}
sectors.push(sector.data);
}
}
}
// Follow the linked list of directory entries.
dirEntry = dirEntry.nextDirEntry;
}
// All sectors.
const binary = concatByteArrays(sectors);
// Clip to size. In principle this is cheap because it's a view.
return binary.subarray(0, fileSize);
}
}
/**
* Maps an index into the HIT (zero-based) to its sector index and dir entry index.
*/
function hitNumberToDirEntry(hitIndex: number, version: TrsdosVersion, dirEntriesPerSector: number): DirEntryPosition {
let sectorIndex: number;
let dirEntryIndex: number;
if (isModel3(version)) {
// These are laid out continuously.
sectorIndex = hitIndex / dirEntriesPerSector + 2;
dirEntryIndex = hitIndex % dirEntriesPerSector;
} else {
// These are laid out in chunks of 32 to make decoding easier.
sectorIndex = (hitIndex & 0x1F) + 2;
dirEntryIndex = hitIndex >> 5;
}
return new DirEntryPosition(sectorIndex, dirEntryIndex);
}
/**
* Decode a TRSDOS diskette for a particular version, or return undefined if this does not look like such a diskette.
*/
export function decodeTrsdosVersion(disk: FloppyDisk, version: TrsdosVersion): Trsdos | undefined {
const geometry = disk.getGeometry();
const bootSector = disk.readSector(geometry.firstTrack.trackNumber,
geometry.firstTrack.firstSide, geometry.firstTrack.firstSector);
if (bootSector === undefined) {
if (DEBUG) console.log("Can't read boot sector");
return undefined;
}
let dirTrackNumber = bootSector.data[isModel3(version) ? 1 : 2] & 0x7F;
if (!geometry.isValidTrackNumber(dirTrackNumber)) {
if (DEBUG) console.log("Bad dir track: " + dirTrackNumber);
return undefined;
}
// Decode Granule Allocation Table sector.
const gatSector = disk.readSector(dirTrackNumber, geometry.lastTrack.firstSide, geometry.lastTrack.firstSector);
if (gatSector === undefined) {
if (DEBUG) console.log("Can't read GAT sector");
return undefined;
}
const gatInfo = decodeGatInfo(gatSector.data, geometry, version);
if (gatInfo === undefined) {
if (DEBUG) console.log("Can't decode GAT");
return undefined;
}
const sideCount = geometry.lastTrack.numSides();
const sectorsPerTrack = geometry.lastTrack.numSectors();
let dirEntryLength: number;
let sectorsPerGranule: number;
let granulesPerTrack: number;
if (isModel3(version)) {
dirEntryLength = 48;
sectorsPerGranule = geometry.lastTrack.density === Density.SINGLE ? 2 : 3;
granulesPerTrack = Math.floor(sectorsPerTrack / sectorsPerGranule);
} else {
if (!(gatInfo instanceof Trsdos14GatInfo)) {
throw new Error("GAT must be Model 1/4 object");
}
dirEntryLength = 32;
if (sideCount !== gatInfo.sideCount) {
// Sanity check.
if (DEBUG) console.log(`Warning: Media sides ${sideCount} doesn't match GAT sides ${gatInfo.sideCount}`);
// But don't fail loading, keep using media sides.
}
granulesPerTrack = version === TrsdosVersion.MODEL_1
? geometry.lastTrack.density === Density.SINGLE ? 2 : 3
: gatInfo.granulesPerTrack;
sectorsPerGranule = Math.floor(sectorsPerTrack / granulesPerTrack);
}
const dirEntriesPerSector = Math.floor(geometry.lastTrack.sectorSize / dirEntryLength);
if (!gatInfo.isValid(granulesPerTrack, version)) {
if (DEBUG) console.log("GAT is invalid");
return undefined;
}
const granulesPerCylinder = granulesPerTrack * sideCount;
if (granulesPerCylinder < 2 || granulesPerCylinder > 8) {
if (DEBUG) console.log("Invalid number of granules per cylinder: " + granulesPerCylinder);
return undefined;
}
if (sectorsPerTrack % granulesPerTrack !== 0) {
if (DEBUG) console.log(`Sectors per track ${sectorsPerTrack} is not a multiple of granules per track ${granulesPerTrack}`);
return undefined;
}
if (!isModel3(version)) {
if (geometry.lastTrack.density === Density.SINGLE && sectorsPerGranule !== 5 && sectorsPerGranule !== 8) {
if (DEBUG) console.log("Invalid sectors per granule for single density: " + sectorsPerGranule);
return undefined;
}
if (geometry.lastTrack.density === Density.DOUBLE && sectorsPerGranule !== 6 && sectorsPerGranule !== 10) {
if (DEBUG) console.log("Invalid sectors per granule for double density: " + sectorsPerGranule);
return undefined;
}
}
// Decode Hash Index Table sector.
const hitSector = disk.readSector(dirTrackNumber, geometry.lastTrack.firstSide,
geometry.lastTrack.firstSector + 1);
if (hitSector === undefined) {
if (DEBUG) console.log("Can't read HIT sector");
return undefined;
}
const hitInfo = decodeHitInfo(hitSector.data, geometry, version);
if (hitInfo === undefined) {
if (DEBUG) console.log("Can't decode HIT");
return undefined;
}
// Map from position of directory entry to its actual entry. The key is the asKey() result
// of DirEntryPosition.
const dirEntries = new Map<string, TrsdosDirEntry>();
// Decode directory entries.
for (let side = 0; side < geometry.lastTrack.numSides(); side++) {
for (let sectorIndex = 0; sectorIndex < geometry.lastTrack.numSectors(); sectorIndex++) {
const sectorNumber = geometry.firstTrack.firstSector + sectorIndex;
if (side === 0 && sectorIndex < 2) {
// Skip GAT and HIT.
continue;
}
const dirSector = disk.readSector(dirTrackNumber, numberToSide(side), sectorNumber);
if (dirSector !== undefined) {
// Sanity check Model III entry.
if (isModel3(version)) {
const tandy = decodeAscii(dirSector.data.subarray(dirEntriesPerSector * dirEntryLength));
if (tandy !== EXPECTED_TANDY) {
console.error(`Expected "${EXPECTED_TANDY}", got "${tandy}"`);
return undefined;
}
}
for (let i = 0; i < dirEntriesPerSector; i++) {
if (!isModel3(version) && side === 0 && sectorIndex < 2 + 8 && i < 2) {
// Skip system files, the first two files in the first 8 sectors of the first side.
continue;
}
const dirEntryBinary = dirSector.data.subarray(i * dirEntryLength, (i + 1) * dirEntryLength);
const dirEntry = decodeDirEntry(dirEntryBinary, geometry, version);
if (dirEntry !== undefined) {
dirEntries.set(new DirEntryPosition(sectorIndex, i).asKey(), dirEntry);
}
}
}
}
}
// Keep only good entries (active and not extensions to other entries).
const goodDirEntries = Array.from(dirEntries.values()).filter(d => d.isActive() && !d.isExtendedEntry());
// Look up continuations by sector/index and update original entries.
for (const dirEntry of dirEntries.values()) {
if (dirEntry.nextHit !== undefined) {
const position = hitNumberToDirEntry(dirEntry.nextHit, version, dirEntriesPerSector);
const nextDirEntry = dirEntries.get(position.asKey());
if (nextDirEntry !== undefined) {
dirEntry.nextDirEntry = nextDirEntry;
}
}
}
return new Trsdos(disk, version, sectorsPerGranule, gatInfo, hitInfo, goodDirEntries);
}
/**
* Decode a TRSDOS diskette, or return undefined if this does not look like such a diskette.
*/
export function decodeTrsdos(disk: FloppyDisk): Trsdos | undefined {
// Try each one in turn.
let trsdos = decodeTrsdosVersion(disk, TrsdosVersion.MODEL_4);
if (trsdos !== undefined) {
return trsdos;
}
trsdos = decodeTrsdosVersion(disk, TrsdosVersion.MODEL_3);
if (trsdos !== undefined) {
return trsdos;
}
return decodeTrsdosVersion(disk, TrsdosVersion.MODEL_1);
} | the_stack |
import { Selector, Agile, Collection, StateObserver, Item } from '../../../src';
import { LogMock } from '../../helper/logMock';
describe('Selector Tests', () => {
interface ItemInterface {
id: string;
name: string;
}
let dummyAgile: Agile;
let dummyCollection: Collection<ItemInterface>;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
dummyCollection = new Collection<ItemInterface>(dummyAgile);
jest.spyOn(Selector.prototype, 'select');
jest.clearAllMocks();
});
it('should create Selector and call initial select (default config)', () => {
// Overwrite select once to not call it
jest
.spyOn(Selector.prototype, 'select')
.mockReturnValueOnce(undefined as any);
const selector = new Selector(dummyCollection, 'dummyItemKey');
expect(selector.collection()).toBe(dummyCollection);
expect(selector._item).toBeNull(); // Because 'select()' is mocked
expect(selector._itemKey).toBe('dummyItemKey');
expect(selector.select).toHaveBeenCalledWith('dummyItemKey', {
overwrite: true,
});
// Check if State was called with correct parameters
expect(selector._key).toBeUndefined();
expect(selector.isSet).toBeFalsy();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.initialStateValue).toBeNull();
expect(selector._value).toBeNull();
expect(selector.previousStateValue).toBeNull();
expect(selector.nextStateValue).toBeNull();
expect(selector.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(selector.observers['value'].dependents)).toStrictEqual(
[]
);
expect(selector.observers['value'].key).toBeUndefined();
expect(selector.sideEffects).toStrictEqual({});
expect(selector.computeValueMethod).toBeUndefined();
expect(selector.computeExistsMethod).toBeInstanceOf(Function);
expect(selector.isPersisted).toBeFalsy();
expect(selector.persistent).toBeUndefined();
});
it('should create Selector and call initial select (specific config)', () => {
// Overwrite select once to not call it
jest
.spyOn(Selector.prototype, 'select')
.mockReturnValueOnce(undefined as any);
const selector = new Selector(dummyCollection, 'dummyItemKey', {
key: 'dummyKey',
});
expect(selector.collection()).toBe(dummyCollection);
expect(selector._item).toBeNull(); // Because 'select()' is mocked
expect(selector._itemKey).toBe('dummyItemKey');
expect(selector.select).toHaveBeenCalledWith('dummyItemKey', {
overwrite: true,
});
// Check if State was called with correct parameters
expect(selector._key).toBe('dummyKey');
expect(selector.isSet).toBeFalsy();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.initialStateValue).toBeNull();
expect(selector._value).toBeNull();
expect(selector.previousStateValue).toBeNull();
expect(selector.nextStateValue).toBeNull();
expect(selector.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(selector.observers['value'].dependents)).toStrictEqual(
[]
);
expect(selector.observers['value'].key).toBe('dummyKey');
expect(selector.sideEffects).toStrictEqual({});
expect(selector.computeValueMethod).toBeUndefined();
expect(selector.computeExistsMethod).toBeInstanceOf(Function);
expect(selector.isPersisted).toBeFalsy();
expect(selector.persistent).toBeUndefined();
});
it("should create Selector and shouldn't call initial select (config.isPlaceholder = true)", () => {
// Overwrite select once to not call it
jest
.spyOn(Selector.prototype, 'select')
.mockReturnValueOnce(undefined as any);
const selector = new Selector(dummyCollection, 'dummyItemKey', {
isPlaceholder: true,
});
expect(selector.collection()).toBe(dummyCollection);
expect(selector._item).toBeNull();
expect(selector._itemKey).toBeNull();
expect(selector.select).not.toHaveBeenCalled();
// Check if State was called with correct parameters
expect(selector._key).toBeUndefined();
expect(selector.isSet).toBeFalsy();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.initialStateValue).toBeNull();
expect(selector._value).toBeNull();
expect(selector.previousStateValue).toBeNull();
expect(selector.nextStateValue).toBeNull();
expect(selector.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(selector.observers['value'].dependents)).toStrictEqual(
[]
);
expect(selector.observers['value'].key).toBeUndefined();
expect(selector.sideEffects).toStrictEqual({});
expect(selector.computeValueMethod).toBeUndefined();
expect(selector.computeExistsMethod).toBeInstanceOf(Function);
expect(selector.isPersisted).toBeFalsy();
expect(selector.persistent).toBeUndefined();
});
it("should create Selector and shouldn't call initial select if specified selector key is null (default config)", () => {
// Overwrite select once to not call it
jest
.spyOn(Selector.prototype, 'select')
.mockReturnValueOnce(undefined as any);
const selector = new Selector(dummyCollection, null);
expect(selector.collection()).toBe(dummyCollection);
expect(selector._item).toBeNull();
expect(selector._itemKey).toBeNull();
expect(selector.select).not.toHaveBeenCalled();
// Check if State was called with correct parameters
expect(selector._key).toBeUndefined();
expect(selector.isSet).toBeFalsy();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.initialStateValue).toBeNull();
expect(selector._value).toBeNull();
expect(selector.previousStateValue).toBeNull();
expect(selector.nextStateValue).toBeNull();
expect(selector.observers['value']).toBeInstanceOf(StateObserver);
expect(Array.from(selector.observers['value'].dependents)).toStrictEqual(
[]
);
expect(selector.observers['value'].key).toBeUndefined();
expect(selector.sideEffects).toStrictEqual({});
expect(selector.computeValueMethod).toBeUndefined();
expect(selector.computeExistsMethod).toBeInstanceOf(Function);
expect(selector.isPersisted).toBeFalsy();
expect(selector.persistent).toBeUndefined();
});
describe('Selector Function Tests', () => {
let selector: Selector<ItemInterface>;
let dummyItem1: Item<ItemInterface>;
beforeEach(() => {
dummyItem1 = new Item(dummyCollection, {
id: 'dummyItem1',
name: 'Frank',
});
dummyCollection.data = {
dummyItem1: dummyItem1,
};
selector = new Selector<ItemInterface>(dummyCollection, 'dummyItem1');
});
describe('itemKey set function tests', () => {
it('should call the select() method with the passed value', () => {
selector.select = jest.fn();
selector._itemKey = null as any;
selector.itemKey = 'newItemKey';
expect(selector.select).toHaveBeenCalledWith('newItemKey');
expect(selector._itemKey).toBeNull();
});
});
describe('itemKey get function tests', () => {
it('should return the identifier of the Item currently selected by the Selector', () => {
selector._itemKey = 'coolItemKey';
expect(selector.itemKey).toBe('coolItemKey');
});
});
describe('item set function tests', () => {
it('should call the select() method with the Item identifier of the specified Item', () => {
selector.select = jest.fn();
selector._item = null as any;
dummyItem1._key = 'AReallyCoolKey';
selector.item = dummyItem1;
expect(selector.select).toHaveBeenCalledWith('AReallyCoolKey');
expect(selector._item).toBeNull();
});
});
describe('item get function tests', () => {
it('should return the currently selected Item of the Selector', () => {
selector._item = dummyItem1;
expect(selector.item).toBe(dummyItem1);
});
});
describe('select function tests', () => {
let dummyItem2: Item<ItemInterface>;
beforeEach(() => {
dummyItem2 = new Item(dummyCollection, {
id: 'dummyItem2',
name: 'Jeff',
});
dummyCollection.data['dummyItem2'] = dummyItem2;
selector.rebuildSelector = jest.fn();
selector.unselect = jest.fn();
dummyItem1.addSideEffect = jest.fn();
dummyItem2.addSideEffect = jest.fn();
selector.addSideEffect = jest.fn();
});
it('should unselect old selected Item and select new Item (default config)', () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
selector.select('dummyItem2');
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem2'
);
expect(selector._itemKey).toBe('dummyItem2');
expect(selector._item).toBe(dummyItem2);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: false,
overwrite: false,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem2.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(Array.from(dummyItem2.selectedBy)).toStrictEqual([
selector._key,
]);
});
it('should unselect old selected Item and select new Item (specific config)', () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
selector.select('dummyItem2', {
force: true,
sideEffects: {
enabled: false,
},
background: true,
overwrite: true,
});
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem2'
);
expect(selector._itemKey).toBe('dummyItem2');
expect(selector._item).toBe(dummyItem2);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: true,
sideEffects: {
enabled: false,
},
force: true,
overwrite: true,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem2.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(dummyItem2.selectedBy.size).toBe(1);
expect(dummyItem2.selectedBy.has(selector._key as any));
});
it("shouldn't select selected Item again (default config)", () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem1);
selector.select('dummyItem1');
expect(dummyCollection.getItemWithReference).not.toHaveBeenCalled();
expect(selector._itemKey).toBe('dummyItem1');
expect(selector._item).toBe(dummyItem1);
expect(selector.unselect).not.toHaveBeenCalled();
expect(selector.rebuildSelector).not.toHaveBeenCalled();
expect(selector.addSideEffect).not.toHaveBeenCalled();
expect(dummyItem1.addSideEffect).not.toHaveBeenCalled();
expect(Array.from(dummyItem1.selectedBy)).toStrictEqual([
selector._key,
]);
});
it('should select selected Item again (config.force = true)', () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem1);
selector.select('dummyItem1', { force: true });
expect(console.warn).not.toHaveBeenCalled();
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem1'
);
expect(selector._itemKey).toBe('dummyItem1');
expect(selector._item).toBe(dummyItem1);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: true,
overwrite: false,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem1.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(dummyItem1.selectedBy.size).toBe(1);
expect(dummyItem1.selectedBy.has(selector._key as any));
});
it("shouldn't select Item if Collection isn't instantiated (default config)", () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
dummyCollection.isInstantiated = false;
selector.select('dummyItem2');
expect(dummyCollection.getItemWithReference).not.toHaveBeenCalled();
expect(selector._itemKey).toBe('dummyItem1');
expect(selector._item).toBe(dummyItem1);
expect(selector.unselect).not.toHaveBeenCalled();
expect(selector.rebuildSelector).not.toHaveBeenCalled();
expect(selector.addSideEffect).not.toHaveBeenCalled();
expect(dummyItem2.addSideEffect).not.toHaveBeenCalled();
expect(Array.from(dummyItem2.selectedBy)).toStrictEqual([]);
});
it("should unselect old selected Item and select new Item although Collection isn't instantiated (config.force = true)", () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
dummyCollection.isInstantiated = false;
selector.select('dummyItem2', {
force: true,
});
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem2'
);
expect(selector._itemKey).toBe('dummyItem2');
expect(selector._item).toBe(dummyItem2);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: true,
overwrite: false,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem2.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(Array.from(dummyItem2.selectedBy)).toStrictEqual([
selector._key,
]);
});
it('should remove old selected Item, select new Item and overwrite Selector if old Item is placeholder (default config)', async () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
dummyItem1.isPlaceholder = true;
selector.select('dummyItem2');
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem2'
);
expect(selector._itemKey).toBe('dummyItem2');
expect(selector._item).toBe(dummyItem2);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: false,
overwrite: true,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem2.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(Array.from(dummyItem2.selectedBy)).toStrictEqual([
selector._key,
]);
});
it("should remove old selected Item, select new Item and shouldn't overwrite Selector if old Item is placeholder (config.overwrite = false)", async () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
dummyItem1.isPlaceholder = true;
selector.select('dummyItem2', { overwrite: false });
expect(dummyCollection.getItemWithReference).toHaveBeenCalledWith(
'dummyItem2'
);
expect(selector._itemKey).toBe('dummyItem2');
expect(selector._item).toBe(dummyItem2);
expect(selector.unselect).toHaveBeenCalledWith({ background: true });
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: false,
sideEffects: {
enabled: true,
exclude: [],
},
force: false,
overwrite: false,
storage: true,
});
expect(selector.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildItemSideEffectKey,
expect.any(Function),
{ weight: 90 }
);
expect(dummyItem2.addSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey,
expect.any(Function),
{ weight: 100 }
);
expect(Array.from(dummyItem2.selectedBy)).toStrictEqual([
selector._key,
]);
});
it("shouldn't select null and unselect old Item (default config)", () => {
dummyCollection.getItemWithReference = jest.fn(() => dummyItem2);
selector.select(null);
expect(dummyCollection.getItemWithReference).not.toHaveBeenCalled();
// expect(selector._itemKey).toBe(Selector.unknownItemPlaceholderKey); // Because 'unselect()' is mocked
// expect(selector._item).toBeNull(); // Because 'unselect()' is mocked
expect(selector.unselect).toHaveBeenCalledWith({ background: false });
expect(selector.rebuildSelector).not.toHaveBeenCalled();
expect(selector.addSideEffect).not.toHaveBeenCalled();
});
describe('test added sideEffect called Selector.rebuildSelectorSideEffectKey', () => {
beforeEach(() => {
selector.rebuildSelector = jest.fn();
});
it('should call rebuildSelector', () => {
selector.select('dummyItem1');
dummyItem1.sideEffects[
Selector.rebuildSelectorSideEffectKey
].callback(dummyItem1, {
dummy: 'property',
});
expect(selector.rebuildSelector).toHaveBeenCalledWith({
dummy: 'property',
});
});
});
describe('test added sideEffect called Selector.rebuildItemSideEffectKey', () => {
beforeEach(() => {
dummyItem1.set = jest.fn();
});
it('should call set on Item if Item is no placeholder', () => {
dummyItem1.isPlaceholder = false;
selector._value = { id: '1', name: 'jeff' };
selector.select('dummyItem1');
selector.sideEffects[Selector.rebuildItemSideEffectKey].callback(
selector,
{
dummy: 'property',
}
);
expect(dummyItem1.set).toHaveBeenCalledWith(
{ id: '1', name: 'jeff' },
{
dummy: 'property',
sideEffects: {
enabled: true,
exclude: [Selector.rebuildSelectorSideEffectKey],
},
}
);
});
it("shouldn't call set on Item if Item is on placeholder", () => {
dummyItem1.isPlaceholder = true;
selector.select('dummyItem1');
selector.sideEffects[Selector.rebuildItemSideEffectKey].callback(
selector,
{
dummy: 'property',
}
);
expect(dummyItem1.set).not.toHaveBeenCalled();
});
});
});
describe('reselect function tests', () => {
beforeEach(() => {
selector.select = jest.fn();
});
it("should reselect Item if Item isn't selected correctly (default config)", () => {
jest.spyOn(selector, 'hasSelected').mockReturnValueOnce(false);
selector.reselect();
expect(selector.select).toHaveBeenCalledWith(selector._itemKey, {});
});
it("should reselect Item if Item isn't selected correctly (specific config)", () => {
jest.spyOn(selector, 'hasSelected').mockReturnValueOnce(false);
selector.reselect({ force: true, background: true });
expect(selector.select).toHaveBeenCalledWith(selector._itemKey, {
force: true,
background: true,
});
});
it("shouldn't reselect Item if itemKey is not set", () => {
jest.spyOn(selector, 'hasSelected').mockReturnValueOnce(false);
selector._itemKey = null as any;
selector.reselect();
expect(selector.select).not.toHaveBeenCalled();
});
it("shouldn't reselect Item if Item is already selected correctly", () => {
jest.spyOn(selector, 'hasSelected').mockReturnValueOnce(true);
selector.reselect();
expect(selector.select).not.toHaveBeenCalled();
});
});
describe('unselect function tests', () => {
beforeEach(() => {
selector.rebuildSelector = jest.fn();
dummyItem1.removeSideEffect = jest.fn();
});
it("should unselect current selected Item and shouldn't remove it from Collection (default config)", () => {
selector.unselect();
expect(dummyItem1.selectedBy.size).toBe(0);
expect(dummyItem1.removeSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey
);
expect(selector._item).toBeNull();
expect(selector._itemKey).toBeNull();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.rebuildSelector).toHaveBeenCalledWith({});
expect(dummyCollection.data).toHaveProperty('dummyItem1');
});
it("should unselect current selected Item and shouldn't remove it from Collection (specific config)", () => {
selector.unselect({
background: true,
overwrite: true,
force: true,
});
expect(dummyItem1.selectedBy.size).toBe(0);
expect(dummyItem1.removeSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey
);
expect(selector._item).toBeNull();
expect(selector._itemKey).toBeNull();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.rebuildSelector).toHaveBeenCalledWith({
background: true,
overwrite: true,
force: true,
});
expect(dummyCollection.data).toHaveProperty('dummyItem1');
});
it('should unselect current selected placeholder Item and remove it from Collection (default config)', () => {
dummyItem1.isPlaceholder = true;
selector.unselect();
expect(dummyItem1.selectedBy.size).toBe(0);
expect(dummyItem1.removeSideEffect).toHaveBeenCalledWith(
Selector.rebuildSelectorSideEffectKey
);
expect(selector._item).toBeNull();
expect(selector._itemKey).toBeNull();
expect(selector.isPlaceholder).toBeTruthy();
expect(selector.rebuildSelector).toHaveBeenCalledWith({});
expect(dummyCollection.data).not.toHaveProperty('dummyItem1');
});
});
describe('hasSelected function tests', () => {
beforeEach(() => {
selector._itemKey = 'dummyItemKey';
});
it('should return true if Selector has selected itemKey correctly and Item isSelected', () => {
if (selector._item) selector._item.selectedBy.add(selector._key as any);
expect(selector.hasSelected('dummyItemKey')).toBeTruthy();
});
it("should return false if Selector hasn't selected itemKey correctly (itemKey = undefined)", () => {
expect(selector.hasSelected('notSelectedItemKey')).toBeFalsy();
});
it("should return false if Selector hasn't selected itemKey correctly (itemKey = undefined, correctlySelected = false)", () => {
expect(selector.hasSelected('notSelectedItemKey', false)).toBeFalsy();
});
it("should return false if Selector hasn't selected itemKey correctly (item = undefined)", () => {
selector._item = null;
expect(selector.hasSelected('dummyItemKey')).toBeFalsy();
});
it("should return true if Selector hasn't selected itemKey correctly (item = undefined, correctlySelected = false)", () => {
selector._item = null;
expect(selector.hasSelected('dummyItemKey', false)).toBeTruthy();
});
it("should return false if Selector has selected itemKey correctly and Item isn't isSelected", () => {
if (selector._item) selector._item.selectedBy = new Set();
expect(selector.hasSelected('dummyItemKey')).toBeFalsy();
});
it("should return true if Selector has selected itemKey correctly and Item isn't isSelected (correctlySelected = false)", () => {
if (selector._item) selector._item.selectedBy = new Set();
expect(selector.hasSelected('dummyItemKey', false)).toBeTruthy();
});
});
describe('rebuildSelector function tests', () => {
beforeEach(() => {
selector.set = jest.fn();
});
it('should set selector value to item value (default config)', () => {
selector._item = dummyItem1;
selector.rebuildSelector();
expect(selector.set).toHaveBeenCalledWith(selector._item._value, {});
});
it('should set selector value to item value (specific config)', () => {
selector._item = dummyItem1;
selector.rebuildSelector({
sideEffects: {
enabled: false,
},
background: true,
force: true,
});
expect(selector.set).toHaveBeenCalledWith(selector._item._value, {
sideEffects: {
enabled: false,
},
background: true,
force: true,
});
});
it('should set selector value to undefined if Item is undefined (default config)', () => {
selector._item = null;
selector.rebuildSelector();
expect(selector.set).toHaveBeenCalledWith(null, {});
});
});
});
}); | the_stack |
import { Component, OnInit, ElementRef, HostListener, OnDestroy, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { Subject } from 'rxjs/Subject';
import { Title } from '@angular/platform-browser';
import { global, authPayload, StorageService } from '../../services/common';
import { AppStore } from '../../app.store';
import { chatAction } from './actions';
import { mainAction } from '../main/actions';
import { roomAction } from '../room/actions';
import { Util } from '../../services/util';
import { contactAction } from '../contact/actions';
import * as Push from 'push.js';
@Component({
selector: 'chat-component',
styleUrls: ['./chat.component.scss'],
templateUrl: './chat.component.html'
})
export class ChatComponent implements OnInit, OnDestroy {
@Input()
private hideAll;
private isLoadedSubject$ = new Subject();
private isLoaded$ = this.isLoadedSubject$.asObservable();
private isLoaded = false;
private chatStream$;
private conversationList = [];
private messageList = [
{
key: 0,
msgs: [],
groupSetting: {
groupInfo: {},
memberList: []
}
}
];
private global = global;
private active = {
// 当前active的用户
name: '',
nickName: '',
key: '',
activeIndex: -1,
type: 0,
change: false,
shield: false,
appkey: ''
};
private defaultPanelIsShow = true;
private otherInfo = {
show: false,
info: {
name: '',
appkey: '',
avatarUrl: '',
nickName: ''
}
};
private blackMenu = {
show: false,
menu: []
};
private groupSetting = {
groupInfo: {
name: '',
desc: '',
gid: 0
},
memberList: [],
active: {},
show: false
};
private msgKey = 1;
private groupDescription = {
show: false,
description: {}
};
private selfInfo: any = {};
private isCacheArr = [];
private playVideoShow = {
show: false,
url: ''
};
private eventArr = [];
private hasOffline = 0;
// 其他操作触发滚动条到底部
private otherOptionScrollBottom = false;
// 切换用户触发滚动条到底部
private changeActiveScrollBottom = false;
private windowIsFocus = true;
private newMessageNotice = {
timer: null,
num: 0
};
private messageTransmit = {
list: [],
show: false,
type: ''
};
private transmitAllMsg = {
content: {
msg_type: '',
from_id: '',
target_id: ''
},
msgKey: -1,
totalTransmitNum: 0,
ctime_ms: 0,
conversation_time_show: '',
time_show: '',
hasLoad: false,
showMoreIcon: false,
type: 0,
key: 0,
isTransmitMsg: true,
msg_id: 0,
unread_count: 0,
msg_type: 0,
success: 1
};
private verifyModal = {
info: {},
show: false
};
private changeOtherInfoFlag = false;
private sendBusinessCardCount = 0;
private groupAvatar = {
info: {
src: '',
width: 0,
height: 0,
pasteFile: {}
},
show: false,
formData: {},
src: '',
filename: '',
title: '群组头像'
};
private unreadList = {
show: false,
info: {
read: [],
unread: []
},
loading: false
};
private isMySelf = false;
private noLoadedMessage = [];
private inputMessage = '';
private inputMessageTimer = null;
constructor(
private store$: Store<AppStore>,
private storageService: StorageService,
private elementRef: ElementRef,
private titleService: Title
) { }
public ngOnInit() {
this.store$.dispatch({
type: chatAction.init,
payload: null
});
this.hasOffline = 0;
this.subscribeStore();
this.store$.dispatch({
type: chatAction.getVoiceState,
payload: `voiceState-${authPayload.appkey}-${global.user}`
});
global.JIM.onMsgReceive((data) => {
if (!this.isLoaded) {
this.noLoadedMessage.push(data);
return;
}
this.receiveNewMessage(data);
});
// 异常断线监听
global.JIM.onDisconnect(() => {
// 定时器是为了解决火狐下刷新时先弹出断线提示
setTimeout(() => {
this.store$.dispatch({
type: mainAction.logoutKickShow,
payload: {
show: true,
info: {
title: '提示',
tip: '网络断线,请检查网络或重新登陆'
}
}
});
}, 2000);
});
// 监听在线事件消息
global.JIM.onEventNotification((data) => {
data.isOffline = false;
if (!this.isLoaded) {
this.eventArr.push(data);
} else {
this.asyncEvent(data);
}
});
// 监听离线事件消息
global.JIM.onSyncEvent((data) => {
if (!this.isLoaded) {
this.eventArr = data;
} else {
for (let item of data) {
item.isOffline = true;
this.asyncEvent(item);
}
}
});
// 多端在线清空会话未读数
global.JIM.onMutiUnreadMsgUpdate((data) => {
if (data.username) {
data.name = data.username;
}
this.store$.dispatch({
type: chatAction.emptyUnreadNumSyncEvent,
payload: data
});
});
// 离线业务消息监听,加载完会话数据之后才执行
this.isLoaded$.subscribe((isLoaded) => {
if (isLoaded) {
for (let message of this.noLoadedMessage) {
this.receiveNewMessage(message);
}
this.noLoadedMessage = [];
for (let item of this.eventArr) {
item.isOffline = true;
this.asyncEvent(item);
}
this.eventArr = [];
}
});
// 离线消息同步监听
global.JIM.onSyncConversation((data) => {
// 限制只触发一次
if (this.hasOffline === 0) {
this.hasOffline++;
this.store$.dispatch({
type: chatAction.getAllMessage,
payload: data
});
}
});
// 如果4秒内没有加载离线消息则手动触发
setTimeout(() => {
if (this.hasOffline === 0) {
this.store$.dispatch({
type: chatAction.getAllMessage,
payload: []
});
}
}, 4000);
// 监听已读回执
global.JIM.onMsgReceiptChange((data) => {
this.store$.dispatch({
type: chatAction.msgReceiptChangeEvent,
payload: data
});
});
// 监听同步的已读回执,用作补偿
global.JIM.onSyncMsgReceipt((data) => {
this.store$.dispatch({
type: chatAction.msgReceiptChangeEvent,
payload: data
});
});
// 监听用户的信息变化,只有用户信息变化且发了消息的才会触发
global.JIM.onUserInfUpdate((data) => {
this.store$.dispatch({
type: chatAction.userInfUpdateEvent,
payload: data
});
});
// 消息透传(正在输入)
global.JIM.onTransMsgRec((data) => {
if (data.from_username === this.active.name) {
this.inputMessage = data.cmd;
clearTimeout(this.inputMessageTimer);
// 6s内没有新的透传消息,则清除正在输入
this.inputMessageTimer = setTimeout(() => {
this.store$.dispatch({
type: chatAction.receiveInputMessage,
payload: false
});
}, 6000);
this.store$.dispatch({
type: chatAction.receiveInputMessage,
payload: true
});
}
});
}
public ngOnDestroy() {
this.chatStream$.unsubscribe();
this.isLoadedSubject$.unsubscribe();
}
@HostListener('window:blur') private onBlurWindow() {
this.windowIsFocus = false;
}
@HostListener('window:focus') private onFocusWindow() {
this.windowIsFocus = true;
this.newMessageNotice.num = 0;
}
// 切换标签页事件
@HostListener('document:visibilitychange') private onChangeWindow() {
const hiddenProperty = 'hidden' in document ? 'hidden' :
'webkitHidden' in document ? 'webkitHidden' :
'mozHidden' in document ? 'mozHidden' : null;
if (!document[hiddenProperty]) {
this.windowIsFocus = true;
this.newMessageNotice.num = 0;
} else {
this.windowIsFocus = false;
}
}
private subscribeStore() {
this.chatStream$ = this.store$.select((state) => {
const chatState = state['chatReducer'];
const mainState = state['mainReducer'];
this.stateChanged(chatState, mainState);
return state;
}).subscribe((state) => {
// pass
});
}
private stateChanged(chatState, mainState) {
const activeIndex = chatState.activePerson.activeIndex;
const messageListActive = chatState.messageList[activeIndex];
switch (chatState.actionType) {
case chatAction.init:
this.init();
break;
case chatAction.getFriendListSuccess:
this.conversationList = chatState.conversation;
this.dispatchFriendList(chatState);
if (chatState.activePerson.activeIndex > 0) {
this.active = chatState.activePerson;
}
break;
case chatAction.getConversationSuccess:
this.conversationList = chatState.conversation;
this.messageList = chatState.messageList;
this.dispatchConversationUnreadNum(chatState);
if (chatState.isLoaded) {
this.isLoaded = chatState.isLoaded;
this.isLoadedSubject$.next(this.isLoaded);
}
break;
case chatAction.receiveMessageSuccess:
if (chatState.newMessageIsActive) {
this.emptyUnreadCount(chatState.unreadCount);
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
this.messageList = chatState.messageList;
if (!chatState.newMessageIsDisturb && !this.isMySelf) {
this.notification(chatState.newMessage);
this.dispatchConversationUnreadNum(chatState);
}
break;
case chatAction.sendSingleMessage:
case chatAction.sendGroupMessage:
case chatAction.sendSinglePic:
case chatAction.sendGroupPic:
case chatAction.sendSingleFile:
case chatAction.sendGroupFile:
// 触发滚动条向下滚动
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
break;
case chatAction.updateGroupInfoEventSuccess:
if (activeIndex >= 0 && messageListActive && messageListActive.groupSetting) {
this.groupSetting = Object.assign({},
this.groupSetting, messageListActive.groupSetting);
this.groupSetting.active = this.active;
}
this.dispatchGroupList(chatState);
// 触发滚动条向下滚动
if (chatState.newMessageIsActive) {
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
break;
case chatAction.sendMsgComplete:
this.modalTipSendCardSuccess(chatState);
break;
case chatAction.changeActivePerson:
case contactAction.selectContactItem:
case mainAction.selectSearchUser:
this.messageList = chatState.messageList;
this.changeActivePerson(chatState);
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.emptyUnreadCount(chatState.unreadCount);
this.dispatchConversationUnreadNum(chatState);
break;
case chatAction.addReceiptReportAction:
if (chatState.readObj && chatState.readObj.msg_id.length > 0) {
this.store$.dispatch({
type: chatAction.addReceiptReport,
payload: chatState.readObj
});
}
break;
case chatAction.saveDraft:
this.messageList = chatState.messageList;
this.conversationList = chatState.conversation;
break;
case mainAction.searchUserSuccess:
this.store$.dispatch({
type: chatAction.searchUserSuccess,
payload: chatState.searchUserResult
});
break;
case chatAction.deleteConversationItem:
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.closeGroupSettingEmit();
this.dispatchFriendList(chatState);
this.active = chatState.activePerson;
this.dispatchConversationUnreadNum(chatState);
break;
case chatAction.watchOtherInfoSuccess:
case chatAction.hideOtherInfo:
case mainAction.createSingleChatSuccess:
case contactAction.watchVerifyUserSuccess:
this.otherInfo = chatState.otherInfo;
break;
case chatAction.groupSetting:
if (activeIndex < 0) {
this.groupSetting.show = false;
}
case chatAction.groupInfo:
if (activeIndex >= 0 && messageListActive && messageListActive.groupSetting) {
this.groupSetting = Object.assign({},
this.groupSetting, messageListActive.groupSetting);
this.groupSetting.active = this.active;
}
break;
case mainAction.createGroupSuccess:
this.messageList = chatState.messageList;
this.changeActivePerson(chatState);
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.dispatchGroupList(chatState);
break;
case chatAction.createOtherChat:
this.messageList = chatState.messageList;
this.changeActivePerson(chatState);
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.emptyUnreadCount(chatState.unreadCount);
this.unreadList.show = false;
this.closeGroupSettingEmit();
this.dispatchConversationUnreadNum(chatState);
break;
case mainAction.exitGroupSuccess:
this.conversationList = chatState.conversation;
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.closeGroupSettingEmit();
this.active = chatState.activePerson;
this.dispatchGroupList(chatState);
this.dispatchConversationUnreadNum(chatState);
break;
case mainAction.addBlackListSuccess:
this.conversationList = chatState.conversation;
this.otherInfo = chatState.otherInfo;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
break;
case chatAction.groupDescription:
this.groupDescription.show = chatState.groupDeacriptionShow;
this.groupDescription.description =
Util.deepCopyObj(messageListActive.groupSetting.groupInfo);
break;
case mainAction.showSelfInfo:
if (mainState.selfInfo.info) {
this.selfInfo = mainState.selfInfo.info;
}
break;
case mainAction.addGroupMemberSuccess:
this.groupSetting.memberList = messageListActive.groupSetting.memberList;
break;
case chatAction.changeGroupShieldSuccess:
this.conversationList = chatState.conversation;
this.active.shield = chatState.activePerson.shield;
break;
case chatAction.playVideoShow:
this.playVideoShow = chatState.playVideoShow;
break;
// 群聊事件
case chatAction.addGroupMembersEventSuccess:
if (activeIndex >= 0 && messageListActive && messageListActive.groupSetting) {
this.groupSetting = Object.assign({},
this.groupSetting, messageListActive.groupSetting);
}
if (chatState.currentIsActive) {
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
this.dispatchGroupList(chatState);
break;
case chatAction.deleteGroupMembersEvent:
this.dispatchGroupList(chatState);
if (activeIndex >= 0 && messageListActive && messageListActive.groupSetting) {
this.groupSetting = Object.assign({},
this.groupSetting, messageListActive.groupSetting);
}
if (chatState.currentIsActive) {
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
break;
case chatAction.updateGroupMembersEvent:
case chatAction.exitGroupEvent:
if (activeIndex >= 0 && messageListActive && messageListActive.groupSetting) {
this.groupSetting = Object.assign({},
this.groupSetting, messageListActive.groupSetting);
}
if (chatState.currentIsActive) {
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
break;
case chatAction.createGroupSuccessEvent:
this.conversationList = chatState.conversation;
this.dispatchGroupList(chatState);
break;
case chatAction.msgRetractEvent:
this.conversationList = chatState.conversation;
this.messageList = chatState.messageList;
break;
// 转发单聊文本消息
case chatAction.transmitSingleMessage:
// 转发单聊图片消息
case chatAction.transmitSinglePic:
// 转发单聊文件消息
case chatAction.transmitSingleFile:
// 转发群聊文本消息
case chatAction.transmitGroupMessage:
// 转发单聊图片消息
case chatAction.transmitGroupPic:
// 转发单聊文件消息
case chatAction.transmitGroupFile:
// 转发单聊位置
case chatAction.transmitSingleLocation:
// 转发群聊位置
case chatAction.transmitGroupLocation:
this.conversationList = chatState.conversation;
break;
case chatAction.emptyUnreadNumSyncEvent:
this.conversationList = chatState.conversation;
this.dispatchConversationUnreadNum(chatState);
break;
// 转发消息成功(如果全部成功则为成功,有一个用户失败则不成功,会提示相关信息)
case chatAction.transmitMessageComplete:
this.modalTipTransmitSuccess(chatState);
break;
case contactAction.agreeAddFriendSuccess:
this.conversationList = chatState.conversation;
this.dispatchFriendList(chatState);
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
break;
case chatAction.friendReplyEventSuccess:
this.otherInfo = chatState.otherInfo;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
this.dispatchFriendList(chatState);
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
break;
case chatAction.showVerifyModal:
this.verifyModal = chatState.verifyModal;
break;
case chatAction.deleteSingleBlackSuccess:
this.otherInfo = chatState.otherInfo;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
break;
case chatAction.changeGroupNoDisturbSuccess:
this.dispatchConversationUnreadNum(chatState);
break;
case mainAction.addSingleNoDisturbSuccess:
case chatAction.deleteSingleNoDisturbSuccess:
this.dispatchConversationUnreadNum(chatState);
this.otherInfo = chatState.otherInfo;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
break;
case chatAction.saveMemoNameSuccess:
case chatAction.deleteFriendSyncEvent:
case chatAction.addFriendSyncEvent:
this.conversationList = chatState.conversation;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
this.dispatchFriendList(chatState);
break;
case chatAction.userInfUpdateEventSuccess:
this.dispatchFriendList(chatState);
this.otherInfo.info = chatState.otherInfo.info;
break;
case mainAction.deleteFriendSuccess:
this.dispatchFriendList(chatState);
this.otherInfo = chatState.otherInfo;
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
this.conversationList = chatState.conversation;
this.defaultPanelIsShow = chatState.defaultPanelIsShow;
this.unreadList.show = false;
break;
case chatAction.addSingleBlackSyncEvent:
case chatAction.deleteSingleBlackSyncEvent:
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
break;
case chatAction.addSingleNoDisturbSyncEvent:
case chatAction.deleteSingleNoDisturbSyncEvent:
case chatAction.addGroupNoDisturbSyncEvent:
case chatAction.deleteGroupNoDisturbSyncEvent:
this.dispatchConversationUnreadNum(chatState);
this.changeOtherInfoFlag = !this.changeOtherInfoFlag;
break;
case chatAction.conversationToTopSuccess:
this.conversationList = chatState.conversation;
break;
case chatAction.watchUnreadList:
this.unreadList = chatState.unreadList;
break;
case chatAction.watchUnreadListSuccess:
this.unreadList = chatState.unreadList;
break;
case chatAction.msgReceiptChangeEvent:
this.conversationList = chatState.conversation;
break;
case mainAction.dispatchSendSelfCard:
this.sendCardEmit();
break;
case contactAction.getGroupListSuccess:
this.dispatchGroupList(chatState);
break;
case roomAction.transmitAllMsg:
this.msgTransmitEmit(chatState.roomTransmitMsg);
break;
case chatAction.receiveGroupInvitationEventSuccess:
this.store$.dispatch({
type: chatAction.dispatchReceiveGroupInvitationEvent,
payload: chatState.receiveGroupInvitationEventObj
});
this.notification(chatState.receiveGroupInvitationEventObj);
break;
case chatAction.receiveGroupRefuseEventSuccess:
this.store$.dispatch({
type: chatAction.dispatchReceiveGroupRefuseEvent,
payload: chatState.receiveGroupRefuseEventObj
});
this.notification(chatState.receiveGroupRefuseEventObj);
break;
case chatAction.addGroupMemberSilenceEvent:
if (chatState.currentIsActive) {
// 触发滚动条向下滚动
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
break;
case chatAction.deleteGroupMemberSilenceEvent:
if (chatState.currentIsActive) {
// 触发滚动条向下滚动
this.otherOptionScrollBottom = !this.otherOptionScrollBottom;
}
break;
default:
}
}
// 传递会话列表总未读数
private dispatchConversationUnreadNum(chatState) {
this.store$.dispatch({
type: chatAction.dispatchConversationUnreadNum,
payload: chatState.conversationUnreadNum
});
}
// 传递群组列表
private dispatchGroupList(chatState) {
this.store$.dispatch({
type: chatAction.dispatchGroupList,
payload: chatState.groupList
});
}
// 传递好友列表
private dispatchFriendList(chatState) {
this.store$.dispatch({
type: chatAction.dispatchFriendList,
payload: chatState.friendList
});
}
// 清空未读数
private emptyUnreadCount(unread) {
if (unread.type === 3 || unread.type === 4) {
this.store$.dispatch({
type: chatAction.emptyUnreadNum,
payload: unread
});
}
}
// 收到新消息
private receiveNewMessage(data) {
// 与用户名是feedback_开头的消息不做处理
const feedbackReg = /^feedback_/g;
if (data.messages[0].content.target_id.match(feedbackReg)) {
return;
}
if (data.messages[0].content.from_id === global.user) {
this.isMySelf = true;
this.store$.dispatch({
type: chatAction.syncReceiveMessage,
payload: {
data
}
});
return;
} else {
this.isMySelf = false;
}
// 群聊消息
if (data.messages[0].msg_type === 4) {
this.store$.dispatch({
type: chatAction.receiveGroupMessage,
payload: {
data,
conversation: this.conversationList,
messageList: this.messageList
}
});
// 单聊消息
} else {
this.store$.dispatch({
type: chatAction.receiveInputMessage,
payload: false
});
this.store$.dispatch({
type: chatAction.receiveSingleMessage,
payload: {
data,
conversation: this.conversationList
}
});
}
}
// 发送名片成功的提示
private modalTipSendCardSuccess(chatState) {
const count = this.sendBusinessCardCount;
if (count !== 0 && count === chatState.sendBusinessCardSuccess) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
title: '成功', // 模态框标题
tip: '发送名片成功', // 模态框内容
actionType: '[main] send business card success', // 哪种操作,点击确定时可以执行对应操作
success: 1 // 成功的提示框/失败的提示框,1.5s后会自动消失
}
}
});
}
this.sendBusinessCardCount = 0;
this.store$.dispatch({
type: chatAction.hideOtherInfo,
payload: {
show: false,
info: {}
}
});
this.store$.dispatch({
type: mainAction.showSelfInfo,
payload: {
show: false,
loading: false
}
});
}
// 转发消息成功的提示
private modalTipTransmitSuccess(chatState) {
const count = this.transmitAllMsg.totalTransmitNum;
if (count !== 0 && chatState.transmitSuccess === count) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
title: '成功', // 模态框标题
tip: '转发成功', // 模态框内容
actionType: '[main] transmit success', // 哪种操作,点击确定时可以执行对应操作
success: 1 // 成功的提示框/失败的提示框,1.5s后会自动消失
}
}
});
this.transmitAllMsg.totalTransmitNum = 0;
}
if (chatState.transmitSuccess === 0) {
this.transmitAllMsg.totalTransmitNum = 0;
}
}
// 事件消息
private asyncEvent(data) {
switch (data.event_type) {
// 账号在其他地方登陆web jchat
case 1:
this.store$.dispatch({
type: mainAction.logoutKickShow,
payload: {
show: true,
info: {
title: '提示',
tip: '您的账号在其他设备登录'
}
}
});
break;
// 密码被其他设备修改的同步事件
case 2:
this.store$.dispatch({
type: mainAction.logoutKickShow,
payload: {
show: true,
info: {
title: '提示',
tip: '您的密码已在其他设备修改,请重新登录',
hideRepeateLoginBtn: true
}
}
});
break;
case 5:
// 好友请求和应答事件
this.store$.dispatch({
type: chatAction.friendEvent,
payload: data
});
this.notification(data);
break;
case 6:
// 删除好友同步消息
if (!data.isOffline) {
if (data.extra === 0) {
this.store$.dispatch({
type: chatAction.getFriendList,
payload: null
});
}
}
break;
case 7:
// 非客户端修改好友关系事件
if (!data.isOffline) {
if (data.extra === 0) {
this.store$.dispatch({
type: chatAction.getFriendList,
payload: 'api'
});
}
}
break;
case 8:
// 创建群的事件
if (data.from_username === '' && !data.isOffline) {
this.store$.dispatch({
type: chatAction.createGroupEvent,
payload: data
});
}
break;
case 9:
// 退群事件
if (data.to_usernames[0].username !== global.user) {
this.store$.dispatch({
type: chatAction.exitGroupEvent,
payload: data
});
} else {
this.store$.dispatch({
type: mainAction.exitGroupSuccess,
payload: {
item: {
type: 4,
name: data.group_name,
key: data.gid
}
}
});
}
break;
case 10:
// 添加群成员事件
if (data.extra === 0 || data.extra === 1 || data.extra === 2) {
this.store$.dispatch({
type: chatAction.addGroupMembersEvent,
payload: data
});
}
break;
case 11:
// 删除群成员事件
if (data.extra === 0) {
this.store$.dispatch({
type: chatAction.deleteGroupMembersEvent,
payload: data
});
}
break;
case 12:
// 更新群信息事件
if (!data.isOffline) {
this.store$.dispatch({
type: chatAction.updateGroupInfoEvent,
payload: data
});
}
break;
case 40:
// 个人信息更新同步事件
if (!data.isOffline) {
if (data.extra === 0) {
this.store$.dispatch({
type: mainAction.getSelfInfo,
payload: null
});
}
}
case 55:
// 消息撤回事件,不考虑离线的消息撤回事件
if (!data.isOffline) {
this.store$.dispatch({
type: chatAction.msgRetractEvent,
payload: data
});
}
break;
// 群主或者管理员收到用户申请入群事件
case 56:
this.store$.dispatch({
type: chatAction.receiveGroupInvitationEvent,
payload: data
});
break;
// 被拒绝入群
case 57:
this.store$.dispatch({
type: chatAction.receiveGroupRefuseEvent,
payload: data
});
break;
case 65:
if (!data.isOffline) {
// 禁言事件
if (data.extra === 1) {
this.store$.dispatch({
type: chatAction.addGroupMemberSilenceEvent,
payload: data
});
// 取消禁言事件
} else if (data.extra === 2) {
this.store$.dispatch({
type: chatAction.deleteGroupMemberSilenceEvent,
payload: data
});
}
}
case 100:
// 好友列表更新同步事件
if (!data.isOffline) {
this.updateFriendListSyncEvent(data);
}
break;
case 101:
// 添加黑名单同步事件
if (!data.isOffline) {
if (data.extra === 1) {
this.store$.dispatch({
type: chatAction.addSingleBlackSyncEvent,
payload: data
});
this.store$.dispatch({
type: mainAction.blackMenu,
payload: {
show: null
}
});
} else if (data.extra === 2) {
this.store$.dispatch({
type: chatAction.deleteSingleBlackSyncEvent,
payload: data
});
this.store$.dispatch({
type: mainAction.blackMenu,
payload: {
show: null
}
});
}
}
break;
case 102:
// 免打扰同步事件
if (!data.isOffline) {
this.updateNoDisturbSyncEvent(data);
}
break;
case 103:
// 屏蔽群消息的同步事件
if (!data.isOffline) {
if (data.extra === 1) {
this.store$.dispatch({
type: chatAction.addGroupShieldSyncEvent,
payload: data
});
} else if (data.extra === 2) {
this.store$.dispatch({
type: chatAction.deleteGroupShieldSyncEvent,
payload: data
});
}
}
break;
default:
}
}
// 更新好友列表同步事件
private updateFriendListSyncEvent(data) {
if (data.extra === 5) {
this.store$.dispatch({
type: chatAction.getFriendList,
payload: null
});
this.store$.dispatch({
type: chatAction.addFriendSyncEvent,
payload: data
});
} else if (data.extra === 6) {
this.store$.dispatch({
type: chatAction.getFriendList,
payload: null
});
this.store$.dispatch({
type: chatAction.deleteFriendSyncEvent,
payload: data
});
} else if (data.extra === 7) {
this.store$.dispatch({
type: chatAction.saveMemoNameSuccess,
payload: data
});
}
}
// 更新免打扰同步事件
private updateNoDisturbSyncEvent(data) {
switch (data.extra) {
case 31:
this.store$.dispatch({
type: chatAction.addSingleNoDisturbSyncEvent,
payload: data
});
break;
case 32:
this.store$.dispatch({
type: chatAction.deleteSingleNoDisturbSyncEvent,
payload: data
});
break;
case 33:
this.store$.dispatch({
type: chatAction.addGroupNoDisturbSyncEvent,
payload: data
});
break;
case 34:
this.store$.dispatch({
type: chatAction.deleteGroupNoDisturbSyncEvent,
payload: data
});
break;
default:
}
}
// 通知栏
private notification(newMessage) {
if (!this.windowIsFocus) {
let title = '';
let body = '';
// 好友验证消息
if (newMessage.event_type === 5) {
if (newMessage.extra === 1) {
title = '好友邀请';
body = `${newMessage.from_nickname || newMessage.from_username}申请添加您为好友`;
} else if (newMessage.extra === 2) {
if (newMessage.return_code === 0) {
title = '同意好友申请';
body = `${newMessage.from_nickname || newMessage.from_username}同意了您的好友申请`;
} else {
title = '拒绝好友申请';
body = `${newMessage.from_nickname || newMessage.from_username}拒绝了您的好友申请`;
}
}
// 入群申请消息
} else if (newMessage.event_type === 56) {
title = '入群申请';
if (newMessage.by_self) {
body = `${newMessage.from_memo_name || newMessage.from_nickname ||
newMessage.from_username} 申请入群 ${newMessage.group_name}`;
} else {
let name = '';
for (let i = 0; i < newMessage.to_usernames.length; i++) {
name += newMessage.to_usernames[i].memo_name ||
newMessage.to_usernames[i].nickname ||
newMessage.to_usernames[i].username;
if (i >= 5) {
name += '等人';
break;
} else if (i !== newMessage.to_usernames.length - 1) {
name += '、';
}
}
body = `${newMessage.from_memo_name || newMessage.from_nickname ||
newMessage.from_username} 邀请 ${name} 入群 ${newMessage.group_name}`;
}
// 被拒绝入群消息
} else if (newMessage.event_type === 57) {
let name = newMessage.to_usernames[0].username === global.user ?
'您' : (newMessage.to_usernames[0].memo_name ||
newMessage.to_usernames[0].nickname ||
newMessage.to_usernames[0].username);
title = '拒绝入群申请';
body = `群组 ${newMessage.group_name} 拒绝了 ${name} 的入群申请`;
// 普通消息
} else {
if (newMessage.msg_type === 4) {
title = newMessage.content.target_name || '群';
body += `${newMessage.content.memo_name ||
newMessage.content.from_name || newMessage.content.from_id}:`;
} else {
title = newMessage.content.memo_name ||
newMessage.content.from_name || newMessage.content.from_id || ' ';
}
switch (newMessage.content.msg_type) {
case 'text':
body += newMessage.content.msg_body.text;
break;
case 'image':
body += '[图片]';
break;
case 'location':
body += '[位置]';
break;
case 'voice':
body += '[语音]';
break;
case 'file':
let extras = newMessage.content.msg_body.extras;
if (extras && extras.video) {
body += '[视频]';
} else {
body += '[文件]';
}
break;
default:
body += '消息';
}
}
Push.create(title, {
body,
icon: '../../../assets/images/notification-icon.png',
timeout: 4000,
onClick() {
window.focus();
this.close();
}
});
this.newMessageNotice.num++;
clearInterval(this.newMessageNotice.timer);
this.newMessageNotice.timer = setInterval(() => {
if (this.titleService.getTitle() === 'JChat - 极光 IM Demo') {
this.titleService.setTitle(`jchat(${this.newMessageNotice.num})`);
} else {
this.titleService.setTitle('JChat - 极光 IM Demo');
}
if (this.newMessageNotice.num === 0) {
clearInterval(this.newMessageNotice.timer);
this.titleService.setTitle('JChat - 极光 IM Demo');
}
}, 1000);
}
}
// 更新当前对话用户信息
private changeActivePerson(chatState) {
this.inputMessage = '';
this.store$.dispatch({
type: chatAction.receiveInputMessage,
payload: false
});
this.closeGroupSettingEmit();
this.active = chatState.activePerson;
this.emptyUnreadCount(this.active);
this.changeActiveScrollBottom = !this.changeActiveScrollBottom;
// 判断是否已经缓存
if (this.isCacheArr.indexOf(this.active.key) === -1) {
this.isCacheArr.push(this.active.key);
this.store$.dispatch({
type: chatAction.getSourceUrl,
payload: {
active: this.active,
messageList: this.messageList,
loadingCount: 1 // 加载的页数
}
});
if (this.active.type === 4) {
this.store$.dispatch({
type: chatAction.getGroupMembers,
payload: this.active
});
// 获取messageList avatar url
this.store$.dispatch({
type: chatAction.getMemberAvatarUrl,
payload: {
active: this.active,
messageList: this.messageList,
loadingCount: 1 // 加载的页数
}
});
} else {
this.store$.dispatch({
type: chatAction.getSingleAvatarUrl,
payload: null
});
}
}
}
// 切换当前对话用户
private selectTargetEmit(item) {
const group = item.type === 4 && this.active.type === 4 &&
Number(this.active.key) === Number(item.key);
const single = item.type === 3 && this.active.type === 3 && this.active.name === item.name;
if (group || single) {
return;
}
this.store$.dispatch({
type: chatAction.changeActivePerson,
payload: {
item,
defaultPanelIsShow: false
}
});
}
// 滚动加载消息列表
private loadMoreEmit(num) {
// num.loadingCount 滚动加载第几页的页数
if (this.active.activeIndex < 0) {
return;
}
this.store$.dispatch({
type: chatAction.getSourceUrl,
payload: {
active: this.active,
messageList: this.messageList,
loadingCount: num.loadingCount
}
});
if (this.active.type === 4) {
this.store$.dispatch({
type: chatAction.getMemberAvatarUrl,
payload: {
active: this.active,
messageList: this.messageList,
loadingCount: num.loadingCount
}
});
}
}
// 删除本地会话列表
private deleteConversationItemEmit(item) {
this.store$.dispatch({
type: chatAction.deleteConversationItem,
payload: {
item
}
});
}
// 发送文本消息
private sendMsgEmit(data, active?) {
let activePerson = active || this.active;
// repeatSend = true重发消息
/**
* success
* 取值 状态
* 1 正在发送
* 2 发送成功
* 3 发送失败
*/
let msgs: any = {
content: {
msg_type: 'text',
from_id: global.user,
msg_body: {
text: data.content,
extras: data.localExtras
}
},
ctime_ms: new Date().getTime(),
success: 1,
msgKey: this.msgKey++,
unread_count: 0
};
// 转发消息失败重发单聊消息
if (activePerson.type === 3 && data.repeatSend && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitSingleMessage,
payload: {
msgs: data,
select: {
name: activePerson.name,
type: 3
},
key: activePerson.key
}
});
// 转发消息失败重发群聊消息
} else if (activePerson.type === 4 && data.repeatSend && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitGroupMessage,
payload: {
msgs: data,
select: {
key: activePerson.key,
type: 4
},
key: activePerson.key
}
});
// 发送单聊消息
} else if (activePerson.type === 3 && !data.repeatSend) {
let singleMsg: any = {
target_username: activePerson.name,
content: data.content,
need_receipt: true
};
if (data.extras) {
singleMsg.extras = data.extras;
}
msgs.singleMsg = singleMsg;
msgs.msg_type = 3;
this.store$.dispatch({
type: chatAction.sendSingleMessage,
payload: {
singleMsg,
key: activePerson.key,
msgs,
active: activePerson
}
});
// 发送群组消息
} else if (activePerson.type === 4 && !data.repeatSend) {
let groupMsg: any = {
target_gid: activePerson.key,
content: data.content,
need_receipt: true
};
if (data.extras) {
groupMsg.extras = data.extras;
}
if (data.isAtAll) {
groupMsg.at_list = [];
} else if (data.atList && data.atList.length > 0) {
groupMsg.at_list = data.atList;
}
msgs.groupMsg = groupMsg;
msgs.msg_type = 4;
this.store$.dispatch({
type: chatAction.sendGroupMessage,
payload: {
groupMsg,
key: activePerson.key,
msgs,
active: activePerson
}
});
// 重发单聊消息
} else if (activePerson.type === 3 && data.repeatSend) {
this.store$.dispatch({
type: chatAction.sendSingleMessage,
payload: {
singleMsg: data.singleMsg,
key: activePerson.key,
msgs: data,
active: activePerson
}
});
// 重发群聊消息
} else if (activePerson.type === 4 && data.repeatSend) {
this.store$.dispatch({
type: chatAction.sendGroupMessage,
payload: {
groupMsg: data.groupMsg,
key: activePerson.key,
msgs: data,
active: activePerson
}
});
}
}
// 发送图片消息
private sendPicEmit(data) {
const file = this.elementRef.nativeElement.querySelector('#sendPic');
// repeatSend = true重发消息
if (data.repeatSend && this.active.type === 3 && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitSinglePic,
payload: {
msgs: data,
select: {
name: this.active.name,
type: 3
},
key: this.active.key
}
});
return;
} else if (data.repeatSend && this.active.type === 4 && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitGroupPic,
payload: {
msgs: data,
select: {
key: this.active.key,
type: 4
},
key: this.active.key
}
});
return;
} else if (data.repeatSend && this.active.type === 3) {
this.store$.dispatch({
type: chatAction.sendSinglePic,
payload: {
singlePicFormData: data.singlePicFormData,
key: this.active.key,
msgs: data,
active: this.active
}
});
return;
} else if (data.repeatSend && this.active.type === 4) {
this.store$.dispatch({
type: chatAction.sendGroupPic,
payload: {
groupPicFormData: data.groupPicFormData,
key: this.active.key,
msgs: data,
active: this.active
}
});
return;
}
// 粘贴图片发送
if (data.type === 'paste') {
this.sendPicContent(data.info, data.img);
// 正常发送图片
} else if (data.type === 'send') {
const isNotImage = '选择的文件必须是图片';
Util.imgReader(file,
() => this.selectImageError(isNotImage),
(value) => this.sendPicContent(value, data.img)
);
// 发送极光熊表情
} else if (data.type === 'jpushEmoji') {
const msg = {
content: {
from_id: global.user,
msg_type: 'image',
msg_body: data.jpushEmoji.body,
target_id: this.active.name
},
ctime_ms: new Date().getTime(),
success: 1,
msgKey: this.msgKey++,
unread_count: 0,
hasLoad: false,
showMoreIcon: false,
conversation_time_show: 'today',
isTransmitMsg: true
};
const message = {
select: this.active,
msgs: msg,
key: this.active.key
};
let type;
if (this.active.type === 3) {
type = chatAction.transmitSinglePic;
} else if (this.active.type === 4) {
type = chatAction.transmitGroupPic;
}
this.store$.dispatch({
type,
payload: message
});
}
}
private sendPicContent(value, data) {
let msgs: any = {
content: {
from_id: global.user,
msg_type: 'image',
msg_body: {
media_url: value.src,
width: value.width,
height: value.height
}
},
ctime_ms: new Date().getTime(),
success: 1,
msgKey: this.msgKey++,
unread_count: 0
};
// 发送单聊图片
if (this.active.type === 3) {
const singlePicFormData = {
target_username: this.active.name,
appkey: authPayload.appkey,
image: data,
need_receipt: true
};
msgs.singlePicFormData = singlePicFormData;
msgs.msg_type = 3;
this.store$.dispatch({
type: chatAction.sendSinglePic,
payload: {
singlePicFormData,
key: this.active.key,
msgs,
active: this.active
}
});
// 发送群聊图片
} else if (this.active.type === 4) {
const groupPicFormData = {
target_gid: this.active.key,
image: data,
need_receipt: true
};
msgs.groupPicFormData = groupPicFormData;
msgs.msg_type = 4;
this.store$.dispatch({
type: chatAction.sendGroupPic,
payload: {
groupPicFormData,
key: this.active.key,
msgs,
active: this.active
}
});
}
}
private sendFileEmit(data) {
// 转发消息失败重发消息
if (data.repeatSend && this.active.type === 3 && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitSingleFile,
payload: {
msgs: data,
select: {
name: this.active.name,
type: 3
},
key: this.active.key
}
});
return;
} else if (data.repeatSend && this.active.type === 4 && data.isTransmitMsg) {
this.store$.dispatch({
type: chatAction.transmitGroupFile,
payload: {
msgs: data,
select: {
key: this.active.key,
type: 4
},
key: this.active.key
}
});
return;
}
// repeatSend = true重发消息
let msgs;
if (!data.repeatSend) {
const ext = Util.getExt(data.fileData.name);
msgs = {
content: {
msg_type: 'file',
from_id: global.user,
from_name: this.selfInfo.nickname,
msg_body: {
fname: data.fileData.name,
fsize: data.fileData.size,
extras: {
fileSize: data.fileData.size,
fileType: ext
}
}
},
ctime_ms: new Date().getTime(),
success: 1,
msgKey: this.msgKey++,
unread_count: 0
};
}
// 发送单聊文件
if (this.active.type === 3 && !data.repeatSend) {
const ext = Util.getExt(data.fileData.name);
const singleFile = {
file: data.file,
target_username: this.active.name,
appkey: authPayload.appkey,
extras: {
fileSize: data.fileData.size,
fileType: ext
},
need_receipt: true
};
msgs.singleFile = singleFile;
msgs.msg_type = 3;
this.store$.dispatch({
type: chatAction.sendSingleFile,
payload: {
key: this.active.key,
msgs,
singleFile,
active: this.active
}
});
// 发送群组文件
} else if (this.active.type === 4 && !data.repeatSend) {
const ext = Util.getExt(data.fileData.name);
const groupFile = {
file: data.file,
target_gid: this.active.key,
extras: {
fileSize: data.fileData.size,
fileType: ext
},
need_receipt: true
};
msgs.groupFile = groupFile;
msgs.msg_type = 4;
this.store$.dispatch({
type: chatAction.sendGroupFile,
payload: {
key: this.active.key,
msgs,
groupFile,
active: this.active
}
});
} else if (this.active.type === 3 && data.repeatSend) {
this.store$.dispatch({
type: chatAction.sendSingleFile,
payload: {
key: this.active.key,
msgs: data,
singleFile: data.singleFile,
active: this.active
}
});
} else if (this.active.type === 4 && data.repeatSend) {
this.store$.dispatch({
type: chatAction.sendGroupFile,
payload: {
key: this.active.key,
msgs: data,
groupFile: data.groupFile,
active: this.active
}
});
}
}
// 转发位置消息失败重发
private sendLocationEmit(data) {
let type = '';
let payload;
if (this.active.type === 3) {
type = chatAction.transmitSingleLocation;
payload = {
msgs: data,
select: {
name: this.active.name,
type: 3
},
key: this.active.key
};
} else {
type = chatAction.transmitGroupLocation;
payload = {
msgs: data,
select: {
key: this.active.key,
type: 4
},
key: this.active.key
};
}
this.store$.dispatch({
type,
payload
});
}
// 保存草稿
private saveDraftEmit(tempArr) {
this.store$.dispatch({
type: chatAction.saveDraft,
payload: tempArr
});
}
// 查看用户信息
private watchOtherInfoEmit(info) {
this.store$.dispatch({
type: chatAction.watchOtherInfo,
payload: info
});
}
// 查看个人信息
private watchSelfInfoEmit() {
this.store$.dispatch({
type: mainAction.showSelfInfo,
payload: {
show: true
}
});
}
// 用户信息面板中,关闭面板或者建立单聊
private OtherInfoEmit(item) {
if (item && item.name !== this.active.name) {
this.store$.dispatch({
type: chatAction.createOtherChat,
payload: item
});
}
// 切换到会话列表tab
if (item) {
this.store$.dispatch({
type: chatAction.changeHideAll,
payload: 0
});
this.store$.dispatch({
type: mainAction.changeListTab,
payload: 0
});
}
this.store$.dispatch({
type: chatAction.hideOtherInfo,
payload: {
show: false,
info: {}
}
});
}
// 查看群设置
private groupSettingEmit() {
const groupSetting = this.messageList[this.active.activeIndex].groupSetting;
this.store$.dispatch({
type: chatAction.groupSetting,
payload: {
active: this.active,
show: true,
// 是否已经请求过
isCache: groupSetting && groupSetting.groupInfo,
loading: true
}
});
}
// 关闭群设置
private closeGroupSettingEmit() {
this.store$.dispatch({
type: chatAction.groupSetting,
payload: {
show: false
}
});
}
// 退出群聊
private exitGroupEmit(groupInfo) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
groupInfo,
title: '退群',
tip: `确定要退出 ${groupInfo.name} 吗?`,
actionType: mainAction.exitGroupConfirmModal
}
}
});
}
// 增加或者取消单聊黑名单
private changeSingleBlackEmit(otherInfo) {
if (otherInfo.black) {
this.store$.dispatch({
type: chatAction.deleteSingleBlack,
payload: otherInfo
});
} else {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
active: otherInfo,
title: '加入黑名单',
tip: `确定将 ${otherInfo.memo_name || otherInfo.nickname
|| otherInfo.username} 加入黑名单吗?`,
actionType: mainAction.addBlackListConfirmModal
}
}
});
}
}
// 增加或者取消单聊免打扰
private changeSingleNoDisturbEmit(otherInfo) {
if (otherInfo.noDisturb) {
this.store$.dispatch({
type: chatAction.deleteSingleNoDisturb,
payload: otherInfo
});
} else {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
active: otherInfo,
title: '消息免打扰',
tip: `确定将 ${otherInfo.memo_name || otherInfo.nickname
|| otherInfo.username} 加入免打扰吗?`,
subTip: '设置之后正常接收消息,但无通知提示',
actionType: mainAction.addSingleNoDisturbConfirmModal
}
}
});
}
}
// 删除群成员
private deleteMemberEmit(item) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
group: this.active,
deleteItem: item,
title: '删除群成员',
tip: `确定删除群成员 ${item.memo_name || item.nickName || item.username} 吗?`,
actionType: mainAction.deleteMemberConfirmModal
}
}
});
}
// 显示群描述模态框
private modifyGroupDescriptionEmit() {
this.store$.dispatch({
type: chatAction.groupDescription,
payload: {
show: true
}
});
}
// 更新群信息
private updateGroupInfoEmit(newGroupInfo) {
if (newGroupInfo) {
this.store$.dispatch({
type: chatAction.updateGroupInfo,
payload: newGroupInfo
});
} else {
this.store$.dispatch({
type: chatAction.groupDescription,
payload: {
show: false
}
});
}
}
// 多人会话
private addGroupEmit() {
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: true,
display: true,
info: {
activeSingle: this.active,
action: 'many',
selfInfo: this.selfInfo
}
}
});
}
// 添加群成员
private addMemberEmit() {
this.store$.dispatch({
type: mainAction.createGroupShow,
payload: {
show: true,
display: true,
info: {
filter: this.groupSetting.memberList,
action: 'add',
activeGroup: this.active
}
}
});
}
// 修改群名
private modifyGroupNameEmit(newGroupName) {
const groupSetting = Object.assign({}, this.groupSetting.groupInfo,
{ name: newGroupName, actionType: 'modifyName' });
this.store$.dispatch({
type: chatAction.updateGroupInfo,
payload: groupSetting
});
}
// 显示视频模态框
private playVideoEmit(url) {
this.store$.dispatch({
type: chatAction.playVideoShow,
payload: {
url,
show: true
}
});
}
// 关闭视频模态框
private closeVideoEmit() {
this.store$.dispatch({
type: chatAction.playVideoShow,
payload: {
url: '',
show: false
}
});
}
// 消息撤回
private msgRetractEmit(item) {
this.store$.dispatch({
type: chatAction.msgRetract,
payload: item
});
}
// 转发消息或发送名片弹窗显示
private msgTransmitEmit(item) {
this.messageTransmit.list = this.conversationList;
this.messageTransmit.show = true;
this.messageTransmit.type = 'msgTransmit';
this.transmitAllMsg = Util.deepCopyObj(item);
}
// 转发消息或发送名片弹窗搜索
private searchMessageTransmitEmit(keywords) {
this.store$.dispatch({
type: chatAction.searchMessageTransmit,
payload: keywords
});
}
// 转发消息或发送名片
private confirmTransmitEmit(info) {
if (info.type === 'sendCard') {
this.sendCardConfirm(info);
} else if (info.type === 'msgTransmit') {
this.msgTransmitConfirm(info);
}
}
// 发送名片发送模态框点击确定发送名片
private sendCardConfirm(info) {
this.sendBusinessCardCount = 0;
let newInfo;
if (this.otherInfo.show) {
newInfo = this.otherInfo.info;
} else {
if (this.selfInfo.username) {
this.selfInfo.name = this.selfInfo.username;
}
if (this.selfInfo.nickname) {
this.selfInfo.nickName = this.selfInfo.nickname;
}
newInfo = this.selfInfo;
}
for (let select of info.selectList) {
const msg = {
content: '推荐了一张名片',
extras: {
userName: newInfo.name,
appKey: newInfo.appkey,
businessCard: 'businessCard'
},
localExtras: {
userName: newInfo.name,
appKey: newInfo.appkey,
businessCard: 'businessCard',
media_url: newInfo.avatarUrl,
nickName: newInfo.nickName
}
};
this.sendBusinessCardCount++;
this.sendMsgEmit(msg, select);
}
}
// 消息面板发送名片
private businessCardSendEmit(user) {
const msg = {
content: '推荐了一张名片',
extras: {
userName: user.name,
appKey: user.appkey,
businessCard: 'businessCard'
},
localExtras: {
userName: user.name,
appKey: user.appkey,
businessCard: 'businessCard',
media_url: user.avatarUrl,
nickName: user.nickName
}
};
this.sendMsgEmit(msg);
}
// 消息转发(包括各种消息的转发)
private msgTransmitConfirm(info) {
delete this.transmitAllMsg.msg_id;
this.transmitAllMsg.msgKey = this.msgKey++;
this.transmitAllMsg.totalTransmitNum = info.selectList.length;
this.transmitAllMsg.ctime_ms = new Date().getTime();
this.transmitAllMsg.conversation_time_show = 'today';
this.transmitAllMsg.time_show = '';
this.transmitAllMsg.showMoreIcon = false;
this.transmitAllMsg.hasLoad = false;
this.transmitAllMsg.content.from_id = global.user;
this.transmitAllMsg.isTransmitMsg = true;
this.transmitAllMsg.unread_count = 0;
this.transmitAllMsg.success = 1;
for (let item of info.selectList) {
this.transmitAllMsg.content.target_id = item.name;
this.transmitAllMsg.type = item.type;
if (item.type === 3) {
this.transmitAllMsg.msg_type = 3;
} else {
this.transmitAllMsg.msg_type = 4;
}
const data = {
select: item,
msgs: Util.deepCopyObj(this.transmitAllMsg),
key: item.key,
transmitMsg: true
};
let type = '';
switch (this.transmitAllMsg.content.msg_type) {
case 'text':
if (item.type === 3) {
type = chatAction.transmitSingleMessage;
} else {
type = chatAction.transmitGroupMessage;
}
break;
case 'image':
if (item.type === 3) {
type = chatAction.transmitSinglePic;
} else {
type = chatAction.transmitGroupPic;
}
break;
case 'file':
if (item.type === 3) {
type = chatAction.transmitSingleFile;
} else {
type = chatAction.transmitGroupFile;
}
break;
case 'location':
if (item.type === 3) {
type = chatAction.transmitSingleLocation;
} else {
type = chatAction.transmitGroupLocation;
}
break;
default:
}
this.store$.dispatch({
type,
payload: data
});
}
}
// 显示发送验证消息的模态框
private addFriendEmit(user) {
this.store$.dispatch({
type: chatAction.showVerifyModal,
payload: {
info: user,
show: true
}
});
}
// 验证消息模态框的按钮
private verifyModalBtnEmit(verifyModalText) {
const userInfo = Object.assign({}, this.verifyModal.info, { verifyModalText });
this.store$.dispatch({
type: chatAction.addFriendConfirm,
payload: userInfo
});
this.store$.dispatch({
type: chatAction.showVerifyModal,
payload: {
info: {},
show: false
}
});
}
// 修改备注名
private saveMemoNameEmit(info) {
this.store$.dispatch({
type: chatAction.saveMemoName,
payload: info
});
}
// 删除好友
private deleteFriendEmit(info) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
active: info,
title: '删除好友',
tip: `确定删除好友 ${info.memo_name || info.nickName || info.name} 吗?`,
actionType: mainAction.deleteFriendConfirmModal
}
}
});
}
// 显示发送名片的模态框
private sendCardEmit() {
this.messageTransmit.list = this.conversationList;
this.messageTransmit.show = true;
this.messageTransmit.type = 'sendCard';
}
// 从对方信息中同意或者拒绝好友请求
private verifyUserBtnEmit(verifyUser) {
this.store$.dispatch({
type: chatAction.hideOtherInfo,
payload: {
show: false,
info: {}
}
});
this.store$.dispatch({
type: contactAction.isAgreeAddFriend,
payload: verifyUser
});
}
private updateGroupAvatarEmit(groupAvatarInput) {
this.getImgObj(groupAvatarInput.files[0]);
groupAvatarInput.value = '';
}
// 选择图片出错
private selectImageError(tip: string) {
this.store$.dispatch({
type: mainAction.showModalTip,
payload: {
show: true,
info: {
title: '提示',
tip,
actionType: '[main] must be image',
cancel: true
}
}
});
}
// 获取图片对象
private getImgObj(file) {
const isNotImage = '选择的文件必须是图片';
const imageTooSmall = '选择的图片宽或高的尺寸太小,请重新选择图片';
Util.getAvatarImgObj(file,
() => this.selectImageError(isNotImage),
() => this.selectImageError(imageTooSmall),
(that, pasteFile, img) => {
this.groupAvatar.info = {
src: that.result,
width: img.naturalWidth,
height: img.naturalHeight,
pasteFile
};
this.groupAvatar.src = that.result;
this.groupAvatar.show = true;
this.groupAvatar.filename = file.name;
}
);
}
// 修改群头像
private groupAvatarEmit(groupAvatarInfo) {
const groupSetting = {
gid: this.groupSetting.groupInfo.gid,
avatar: groupAvatarInfo.formData,
actionType: 'modifyGroupAvatar',
src: groupAvatarInfo.src
};
this.store$.dispatch({
type: chatAction.updateGroupInfo,
payload: groupSetting
});
}
// 会话置顶
private conversationToTopEmit(item) {
if (item.key > 0) {
this.store$.dispatch({
type: chatAction.conversationToTop,
payload: item
});
} else {
this.store$.dispatch({
type: chatAction.conversationToTopSuccess,
payload: item
});
}
}
// 从未读列表查看对方资料
private readListOtherInfoEmit(info) {
this.store$.dispatch({
type: chatAction.watchOtherInfo,
payload: info
});
}
// 透传消息-正在输入
private inputMessageEmit(input) {
this.store$.dispatch({
type: chatAction.inputMessage,
payload: {
active: this.active,
input
}
});
}
// 群成员禁言/取消禁言
private keepSilenceEmit(item) {
if (item.keep_silence) {
this.store$.dispatch({
type: chatAction.deleteGroupMemberSilence,
payload: {
active: this.active,
item
}
});
} else {
this.store$.dispatch({
type: chatAction.addGroupMemberSilence,
payload: {
active: this.active,
item
}
});
}
}
// 初始化所有数据
private init() {
this.isLoaded = false;
this.conversationList = [];
this.messageList = [
{
key: 0,
msgs: [],
groupSetting: {
groupInfo: {},
memberList: []
}
}
];
this.global = global;
this.active = {
name: '',
nickName: '',
key: '',
activeIndex: -1,
type: 0,
change: false,
shield: false,
appkey: ''
};
this.defaultPanelIsShow = true;
this.otherInfo = {
show: false,
info: {
name: '',
appkey: '',
avatarUrl: '',
nickName: ''
}
};
this.blackMenu = {
show: false,
menu: []
};
this.groupSetting = {
groupInfo: {
name: '',
desc: '',
gid: 0
},
memberList: [],
active: {},
show: false
};
this.msgKey = 1;
this.groupDescription = {
show: false,
description: {}
};
this.selfInfo = {};
this.isCacheArr = [];
this.playVideoShow = {
show: false,
url: ''
};
this.eventArr = [];
this.hasOffline = 0;
this.otherOptionScrollBottom = false;
this.changeActiveScrollBottom = false;
this.windowIsFocus = true;
this.newMessageNotice = {
timer: null,
num: 0
};
this.messageTransmit = {
list: [],
show: false,
type: ''
};
this.transmitAllMsg = {
content: {
msg_type: '',
from_id: '',
target_id: ''
},
msgKey: -1,
totalTransmitNum: 0,
ctime_ms: 0,
conversation_time_show: '',
time_show: '',
hasLoad: false,
showMoreIcon: false,
type: 0,
key: 0,
isTransmitMsg: true,
msg_id: 0,
unread_count: 0,
msg_type: 0,
success: 1
};
this.verifyModal = {
info: {},
show: false
};
this.changeOtherInfoFlag = false;
this.sendBusinessCardCount = 0;
this.groupAvatar = {
info: {
src: '',
width: 0,
height: 0,
pasteFile: {}
},
show: false,
formData: {},
src: '',
filename: '',
title: '群组头像'
};
this.unreadList = {
show: false,
info: {
read: [],
unread: []
},
loading: false
};
this.isMySelf = false;
this.noLoadedMessage = [];
this.inputMessage = '';
this.inputMessageTimer = null;
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Logic App (Standard / Single Tenant)
*
* > **Note:** To connect an Azure Logic App and a subnet within the same region `azure.appservice.VirtualNetworkSwiftConnection` can be used.
* For an example, check the `azure.appservice.VirtualNetworkSwiftConnection` documentation.
*
* ## Example Usage
* ### With App Service Plan)
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const examplePlan = new azure.appservice.Plan("examplePlan", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* sku: {
* tier: "ElasticPremium",
* size: "EP1",
* },
* });
* const exampleStandard = new azure.logicapps.Standard("exampleStandard", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* appServicePlanId: examplePlan.id,
* storageAccountName: exampleAccount.name,
* storageAccountAccessKey: exampleAccount.primaryAccessKey,
* });
* ```
* ### For Container Mode)
*
* > **Note:** You must set `azure.appservice.Plan` `kind` to `Linux` and `reserved` to `true` when used with `linuxFxVersion`
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const examplePlan = new azure.appservice.Plan("examplePlan", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* kind: "Linux",
* reserved: true,
* sku: {
* tier: "ElasticPremium",
* size: "EP1",
* },
* });
* const exampleStandard = new azure.logicapps.Standard("exampleStandard", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* appServicePlanId: examplePlan.id,
* storageAccountName: exampleAccount.name,
* storageAccountAccessKey: exampleAccount.primaryAccessKey,
* siteConfig: {
* linuxFxVersion: "DOCKER|mcr.microsoft.com/azure-functions/dotnet:3.0-appservice",
* },
* appSettings: {
* DOCKER_REGISTRY_SERVER_URL: "https://<server-name>.azurecr.io",
* DOCKER_REGISTRY_SERVER_USERNAME: "username",
* DOCKER_REGISTRY_SERVER_PASSWORD: "password",
* },
* });
* ```
*
* ## Import
*
* Logic Apps can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:logicapps/standard:Standard logicapp1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Web/sites/logicapp1
* ```
*/
export class Standard extends pulumi.CustomResource {
/**
* Get an existing Standard resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: StandardState, opts?: pulumi.CustomResourceOptions): Standard {
return new Standard(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:logicapps/standard:Standard';
/**
* Returns true if the given object is an instance of Standard. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Standard {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Standard.__pulumiType;
}
/**
* The ID of the App Service Plan within which to create this Logic App
*/
public readonly appServicePlanId!: pulumi.Output<string>;
/**
* A map of key-value pairs for [App Settings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-app-settings) and custom values.
*/
public readonly appSettings!: pulumi.Output<{[key: string]: string}>;
/**
* If `useExtensionBundle` then controls the allowed range for bundle versions. Default `[1.*, 2.0.0)`
*/
public readonly bundleVersion!: pulumi.Output<string | undefined>;
/**
* Should the Logic App send session affinity cookies, which route client requests in the same session to the same instance?
*/
public readonly clientAffinityEnabled!: pulumi.Output<boolean>;
/**
* The mode of the Logic App's client certificates requirement for incoming requests. Possible values are `Required` and `Optional`.
*/
public readonly clientCertificateMode!: pulumi.Output<string | undefined>;
/**
* An `connectionString` block as defined below.
*/
public readonly connectionStrings!: pulumi.Output<outputs.logicapps.StandardConnectionString[]>;
/**
* An identifier used by App Service to perform domain ownership verification via DNS TXT record.
*/
public /*out*/ readonly customDomainVerificationId!: pulumi.Output<string>;
/**
* The default hostname associated with the Logic App - such as `mysite.azurewebsites.net`
*/
public /*out*/ readonly defaultHostname!: pulumi.Output<string>;
/**
* Is the Logic App enabled?
*/
public readonly enabled!: pulumi.Output<boolean | undefined>;
/**
* Can the Logic App only be accessed via HTTPS? Defaults to `false`.
*/
public readonly httpsOnly!: pulumi.Output<boolean | undefined>;
/**
* An `identity` block as defined below.
*/
public readonly identity!: pulumi.Output<outputs.logicapps.StandardIdentity>;
/**
* The Logic App kind - will be `functionapp,workflowapp`
*/
public /*out*/ readonly kind!: pulumi.Output<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
public readonly location!: pulumi.Output<string>;
/**
* Specifies the name of the Logic App Changing this forces a new resource to be created.
*/
public readonly name!: pulumi.Output<string>;
/**
* A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12`
*/
public /*out*/ readonly outboundIpAddresses!: pulumi.Output<string>;
/**
* A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12,52.143.43.17` - not all of which are necessarily in use. Superset of `outboundIpAddresses`.
*/
public /*out*/ readonly possibleOutboundIpAddresses!: pulumi.Output<string>;
/**
* The name of the resource group in which to create the Logic App
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* A `siteConfig` object as defined below.
*/
public readonly siteConfig!: pulumi.Output<outputs.logicapps.StandardSiteConfig>;
/**
* A `siteCredential` block as defined below, which contains the site-level credentials used to publish to this App Service.
*/
public /*out*/ readonly siteCredentials!: pulumi.Output<outputs.logicapps.StandardSiteCredential[]>;
/**
* The access key which will be used to access the backend storage account for the Logic App
*/
public readonly storageAccountAccessKey!: pulumi.Output<string>;
/**
* The backend storage account name which will be used by this Logic App (e.g. for Stateful workflows data)
*/
public readonly storageAccountName!: pulumi.Output<string>;
/**
* The name of the share used by the logic app, if you want to use a custom name. This corresponds to the WEBSITE_CONTENTSHARE appsetting, which this resource will create for you. If you don't specify a name, then this resource will generate a dynamic name. This setting is useful if you want to provision a storage account and create a share using azurerm_storage_share
*/
public readonly storageAccountShareName!: pulumi.Output<string>;
/**
* A mapping of tags to assign to the resource.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Should the logic app use the bundled extension package? If true, then application settings for `AzureFunctionsJobHost__extensionBundle__id` and `AzureFunctionsJobHost__extensionBundle__version` will be created. Default true
*/
public readonly useExtensionBundle!: pulumi.Output<boolean | undefined>;
/**
* The runtime version associated with the Logic App Defaults to `~1`.
*/
public readonly version!: pulumi.Output<string | undefined>;
/**
* Create a Standard resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: StandardArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: StandardArgs | StandardState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as StandardState | undefined;
inputs["appServicePlanId"] = state ? state.appServicePlanId : undefined;
inputs["appSettings"] = state ? state.appSettings : undefined;
inputs["bundleVersion"] = state ? state.bundleVersion : undefined;
inputs["clientAffinityEnabled"] = state ? state.clientAffinityEnabled : undefined;
inputs["clientCertificateMode"] = state ? state.clientCertificateMode : undefined;
inputs["connectionStrings"] = state ? state.connectionStrings : undefined;
inputs["customDomainVerificationId"] = state ? state.customDomainVerificationId : undefined;
inputs["defaultHostname"] = state ? state.defaultHostname : undefined;
inputs["enabled"] = state ? state.enabled : undefined;
inputs["httpsOnly"] = state ? state.httpsOnly : undefined;
inputs["identity"] = state ? state.identity : undefined;
inputs["kind"] = state ? state.kind : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["outboundIpAddresses"] = state ? state.outboundIpAddresses : undefined;
inputs["possibleOutboundIpAddresses"] = state ? state.possibleOutboundIpAddresses : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["siteConfig"] = state ? state.siteConfig : undefined;
inputs["siteCredentials"] = state ? state.siteCredentials : undefined;
inputs["storageAccountAccessKey"] = state ? state.storageAccountAccessKey : undefined;
inputs["storageAccountName"] = state ? state.storageAccountName : undefined;
inputs["storageAccountShareName"] = state ? state.storageAccountShareName : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["useExtensionBundle"] = state ? state.useExtensionBundle : undefined;
inputs["version"] = state ? state.version : undefined;
} else {
const args = argsOrState as StandardArgs | undefined;
if ((!args || args.appServicePlanId === undefined) && !opts.urn) {
throw new Error("Missing required property 'appServicePlanId'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
if ((!args || args.storageAccountAccessKey === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountAccessKey'");
}
if ((!args || args.storageAccountName === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageAccountName'");
}
inputs["appServicePlanId"] = args ? args.appServicePlanId : undefined;
inputs["appSettings"] = args ? args.appSettings : undefined;
inputs["bundleVersion"] = args ? args.bundleVersion : undefined;
inputs["clientAffinityEnabled"] = args ? args.clientAffinityEnabled : undefined;
inputs["clientCertificateMode"] = args ? args.clientCertificateMode : undefined;
inputs["connectionStrings"] = args ? args.connectionStrings : undefined;
inputs["enabled"] = args ? args.enabled : undefined;
inputs["httpsOnly"] = args ? args.httpsOnly : undefined;
inputs["identity"] = args ? args.identity : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["siteConfig"] = args ? args.siteConfig : undefined;
inputs["storageAccountAccessKey"] = args ? args.storageAccountAccessKey : undefined;
inputs["storageAccountName"] = args ? args.storageAccountName : undefined;
inputs["storageAccountShareName"] = args ? args.storageAccountShareName : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["useExtensionBundle"] = args ? args.useExtensionBundle : undefined;
inputs["version"] = args ? args.version : undefined;
inputs["customDomainVerificationId"] = undefined /*out*/;
inputs["defaultHostname"] = undefined /*out*/;
inputs["kind"] = undefined /*out*/;
inputs["outboundIpAddresses"] = undefined /*out*/;
inputs["possibleOutboundIpAddresses"] = undefined /*out*/;
inputs["siteCredentials"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Standard.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Standard resources.
*/
export interface StandardState {
/**
* The ID of the App Service Plan within which to create this Logic App
*/
appServicePlanId?: pulumi.Input<string>;
/**
* A map of key-value pairs for [App Settings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-app-settings) and custom values.
*/
appSettings?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* If `useExtensionBundle` then controls the allowed range for bundle versions. Default `[1.*, 2.0.0)`
*/
bundleVersion?: pulumi.Input<string>;
/**
* Should the Logic App send session affinity cookies, which route client requests in the same session to the same instance?
*/
clientAffinityEnabled?: pulumi.Input<boolean>;
/**
* The mode of the Logic App's client certificates requirement for incoming requests. Possible values are `Required` and `Optional`.
*/
clientCertificateMode?: pulumi.Input<string>;
/**
* An `connectionString` block as defined below.
*/
connectionStrings?: pulumi.Input<pulumi.Input<inputs.logicapps.StandardConnectionString>[]>;
/**
* An identifier used by App Service to perform domain ownership verification via DNS TXT record.
*/
customDomainVerificationId?: pulumi.Input<string>;
/**
* The default hostname associated with the Logic App - such as `mysite.azurewebsites.net`
*/
defaultHostname?: pulumi.Input<string>;
/**
* Is the Logic App enabled?
*/
enabled?: pulumi.Input<boolean>;
/**
* Can the Logic App only be accessed via HTTPS? Defaults to `false`.
*/
httpsOnly?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.logicapps.StandardIdentity>;
/**
* The Logic App kind - will be `functionapp,workflowapp`
*/
kind?: pulumi.Input<string>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the name of the Logic App Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12`
*/
outboundIpAddresses?: pulumi.Input<string>;
/**
* A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12,52.143.43.17` - not all of which are necessarily in use. Superset of `outboundIpAddresses`.
*/
possibleOutboundIpAddresses?: pulumi.Input<string>;
/**
* The name of the resource group in which to create the Logic App
*/
resourceGroupName?: pulumi.Input<string>;
/**
* A `siteConfig` object as defined below.
*/
siteConfig?: pulumi.Input<inputs.logicapps.StandardSiteConfig>;
/**
* A `siteCredential` block as defined below, which contains the site-level credentials used to publish to this App Service.
*/
siteCredentials?: pulumi.Input<pulumi.Input<inputs.logicapps.StandardSiteCredential>[]>;
/**
* The access key which will be used to access the backend storage account for the Logic App
*/
storageAccountAccessKey?: pulumi.Input<string>;
/**
* The backend storage account name which will be used by this Logic App (e.g. for Stateful workflows data)
*/
storageAccountName?: pulumi.Input<string>;
/**
* The name of the share used by the logic app, if you want to use a custom name. This corresponds to the WEBSITE_CONTENTSHARE appsetting, which this resource will create for you. If you don't specify a name, then this resource will generate a dynamic name. This setting is useful if you want to provision a storage account and create a share using azurerm_storage_share
*/
storageAccountShareName?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Should the logic app use the bundled extension package? If true, then application settings for `AzureFunctionsJobHost__extensionBundle__id` and `AzureFunctionsJobHost__extensionBundle__version` will be created. Default true
*/
useExtensionBundle?: pulumi.Input<boolean>;
/**
* The runtime version associated with the Logic App Defaults to `~1`.
*/
version?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Standard resource.
*/
export interface StandardArgs {
/**
* The ID of the App Service Plan within which to create this Logic App
*/
appServicePlanId: pulumi.Input<string>;
/**
* A map of key-value pairs for [App Settings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-app-settings) and custom values.
*/
appSettings?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* If `useExtensionBundle` then controls the allowed range for bundle versions. Default `[1.*, 2.0.0)`
*/
bundleVersion?: pulumi.Input<string>;
/**
* Should the Logic App send session affinity cookies, which route client requests in the same session to the same instance?
*/
clientAffinityEnabled?: pulumi.Input<boolean>;
/**
* The mode of the Logic App's client certificates requirement for incoming requests. Possible values are `Required` and `Optional`.
*/
clientCertificateMode?: pulumi.Input<string>;
/**
* An `connectionString` block as defined below.
*/
connectionStrings?: pulumi.Input<pulumi.Input<inputs.logicapps.StandardConnectionString>[]>;
/**
* Is the Logic App enabled?
*/
enabled?: pulumi.Input<boolean>;
/**
* Can the Logic App only be accessed via HTTPS? Defaults to `false`.
*/
httpsOnly?: pulumi.Input<boolean>;
/**
* An `identity` block as defined below.
*/
identity?: pulumi.Input<inputs.logicapps.StandardIdentity>;
/**
* Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
*/
location?: pulumi.Input<string>;
/**
* Specifies the name of the Logic App Changing this forces a new resource to be created.
*/
name?: pulumi.Input<string>;
/**
* The name of the resource group in which to create the Logic App
*/
resourceGroupName: pulumi.Input<string>;
/**
* A `siteConfig` object as defined below.
*/
siteConfig?: pulumi.Input<inputs.logicapps.StandardSiteConfig>;
/**
* The access key which will be used to access the backend storage account for the Logic App
*/
storageAccountAccessKey: pulumi.Input<string>;
/**
* The backend storage account name which will be used by this Logic App (e.g. for Stateful workflows data)
*/
storageAccountName: pulumi.Input<string>;
/**
* The name of the share used by the logic app, if you want to use a custom name. This corresponds to the WEBSITE_CONTENTSHARE appsetting, which this resource will create for you. If you don't specify a name, then this resource will generate a dynamic name. This setting is useful if you want to provision a storage account and create a share using azurerm_storage_share
*/
storageAccountShareName?: pulumi.Input<string>;
/**
* A mapping of tags to assign to the resource.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Should the logic app use the bundled extension package? If true, then application settings for `AzureFunctionsJobHost__extensionBundle__id` and `AzureFunctionsJobHost__extensionBundle__version` will be created. Default true
*/
useExtensionBundle?: pulumi.Input<boolean>;
/**
* The runtime version associated with the Logic App Defaults to `~1`.
*/
version?: pulumi.Input<string>;
} | the_stack |
import * as coreHttp from "@azure/core-http";
import { should, assert } from "chai";
import { isEqual } from "lodash";
import HeaderRestClient, { HeaderRestClientRestClient } from "./generated/headerRest/src";
should();
describe("header Rest", function() {
describe("Swagger Header BAT", function() {
describe("Basic Header Operations", function() {
let testClient: HeaderRestClientRestClient;
beforeEach(() => {
testClient = HeaderRestClient();
});
it("should override existing headers (nodejs only)", async function() {
if (!coreHttp.isNode) {
this.skip();
}
await testClient.path("/header/param/existingkey").post({
headers: {
"User-Agent": "overwrite"
},
allowInsecureConnection: true
});
const response = await testClient.path("/header/response/existingkey").post({
allowInsecureConnection: true
});
response.headers["user-agent"]!.should.be.deep.equal("overwrite");
});
it("should throw on changing protected headers", async function() {
await testClient.path("/header/param/protectedkey").post({
headers: {
"Content-Type": "text/html"
},
allowInsecureConnection: true
})
const response = await testClient.path("/header/response/protectedkey").post({
allowInsecureConnection: true
})
response.headers['content-type']!.should.be.deep.equal("text/html; charset=utf-8");
});
it("should send and receive integer type headers", async function() {
await testClient.path("/header/param/prim/integer").post({
headers:{
scenario: "positive",
value: 1
},
allowInsecureConnection: true
});
await testClient.path("/header/param/prim/integer").post({
headers:{
scenario: "negative",
value: -2
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/integer").post({
headers: {
scenario: "positive"
},
allowInsecureConnection: true
})
response1.headers.value!.should.be.deep.equal('1');
const response2 = await testClient.path("/header/response/prim/integer").post({
headers: {
scenario: "negative",
value: -2
},
allowInsecureConnection: true
})
response2.headers.value!.should.be.deep.equal('-2');
});
it("should send and receive long type headers", async function() {
await testClient.path("/header/param/prim/long").post({
headers:{
scenario: "positive",
value: 105
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/long").post({
headers:{
scenario: "positive"
},
allowInsecureConnection: true
});
response1.headers.value!.should.be.deep.equal("105");
await testClient.path("/header/param/prim/long").post({
headers:{
scenario: "negative",
value: -2
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/long").post({
headers:{
scenario: "negative"
},
allowInsecureConnection: true
});
response2.headers.value!.should.be.deep.equal("-2");
});
it("should send and receive float type headers", async function() {
await testClient.path("/header/param/prim/float").post({
headers:{
scenario: "positive",
value: 0.07
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/float").post({
headers:{
scenario: "positive"
},
allowInsecureConnection: true
});
response1.headers.value!.should.be.deep.equal("0.07");
await testClient.path("/header/param/prim/float").post({
headers:{
scenario: "negative",
value: -3.0
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/float").post({
headers:{
scenario: "negative"
},
allowInsecureConnection: true
});
response2.headers.value!.should.be.deep.equal("-3");
});
it("should send and receive double type headers", async function() {
// await testClient.header.paramDouble("positive", 7e120);
// await testClient.header.paramDouble("negative", -3.0);
// const response1 = await testClient.header.responseDouble("positive");
// response1.value!.should.be.deep.equal(7e120);
// const response2 = await testClient.header.responseDouble("negative");
// response2.value!.should.be.deep.equal(-3.0);
await testClient.path("/header/param/prim/double").post({
headers:{
scenario: "positive",
value: 7e120
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/double").post({
headers:{
scenario: "positive"
},
allowInsecureConnection: true
});
response1.headers.value!.should.be.deep.equal("7e+120");
await testClient.path("/header/param/prim/double").post({
headers:{
scenario: "negative",
value: -3.0
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/double").post({
headers:{
scenario: "negative"
},
allowInsecureConnection: true
});
response2.headers.value!.should.be.deep.equal("-3");
});
it("should send and receive boolean type headers", async function() {
await testClient.path("/header/param/prim/bool").post({
headers:{
scenario: "true",
value: true
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/bool").post({
headers:{
scenario: "true"
},
allowInsecureConnection: true
});
response1.headers.value!.should.be.deep.equal("true");
await testClient.path("/header/param/prim/bool").post({
headers:{
scenario: "false",
value: false
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/bool").post({
headers:{
scenario: "false"
},
allowInsecureConnection: true
});
response2.headers.value!.should.be.deep.equal("false");
});
it("should send and receive string type headers", async function() {
await testClient.path("/header/param/prim/string").post({
headers:{
scenario: "valid",
value: "The quick brown fox jumps over the lazy dog"
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/string").post({
headers:{
scenario: "valid"
},
allowInsecureConnection: true
});
response1.headers.value!.should.be.deep.equal("The quick brown fox jumps over the lazy dog");
await testClient.path("/header/param/prim/string").post({
headers:{
scenario: "null",
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/string").post({
headers:{
scenario: "null"
},
allowInsecureConnection: true
});
response2.headers.value!.should.be.deep.equal("null");
await testClient.path("/header/param/prim/string").post({
headers:{
scenario: "empty",
value: ""
},
allowInsecureConnection: true
});
const response3 = await testClient.path("/header/response/prim/string").post({
headers:{
scenario: "empty"
},
allowInsecureConnection: true
});
assert.deepEqual(response3.status, "200");
// assert.deepEqual(response3.headers.value, undefined);
});
it("should send and receive enum type headers", async function() {
await testClient.path("/header/param/prim/enum").post({
headers:{
scenario: "valid",
value: "GREY"
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/enum").post({
headers:{
scenario: "valid"
},
allowInsecureConnection: true
});
assert.deepEqual(response1.headers.value, "GREY");
await testClient.path("/header/param/prim/enum").post({
headers:{
scenario: "null",
},
allowInsecureConnection: true
});
const response2 = await testClient.path("/header/response/prim/enum").post({
headers:{
scenario: "null"
},
allowInsecureConnection: true
});
assert.deepEqual(response2.status, "200");
// assert.deepEqual(response2.headers.value, undefined);
});
// it.skip("should send and receive date type headers", async function() {
// await testClient.path("/header/param/prim/date").post({
// headers:{
// scenario: "valid",
// value: new Date("2010-01-01")
// },
// allowInsecureConnection: true
// });
// const response1 = await testClient.path("/header/response/prim/date").post({
// headers:{
// scenario: "valid"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response1.headers.value, "2010-01-01");
// await testClient.path("/header/param/prim/date").post({
// headers:{
// scenario: "min",
// value: new Date("0001-01-01")
// },
// allowInsecureConnection: true
// });
// const response2 = await testClient.path("/header/response/prim/date").post({
// headers:{
// scenario: "min"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response2.headers.value, "0001-01-01");
// });
// it.skip("should send and receive datetime type headers", async function() {
// await testClient.path("/header/param/prim/datetime").post({
// headers:{
// scenario: "valid",
// value: new Date("2010-01-01T12:34:56Z")
// },
// allowInsecureConnection: true
// });
// const response1 = await testClient.path("/header/response/prim/datetime").post({
// headers:{
// scenario: "valid"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response1.headers.value, "2010-01-01T12:34:56Z");
// await testClient.path("/header/param/prim/datetime").post({
// headers:{
// scenario: "min",
// value: new Date("0001-01-01T00:00:00Z")
// },
// allowInsecureConnection: true
// });
// const response2 = await testClient.path("/header/response/prim/datetime").post({
// headers:{
// scenario: "min"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response2.headers.value, "0001-01-01T00:00:00Z");
// });
// it.skip("should send and receive datetimerfc1123 type headers", async function() {
// await testClient.path("/header/param/prim/datetimerfc1123").post({
// headers:{
// scenario: "valid",
// value: new Date("2010-01-01T12:34:56Z")
// },
// allowInsecureConnection: true
// });
// const response1 = await testClient.path("/header/response/prim/datetimerfc1123").post({
// headers:{
// scenario: "valid"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response1.headers.value, "Mon, 01 Jan 0001 00:00:00 GMT");
// await testClient.path("/header/param/prim/datetimerfc1123").post({
// headers:{
// scenario: "min",
// value: new Date("0001-01-01T00:00:00Z")
// },
// allowInsecureConnection: true
// });
// const response2 = await testClient.path("/header/response/prim/datetimerfc1123").post({
// headers:{
// scenario: "min"
// },
// allowInsecureConnection: true
// });
// assert.deepEqual(response2.headers.value, "Mon, 01 Jan 0001 00:00:00 GMT");
// });
it("should send and receive duration type headers", async function() {
await testClient.path("/header/param/prim/duration").post({
headers:{
scenario: "valid",
value: "P123DT22H14M12.011S"
},
allowInsecureConnection: true
});
const response1 = await testClient.path("/header/response/prim/duration").post({
headers:{
scenario: "valid"
},
allowInsecureConnection: true
});
assert.deepEqual(response1.headers.value, "P123DT22H14M12.011S");
});
it.skip("should send and receive byte array type headers", async function() {
const value = "啊齄丂狛狜隣郎隣兀﨩";
await testClient.path("/header/param/prim/byte").post({
headers:{
scenario: "valid",
value: value
},
allowInsecureConnection: true
});
const response = await testClient.path("/header/response/prim/byte").post({
headers:{
scenario: "valid"
},
allowInsecureConnection: true
});
assert.deepEqual(response.headers.value, value)
});
});
});
}); | the_stack |
// Constants and methods found in Chromium 87.0.4280.141 (nw.js 0.50.3)
// WebGL 2 Compute was removed in Chromium 88.0.4324.11 (19 November 2020), see:
// https://chromereleases.googleblog.com/2020/11/dev-channel-update-for-desktop_19.html
// https://chromium.googlesource.com/chromium/src/+/34b075c18befb4f043aaa9612bd04ee2dc3328fd
interface HTMLCanvasElement extends HTMLElement {
getContext(
contextId: "webgl2-compute",
contextAttributes?: WebGLContextAttributes,
): WebGL2ComputeRenderingContext | null;
}
interface OffscreenCanvas {
getContext(
contextId: "webgl2-compute",
contextAttributes?: WebGLContextAttributes,
): WebGL2ComputeRenderingContext | null;
}
interface WebGL2ComputeRenderingContext extends WebGL2RenderingContext {
readonly ACTIVE_ATOMIC_COUNTER_BUFFERS: number; // 37593
readonly ACTIVE_RESOURCES: number; // 37621
readonly ACTIVE_VARIABLES: number; // 37637
readonly ALL_BARRIER_BITS: number; // 4294967295
readonly ARRAY_SIZE: number; // 37627
readonly ARRAY_STRIDE: number; // 37630
readonly ATOMIC_COUNTER_BARRIER_BIT: number; // 4096
readonly ATOMIC_COUNTER_BUFFER: number; // 37568
readonly ATOMIC_COUNTER_BUFFER_BINDING: number; // 37569
readonly ATOMIC_COUNTER_BUFFER_INDEX: number; // 37633
readonly ATOMIC_COUNTER_BUFFER_SIZE: number; // 37571
readonly ATOMIC_COUNTER_BUFFER_START: number; // 37570
readonly BLOCK_INDEX: number; // 37629
readonly BUFFER_BINDING: number; // 37634
readonly BUFFER_DATA_SIZE: number; // 37635
readonly BUFFER_UPDATE_BARRIER_BIT: number; // 512
readonly BUFFER_VARIABLE: number; // 37605
readonly COMMAND_BARRIER_BIT: number; // 64
readonly COMPUTE_SHADER: number; // 37305
readonly DISPATCH_INDIRECT_BUFFER: number; // 37102
readonly DISPATCH_INDIRECT_BUFFER_BINDING: number; // 37103
readonly DRAW_INDIRECT_BUFFER: number; // 36671
readonly DRAW_INDIRECT_BUFFER_BINDING: number; // 36675
readonly ELEMENT_ARRAY_BARRIER_BIT: number; // 2
readonly FRAMEBUFFER_BARRIER_BIT: number; // 1024
readonly IS_ROW_MAJOR: number; // 37632
readonly LOCATION: number; // 37646
readonly MATRIX_STRIDE: number; // 37631
readonly MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: number; // 37596
readonly MAX_ATOMIC_COUNTER_BUFFER_SIZE: number; // 37592
readonly MAX_COMBINED_ATOMIC_COUNTERS: number; // 37591
readonly MAX_COMBINED_ATOMIC_COUNTER_BUFFERS: number; // 37585
readonly MAX_COMBINED_SHADER_STORAGE_BLOCKS: number; // 37084
readonly MAX_COMPUTE_ATOMIC_COUNTERS: number; // 33381
readonly MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS: number; // 33380
readonly MAX_COMPUTE_IMAGE_UNIFORMS: number; // 37309
readonly MAX_COMPUTE_SHADER_STORAGE_BLOCKS: number; // 37083
readonly MAX_COMPUTE_SHARED_MEMORY_SIZE: number; // 33378
readonly MAX_COMPUTE_TEXTURE_IMAGE_UNITS: number; // 37308
readonly MAX_COMPUTE_UNIFORM_BLOCKS: number; // 37307
readonly MAX_COMPUTE_UNIFORM_COMPONENTS: number; // 33379
readonly MAX_COMPUTE_WORK_GROUP_COUNT: number; // 37310
readonly MAX_COMPUTE_WORK_GROUP_INVOCATIONS: number; // 37099
readonly MAX_COMPUTE_WORK_GROUP_SIZE: number; // 37311
readonly MAX_FRAGMENT_ATOMIC_COUNTERS: number; // 37590
readonly MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS: number; // 37584
readonly MAX_FRAGMENT_SHADER_STORAGE_BLOCKS: number; // 37082
readonly MAX_NAME_LENGTH: number; // 37622
readonly MAX_NUM_ACTIVE_VARIABLES: number; // 37623
readonly MAX_SHADER_STORAGE_BLOCK_SIZE: number; // 37086
readonly MAX_SHADER_STORAGE_BUFFER_BINDINGS: number; // 37085
readonly MAX_VERTEX_ATOMIC_COUNTERS: number; // 37586
readonly MAX_VERTEX_ATOMIC_COUNTER_BUFFERS: number; // 37580
readonly MAX_VERTEX_SHADER_STORAGE_BLOCKS: number; // 37078
readonly NAME_LENGTH: number; // 37625
readonly NUM_ACTIVE_VARIABLES: number; // 37636
readonly OFFSET: number; // 37628
readonly PIXEL_BUFFER_BARRIER_BIT: number; // 128
readonly PROGRAM_INPUT: number; // 37603
readonly PROGRAM_OUTPUT: number; // 37604
readonly READ_ONLY: number; // 35000
readonly READ_WRITE: number; // 35002
readonly REFERENCED_BY_COMPUTE_SHADER: number; // 37643
readonly REFERENCED_BY_FRAGMENT_SHADER: number; // 37642
readonly REFERENCED_BY_VERTEX_SHADER: number; // 37638
readonly SHADER_IMAGE_ACCESS_BARRIER_BIT: number; // 32
readonly SHADER_STORAGE_BARRIER_BIT: number; // 8192
readonly SHADER_STORAGE_BLOCK: number; // 37606
readonly SHADER_STORAGE_BUFFER: number; // 37074
readonly SHADER_STORAGE_BUFFER_BINDING: number; // 37075
readonly SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: number; // 37087
readonly SHADER_STORAGE_BUFFER_SIZE: number; // 37077
readonly SHADER_STORAGE_BUFFER_START: number; // 37076
readonly TEXTURE_FETCH_BARRIER_BIT: number; // 8
readonly TEXTURE_UPDATE_BARRIER_BIT: number; // 256
readonly TOP_LEVEL_ARRAY_SIZE: number; // 37644
readonly TOP_LEVEL_ARRAY_STRIDE: number; // 37645
readonly TRANSFORM_FEEDBACK_BARRIER_BIT: number; // 2048
readonly TRANSFORM_FEEDBACK_VARYING: number; // 37620
readonly TYPE: number; // 37626
readonly UNIFORM: number; // 37601
readonly UNIFORM_BARRIER_BIT: number; // 4
readonly UNIFORM_BLOCK: number; // 37602
readonly UNSIGNED_INT_ATOMIC_COUNTER: number; // 37595
readonly VERTEX_ATTRIB_ARRAY_BARRIER_BIT: number; // 1
readonly WRITE_ONLY: number; // 35001
bindImageTexture(unit: number, texture: WebGLTexture | null, level: number, layered: boolean, layer: number, access: number, format: number): void;
dispatchCompute(num_groups_x: number, num_groups_y: number, num_groups_z: number): void;
dispatchComputeIndirect(offset: number): void;
drawArraysIndirect(mode: number, offset: number): void;
drawElementsIndirect(mode: number, type: number, offset: number): void;
getProgramInterfaceParameter(program: WebGLProgram, programInterface: number, pname: number): any;
getProgramResource(program: WebGLProgram, programInterface: number, index: number, props: number): any;
getProgramResourceIndex(program: WebGLProgram, programInterface: number, name: string): number;
getProgramResourceLocation(program: WebGLProgram, programInterface: number, name: string): any;
getProgramResourceName(program: WebGLProgram, programInterface: number, index: number): string;
memoryBarrier(barriers: number): void;
memoryBarrierByRegion(barriers: number): void;
// Present in specification but not implemented:
// framebufferParameter(target: number, pname: number, param: number): void;
// getFramebufferParameter(target: number, pname: number): any;
// programUniform1i(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number): void;
// programUniform2i(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number): void;
// programUniform3i(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number): void;
// programUniform4i(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number, v3: number): void;
// programUniform1ui(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number): void;
// programUniform2ui(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number): void;
// programUniform3ui(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number): void;
// programUniform4ui(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number, v3: number): void;
// programUniform1f(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number): void;
// programUniform2f(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number): void;
// programUniform3f(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number): void;
// programUniform4f(program: WebGLProgram, location: WebGLUniformLocation | null, v0: number, v1: number, v2: number, v3: number): void;
// programUniform1iv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Int32Array | ArrayLike<number>): void;
// programUniform2iv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Int32Array | ArrayLike<number>): void;
// programUniform3iv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Int32Array | ArrayLike<number>): void;
// programUniform4iv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Int32Array | ArrayLike<number>): void;
// programUniform1uiv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Uint32Array | ArrayLike<number>): void;
// programUniform2uiv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Uint32Array | ArrayLike<number>): void;
// programUniform3uiv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Uint32Array | ArrayLike<number>): void;
// programUniform4uiv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Uint32Array | ArrayLike<number>): void;
// programUniform1fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Float32Array | ArrayLike<number>): void;
// programUniform2fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Float32Array | ArrayLike<number>): void;
// programUniform3fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Float32Array | ArrayLike<number>): void;
// programUniform4fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix2fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix3fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix4fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix2x3fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix3x2fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix2x4fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix4x2fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix3x4fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// programUniformMatrix4x3fv(program: WebGLProgram, location: WebGLUniformLocation | null, count: number, transpose: boolean, data: Float32Array | ArrayLike<number>): void;
// texStorage2DMultisample(target: number, samples: number, internalformat: number, width: number, height: number, fixedsamplelocations: boolean): void;
// getTexLevelParameter(target: number, level: number, pname: number): any;
// getMultisample(pname: number, index: number): any;
// sampleMask(index: number, mask: number): void;
// bindVertexBuffer(bindingindex: number, buffer: WebGLBuffer | null, offset: number, stride: number): void;
// vertexAttribFormat(attribindex: number, size: number, type: number, normalized: boolean, relativeoffset: number): void;
// vertexAttribIFormat(attribindex: number, size: number, type: number, relativeoffset: number): void;
// vertexAttribBinding(attribindex: number, bindingindex: number): void;
// vertexBindingDivisor(bindingindex: number, divisor: number): void;
}
declare var WebGL2ComputeRenderingContext: {
prototype: WebGL2ComputeRenderingContext;
new (): WebGL2ComputeRenderingContext;
// WebGL constants
readonly ACTIVE_ATTRIBUTES: number; // 35721
readonly ACTIVE_TEXTURE: number; // 34016
readonly ACTIVE_UNIFORMS: number; // 35718
readonly ALIASED_LINE_WIDTH_RANGE: number; // 33902
readonly ALIASED_POINT_SIZE_RANGE: number; // 33901
readonly ALPHA: number; // 6406
readonly ALPHA_BITS: number; // 3413
readonly ALWAYS: number; // 519
readonly ARRAY_BUFFER: number; // 34962
readonly ARRAY_BUFFER_BINDING: number; // 34964
readonly ATTACHED_SHADERS: number; // 35717
readonly BACK: number; // 1029
readonly BLEND: number; // 3042
readonly BLEND_COLOR: number; // 32773
readonly BLEND_DST_ALPHA: number; // 32970
readonly BLEND_DST_RGB: number; // 32968
readonly BLEND_EQUATION: number; // 32777
readonly BLEND_EQUATION_ALPHA: number; // 34877
readonly BLEND_EQUATION_RGB: number; // 32777
readonly BLEND_SRC_ALPHA: number; // 32971
readonly BLEND_SRC_RGB: number; // 32969
readonly BLUE_BITS: number; // 3412
readonly BOOL: number; // 35670
readonly BOOL_VEC2: number; // 35671
readonly BOOL_VEC3: number; // 35672
readonly BOOL_VEC4: number; // 35673
readonly BROWSER_DEFAULT_WEBGL: number; // 37444
readonly BUFFER_SIZE: number; // 34660
readonly BUFFER_USAGE: number; // 34661
readonly BYTE: number; // 5120
readonly CCW: number; // 2305
readonly CLAMP_TO_EDGE: number; // 33071
readonly COLOR_ATTACHMENT0: number; // 36064
readonly COLOR_BUFFER_BIT: number; // 16384
readonly COLOR_CLEAR_VALUE: number; // 3106
readonly COLOR_WRITEMASK: number; // 3107
readonly COMPILE_STATUS: number; // 35713
readonly COMPRESSED_TEXTURE_FORMATS: number; // 34467
readonly CONSTANT_ALPHA: number; // 32771
readonly CONSTANT_COLOR: number; // 32769
readonly CONTEXT_LOST_WEBGL: number; // 37442
readonly CULL_FACE: number; // 2884
readonly CULL_FACE_MODE: number; // 2885
readonly CURRENT_PROGRAM: number; // 35725
readonly CURRENT_VERTEX_ATTRIB: number; // 34342
readonly CW: number; // 2304
readonly DECR: number; // 7683
readonly DECR_WRAP: number; // 34056
readonly DELETE_STATUS: number; // 35712
readonly DEPTH_ATTACHMENT: number; // 36096
readonly DEPTH_BITS: number; // 3414
readonly DEPTH_BUFFER_BIT: number; // 256
readonly DEPTH_CLEAR_VALUE: number; // 2931
readonly DEPTH_COMPONENT: number; // 6402
readonly DEPTH_COMPONENT16: number; // 33189
readonly DEPTH_FUNC: number; // 2932
readonly DEPTH_RANGE: number; // 2928
readonly DEPTH_STENCIL: number; // 34041
readonly DEPTH_STENCIL_ATTACHMENT: number; // 33306
readonly DEPTH_TEST: number; // 2929
readonly DEPTH_WRITEMASK: number; // 2930
readonly DITHER: number; // 3024
readonly DONT_CARE: number; // 4352
readonly DST_ALPHA: number; // 772
readonly DST_COLOR: number; // 774
readonly DYNAMIC_DRAW: number; // 35048
readonly ELEMENT_ARRAY_BUFFER: number; // 34963
readonly ELEMENT_ARRAY_BUFFER_BINDING: number; // 34965
readonly EQUAL: number; // 514
readonly FASTEST: number; // 4353
readonly FLOAT: number; // 5126
readonly FLOAT_MAT2: number; // 35674
readonly FLOAT_MAT3: number; // 35675
readonly FLOAT_MAT4: number; // 35676
readonly FLOAT_VEC2: number; // 35664
readonly FLOAT_VEC3: number; // 35665
readonly FLOAT_VEC4: number; // 35666
readonly FRAGMENT_SHADER: number; // 35632
readonly FRAMEBUFFER: number; // 36160
readonly FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: number; // 36049
readonly FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: number; // 36048
readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: number; // 36051
readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: number; // 36050
readonly FRAMEBUFFER_BINDING: number; // 36006
readonly FRAMEBUFFER_COMPLETE: number; // 36053
readonly FRAMEBUFFER_INCOMPLETE_ATTACHMENT: number; // 36054
readonly FRAMEBUFFER_INCOMPLETE_DIMENSIONS: number; // 36057
readonly FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: number; // 36055
readonly FRAMEBUFFER_UNSUPPORTED: number; // 36061
readonly FRONT: number; // 1028
readonly FRONT_AND_BACK: number; // 1032
readonly FRONT_FACE: number; // 2886
readonly FUNC_ADD: number; // 32774
readonly FUNC_REVERSE_SUBTRACT: number; // 32779
readonly FUNC_SUBTRACT: number; // 32778
readonly GENERATE_MIPMAP_HINT: number; // 33170
readonly GEQUAL: number; // 518
readonly GREATER: number; // 516
readonly GREEN_BITS: number; // 3411
readonly HIGH_FLOAT: number; // 36338
readonly HIGH_INT: number; // 36341
readonly IMPLEMENTATION_COLOR_READ_FORMAT: number; // 35739
readonly IMPLEMENTATION_COLOR_READ_TYPE: number; // 35738
readonly INCR: number; // 7682
readonly INCR_WRAP: number; // 34055
readonly INT: number; // 5124
readonly INT_VEC2: number; // 35667
readonly INT_VEC3: number; // 35668
readonly INT_VEC4: number; // 35669
readonly INVALID_ENUM: number; // 1280
readonly INVALID_FRAMEBUFFER_OPERATION: number; // 1286
readonly INVALID_OPERATION: number; // 1282
readonly INVALID_VALUE: number; // 1281
readonly INVERT: number; // 5386
readonly KEEP: number; // 7680
readonly LEQUAL: number; // 515
readonly LESS: number; // 513
readonly LINEAR: number; // 9729
readonly LINEAR_MIPMAP_LINEAR: number; // 9987
readonly LINEAR_MIPMAP_NEAREST: number; // 9985
readonly LINES: number; // 1
readonly LINE_LOOP: number; // 2
readonly LINE_STRIP: number; // 3
readonly LINE_WIDTH: number; // 2849
readonly LINK_STATUS: number; // 35714
readonly LOW_FLOAT: number; // 36336
readonly LOW_INT: number; // 36339
readonly LUMINANCE: number; // 6409
readonly LUMINANCE_ALPHA: number; // 6410
readonly MAX_COMBINED_TEXTURE_IMAGE_UNITS: number; // 35661
readonly MAX_CUBE_MAP_TEXTURE_SIZE: number; // 34076
readonly MAX_FRAGMENT_UNIFORM_VECTORS: number; // 36349
readonly MAX_RENDERBUFFER_SIZE: number; // 34024
readonly MAX_TEXTURE_IMAGE_UNITS: number; // 34930
readonly MAX_TEXTURE_SIZE: number; // 3379
readonly MAX_VARYING_VECTORS: number; // 36348
readonly MAX_VERTEX_ATTRIBS: number; // 34921
readonly MAX_VERTEX_TEXTURE_IMAGE_UNITS: number; // 35660
readonly MAX_VERTEX_UNIFORM_VECTORS: number; // 36347
readonly MAX_VIEWPORT_DIMS: number; // 3386
readonly MEDIUM_FLOAT: number; // 36337
readonly MEDIUM_INT: number; // 36340
readonly MIRRORED_REPEAT: number; // 33648
readonly NEAREST: number; // 9728
readonly NEAREST_MIPMAP_LINEAR: number; // 9986
readonly NEAREST_MIPMAP_NEAREST: number; // 9984
readonly NEVER: number; // 512
readonly NICEST: number; // 4354
readonly NONE: number; // 0
readonly NOTEQUAL: number; // 517
readonly NO_ERROR: number; // 0
readonly ONE: number; // 1
readonly ONE_MINUS_CONSTANT_ALPHA: number; // 32772
readonly ONE_MINUS_CONSTANT_COLOR: number; // 32770
readonly ONE_MINUS_DST_ALPHA: number; // 773
readonly ONE_MINUS_DST_COLOR: number; // 775
readonly ONE_MINUS_SRC_ALPHA: number; // 771
readonly ONE_MINUS_SRC_COLOR: number; // 769
readonly OUT_OF_MEMORY: number; // 1285
readonly PACK_ALIGNMENT: number; // 3333
readonly POINTS: number; // 0
readonly POLYGON_OFFSET_FACTOR: number; // 32824
readonly POLYGON_OFFSET_FILL: number; // 32823
readonly POLYGON_OFFSET_UNITS: number; // 10752
readonly RED_BITS: number; // 3410
readonly RENDERBUFFER: number; // 36161
readonly RENDERBUFFER_ALPHA_SIZE: number; // 36179
readonly RENDERBUFFER_BINDING: number; // 36007
readonly RENDERBUFFER_BLUE_SIZE: number; // 36178
readonly RENDERBUFFER_DEPTH_SIZE: number; // 36180
readonly RENDERBUFFER_GREEN_SIZE: number; // 36177
readonly RENDERBUFFER_HEIGHT: number; // 36163
readonly RENDERBUFFER_INTERNAL_FORMAT: number; // 36164
readonly RENDERBUFFER_RED_SIZE: number; // 36176
readonly RENDERBUFFER_STENCIL_SIZE: number; // 36181
readonly RENDERBUFFER_WIDTH: number; // 36162
readonly RENDERER: number; // 7937
readonly REPEAT: number; // 10497
readonly REPLACE: number; // 7681
readonly RGB: number; // 6407
readonly RGB5_A1: number; // 32855
readonly RGB565: number; // 36194
readonly RGBA: number; // 6408
readonly RGBA4: number; // 32854
readonly SAMPLER_2D: number; // 35678
readonly SAMPLER_CUBE: number; // 35680
readonly SAMPLES: number; // 32937
readonly SAMPLE_ALPHA_TO_COVERAGE: number; // 32926
readonly SAMPLE_BUFFERS: number; // 32936
readonly SAMPLE_COVERAGE: number; // 32928
readonly SAMPLE_COVERAGE_INVERT: number; // 32939
readonly SAMPLE_COVERAGE_VALUE: number; // 32938
readonly SCISSOR_BOX: number; // 3088
readonly SCISSOR_TEST: number; // 3089
readonly SHADER_TYPE: number; // 35663
readonly SHADING_LANGUAGE_VERSION: number; // 35724
readonly SHORT: number; // 5122
readonly SRC_ALPHA: number; // 770
readonly SRC_ALPHA_SATURATE: number; // 776
readonly SRC_COLOR: number; // 768
readonly STATIC_DRAW: number; // 35044
readonly STENCIL_ATTACHMENT: number; // 36128
readonly STENCIL_BACK_FAIL: number; // 34817
readonly STENCIL_BACK_FUNC: number; // 34816
readonly STENCIL_BACK_PASS_DEPTH_FAIL: number; // 34818
readonly STENCIL_BACK_PASS_DEPTH_PASS: number; // 34819
readonly STENCIL_BACK_REF: number; // 36003
readonly STENCIL_BACK_VALUE_MASK: number; // 36004
readonly STENCIL_BACK_WRITEMASK: number; // 36005
readonly STENCIL_BITS: number; // 3415
readonly STENCIL_BUFFER_BIT: number; // 1024
readonly STENCIL_CLEAR_VALUE: number; // 2961
readonly STENCIL_FAIL: number; // 2964
readonly STENCIL_FUNC: number; // 2962
readonly STENCIL_INDEX8: number; // 36168
readonly STENCIL_PASS_DEPTH_FAIL: number; // 2965
readonly STENCIL_PASS_DEPTH_PASS: number; // 2966
readonly STENCIL_REF: number; // 2967
readonly STENCIL_TEST: number; // 2960
readonly STENCIL_VALUE_MASK: number; // 2963
readonly STENCIL_WRITEMASK: number; // 2968
readonly STREAM_DRAW: number; // 35040
readonly SUBPIXEL_BITS: number; // 3408
readonly TEXTURE: number; // 5890
readonly TEXTURE0: number; // 33984
readonly TEXTURE1: number; // 33985
readonly TEXTURE2: number; // 33986
readonly TEXTURE3: number; // 33987
readonly TEXTURE4: number; // 33988
readonly TEXTURE5: number; // 33989
readonly TEXTURE6: number; // 33990
readonly TEXTURE7: number; // 33991
readonly TEXTURE8: number; // 33992
readonly TEXTURE9: number; // 33993
readonly TEXTURE10: number; // 33994
readonly TEXTURE11: number; // 33995
readonly TEXTURE12: number; // 33996
readonly TEXTURE13: number; // 33997
readonly TEXTURE14: number; // 33998
readonly TEXTURE15: number; // 33999
readonly TEXTURE16: number; // 34000
readonly TEXTURE17: number; // 34001
readonly TEXTURE18: number; // 34002
readonly TEXTURE19: number; // 34003
readonly TEXTURE20: number; // 34004
readonly TEXTURE21: number; // 34005
readonly TEXTURE22: number; // 34006
readonly TEXTURE23: number; // 34007
readonly TEXTURE24: number; // 34008
readonly TEXTURE25: number; // 34009
readonly TEXTURE26: number; // 34010
readonly TEXTURE27: number; // 34011
readonly TEXTURE28: number; // 34012
readonly TEXTURE29: number; // 34013
readonly TEXTURE30: number; // 34014
readonly TEXTURE31: number; // 34015
readonly TEXTURE_2D: number; // 3553
readonly TEXTURE_BINDING_2D: number; // 32873
readonly TEXTURE_BINDING_CUBE_MAP: number; // 34068
readonly TEXTURE_CUBE_MAP: number; // 34067
readonly TEXTURE_CUBE_MAP_NEGATIVE_X: number; // 34070
readonly TEXTURE_CUBE_MAP_NEGATIVE_Y: number; // 34072
readonly TEXTURE_CUBE_MAP_NEGATIVE_Z: number; // 34074
readonly TEXTURE_CUBE_MAP_POSITIVE_X: number; // 34069
readonly TEXTURE_CUBE_MAP_POSITIVE_Y: number; // 34071
readonly TEXTURE_CUBE_MAP_POSITIVE_Z: number; // 34073
readonly TEXTURE_MAG_FILTER: number; // 10240
readonly TEXTURE_MIN_FILTER: number; // 10241
readonly TEXTURE_WRAP_S: number; // 10242
readonly TEXTURE_WRAP_T: number; // 10243
readonly TRIANGLES: number; // 4
readonly TRIANGLE_FAN: number; // 6
readonly TRIANGLE_STRIP: number; // 5
readonly UNPACK_ALIGNMENT: number; // 3317
readonly UNPACK_COLORSPACE_CONVERSION_WEBGL: number; // 37443
readonly UNPACK_FLIP_Y_WEBGL: number; // 37440
readonly UNPACK_PREMULTIPLY_ALPHA_WEBGL: number; // 37441
readonly UNSIGNED_BYTE: number; // 5121
readonly UNSIGNED_INT: number; // 5125
readonly UNSIGNED_SHORT: number; // 5123
readonly UNSIGNED_SHORT_4_4_4_4: number; // 32819
readonly UNSIGNED_SHORT_5_5_5_1: number; // 32820
readonly UNSIGNED_SHORT_5_6_5: number; // 33635
readonly VALIDATE_STATUS: number; // 35715
readonly VENDOR: number; // 7936
readonly VERSION: number; // 7938
readonly VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: number; // 34975
readonly VERTEX_ATTRIB_ARRAY_ENABLED: number; // 34338
readonly VERTEX_ATTRIB_ARRAY_NORMALIZED: number; // 34922
readonly VERTEX_ATTRIB_ARRAY_POINTER: number; // 34373
readonly VERTEX_ATTRIB_ARRAY_SIZE: number; // 34339
readonly VERTEX_ATTRIB_ARRAY_STRIDE: number; // 34340
readonly VERTEX_ATTRIB_ARRAY_TYPE: number; // 34341
readonly VERTEX_SHADER: number; // 35633
readonly VIEWPORT: number; // 2978
readonly ZERO: number; // 0
// WebGL2 constants
readonly ACTIVE_UNIFORM_BLOCKS: number; // 35382
readonly ALREADY_SIGNALED: number; // 37146
readonly ANY_SAMPLES_PASSED: number; // 35887
readonly ANY_SAMPLES_PASSED_CONSERVATIVE: number; // 36202
readonly COLOR: number; // 6144
readonly COLOR_ATTACHMENT1: number; // 36065
readonly COLOR_ATTACHMENT2: number; // 36066
readonly COLOR_ATTACHMENT3: number; // 36067
readonly COLOR_ATTACHMENT4: number; // 36068
readonly COLOR_ATTACHMENT5: number; // 36069
readonly COLOR_ATTACHMENT6: number; // 36070
readonly COLOR_ATTACHMENT7: number; // 36071
readonly COLOR_ATTACHMENT8: number; // 36072
readonly COLOR_ATTACHMENT9: number; // 36073
readonly COLOR_ATTACHMENT10: number; // 36074
readonly COLOR_ATTACHMENT11: number; // 36075
readonly COLOR_ATTACHMENT12: number; // 36076
readonly COLOR_ATTACHMENT13: number; // 36077
readonly COLOR_ATTACHMENT14: number; // 36078
readonly COLOR_ATTACHMENT15: number; // 36079
readonly COMPARE_REF_TO_TEXTURE: number; // 34894
readonly CONDITION_SATISFIED: number; // 37148
readonly COPY_READ_BUFFER: number; // 36662
readonly COPY_READ_BUFFER_BINDING: number; // 36662
readonly COPY_WRITE_BUFFER: number; // 36663
readonly COPY_WRITE_BUFFER_BINDING: number; // 36663
readonly CURRENT_QUERY: number; // 34917
readonly DEPTH: number; // 6145
readonly DEPTH24_STENCIL8: number; // 35056
readonly DEPTH32F_STENCIL8: number; // 36013
readonly DEPTH_COMPONENT24: number; // 33190
readonly DEPTH_COMPONENT32F: number; // 36012
readonly DRAW_BUFFER0: number; // 34853
readonly DRAW_BUFFER1: number; // 34854
readonly DRAW_BUFFER2: number; // 34855
readonly DRAW_BUFFER3: number; // 34856
readonly DRAW_BUFFER4: number; // 34857
readonly DRAW_BUFFER5: number; // 34858
readonly DRAW_BUFFER6: number; // 34859
readonly DRAW_BUFFER7: number; // 34860
readonly DRAW_BUFFER8: number; // 34861
readonly DRAW_BUFFER9: number; // 34862
readonly DRAW_BUFFER10: number; // 34863
readonly DRAW_BUFFER11: number; // 34864
readonly DRAW_BUFFER12: number; // 34865
readonly DRAW_BUFFER13: number; // 34866
readonly DRAW_BUFFER14: number; // 34867
readonly DRAW_BUFFER15: number; // 34868
readonly DRAW_FRAMEBUFFER: number; // 36009
readonly DRAW_FRAMEBUFFER_BINDING: number; // 36006
readonly DYNAMIC_COPY: number; // 35050
readonly DYNAMIC_READ: number; // 35049
readonly FLOAT_32_UNSIGNED_INT_24_8_REV: number; // 36269
readonly FLOAT_MAT2x3: number; // 35685
readonly FLOAT_MAT2x4: number; // 35686
readonly FLOAT_MAT3x2: number; // 35687
readonly FLOAT_MAT3x4: number; // 35688
readonly FLOAT_MAT4x2: number; // 35689
readonly FLOAT_MAT4x3: number; // 35690
readonly FRAGMENT_SHADER_DERIVATIVE_HINT: number; // 35723
readonly FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: number; // 33301
readonly FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: number; // 33300
readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: number; // 33296
readonly FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: number; // 33297
readonly FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: number; // 33302
readonly FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: number; // 33299
readonly FRAMEBUFFER_ATTACHMENT_RED_SIZE: number; // 33298
readonly FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: number; // 33303
readonly FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: number; // 36052
readonly FRAMEBUFFER_DEFAULT: number; // 33304
readonly FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: number; // 36182
readonly HALF_FLOAT: number; // 5131
readonly INTERLEAVED_ATTRIBS: number; // 35980
readonly INT_2_10_10_10_REV: number; // 36255
readonly INT_SAMPLER_2D: number; // 36298
readonly INT_SAMPLER_2D_ARRAY: number; // 36303
readonly INT_SAMPLER_3D: number; // 36299
readonly INT_SAMPLER_CUBE: number; // 36300
readonly INVALID_INDEX: number; // 4294967295
readonly MAX: number; // 32776
readonly MAX_3D_TEXTURE_SIZE: number; // 32883
readonly MAX_ARRAY_TEXTURE_LAYERS: number; // 35071
readonly MAX_CLIENT_WAIT_TIMEOUT_WEBGL: number; // 37447
readonly MAX_COLOR_ATTACHMENTS: number; // 36063
readonly MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: number; // 35379
readonly MAX_COMBINED_UNIFORM_BLOCKS: number; // 35374
readonly MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: number; // 35377
readonly MAX_DRAW_BUFFERS: number; // 34852
readonly MAX_ELEMENTS_INDICES: number; // 33001
readonly MAX_ELEMENTS_VERTICES: number; // 33000
readonly MAX_ELEMENT_INDEX: number; // 36203
readonly MAX_FRAGMENT_INPUT_COMPONENTS: number; // 37157
readonly MAX_FRAGMENT_UNIFORM_BLOCKS: number; // 35373
readonly MAX_FRAGMENT_UNIFORM_COMPONENTS: number; // 35657
readonly MAX_PROGRAM_TEXEL_OFFSET: number; // 35077
readonly MAX_SAMPLES: number; // 36183
readonly MAX_SERVER_WAIT_TIMEOUT: number; // 37137
readonly MAX_TEXTURE_LOD_BIAS: number; // 34045
readonly MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: number; // 35978
readonly MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: number; // 35979
readonly MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: number; // 35968
readonly MAX_UNIFORM_BLOCK_SIZE: number; // 35376
readonly MAX_UNIFORM_BUFFER_BINDINGS: number; // 35375
readonly MAX_VARYING_COMPONENTS: number; // 35659
readonly MAX_VERTEX_OUTPUT_COMPONENTS: number; // 37154
readonly MAX_VERTEX_UNIFORM_BLOCKS: number; // 35371
readonly MAX_VERTEX_UNIFORM_COMPONENTS: number; // 35658
readonly MIN: number; // 32775
readonly MIN_PROGRAM_TEXEL_OFFSET: number; // 35076
readonly OBJECT_TYPE: number; // 37138
readonly PACK_ROW_LENGTH: number; // 3330
readonly PACK_SKIP_PIXELS: number; // 3332
readonly PACK_SKIP_ROWS: number; // 3331
readonly PIXEL_PACK_BUFFER: number; // 35051
readonly PIXEL_PACK_BUFFER_BINDING: number; // 35053
readonly PIXEL_UNPACK_BUFFER: number; // 35052
readonly PIXEL_UNPACK_BUFFER_BINDING: number; // 35055
readonly QUERY_RESULT: number; // 34918
readonly QUERY_RESULT_AVAILABLE: number; // 34919
readonly R8: number; // 33321
readonly R8I: number; // 33329
readonly R8UI: number; // 33330
readonly R8_SNORM: number; // 36756
readonly R11F_G11F_B10F: number; // 35898
readonly R16F: number; // 33325
readonly R16I: number; // 33331
readonly R16UI: number; // 33332
readonly R32F: number; // 33326
readonly R32I: number; // 33333
readonly R32UI: number; // 33334
readonly RASTERIZER_DISCARD: number; // 35977
readonly READ_BUFFER: number; // 3074
readonly READ_FRAMEBUFFER: number; // 36008
readonly READ_FRAMEBUFFER_BINDING: number; // 36010
readonly RED: number; // 6403
readonly RED_INTEGER: number; // 36244
readonly RENDERBUFFER_SAMPLES: number; // 36011
readonly RG: number; // 33319
readonly RG8: number; // 33323
readonly RG8I: number; // 33335
readonly RG8UI: number; // 33336
readonly RG8_SNORM: number; // 36757
readonly RG16F: number; // 33327
readonly RG16I: number; // 33337
readonly RG16UI: number; // 33338
readonly RG32F: number; // 33328
readonly RG32I: number; // 33339
readonly RG32UI: number; // 33340
readonly RGB8: number; // 32849
readonly RGB8I: number; // 36239
readonly RGB8UI: number; // 36221
readonly RGB8_SNORM: number; // 36758
readonly RGB9_E5: number; // 35901
readonly RGB10_A2: number; // 32857
readonly RGB10_A2UI: number; // 36975
readonly RGB16F: number; // 34843
readonly RGB16I: number; // 36233
readonly RGB16UI: number; // 36215
readonly RGB32F: number; // 34837
readonly RGB32I: number; // 36227
readonly RGB32UI: number; // 36209
readonly RGBA8: number; // 32856
readonly RGBA8I: number; // 36238
readonly RGBA8UI: number; // 36220
readonly RGBA8_SNORM: number; // 36759
readonly RGBA16F: number; // 34842
readonly RGBA16I: number; // 36232
readonly RGBA16UI: number; // 36214
readonly RGBA32F: number; // 34836
readonly RGBA32I: number; // 36226
readonly RGBA32UI: number; // 36208
readonly RGBA_INTEGER: number; // 36249
readonly RGB_INTEGER: number; // 36248
readonly RG_INTEGER: number; // 33320
readonly SAMPLER_2D_ARRAY: number; // 36289
readonly SAMPLER_2D_ARRAY_SHADOW: number; // 36292
readonly SAMPLER_2D_SHADOW: number; // 35682
readonly SAMPLER_3D: number; // 35679
readonly SAMPLER_BINDING: number; // 35097
readonly SAMPLER_CUBE_SHADOW: number; // 36293
readonly SEPARATE_ATTRIBS: number; // 35981
readonly SIGNALED: number; // 37145
readonly SIGNED_NORMALIZED: number; // 36764
readonly SRGB: number; // 35904
readonly SRGB8: number; // 35905
readonly SRGB8_ALPHA8: number; // 35907
readonly STATIC_COPY: number; // 35046
readonly STATIC_READ: number; // 35045
readonly STENCIL: number; // 6146
readonly STREAM_COPY: number; // 35042
readonly STREAM_READ: number; // 35041
readonly SYNC_CONDITION: number; // 37139
readonly SYNC_FENCE: number; // 37142
readonly SYNC_FLAGS: number; // 37141
readonly SYNC_FLUSH_COMMANDS_BIT: number; // 1
readonly SYNC_GPU_COMMANDS_COMPLETE: number; // 37143
readonly SYNC_STATUS: number; // 37140
readonly TEXTURE_2D_ARRAY: number; // 35866
readonly TEXTURE_3D: number; // 32879
readonly TEXTURE_BASE_LEVEL: number; // 33084
readonly TEXTURE_BINDING_2D_ARRAY: number; // 35869
readonly TEXTURE_BINDING_3D: number; // 32874
readonly TEXTURE_COMPARE_FUNC: number; // 34893
readonly TEXTURE_COMPARE_MODE: number; // 34892
readonly TEXTURE_IMMUTABLE_FORMAT: number; // 37167
readonly TEXTURE_IMMUTABLE_LEVELS: number; // 33503
readonly TEXTURE_MAX_LEVEL: number; // 33085
readonly TEXTURE_MAX_LOD: number; // 33083
readonly TEXTURE_MIN_LOD: number; // 33082
readonly TEXTURE_WRAP_R: number; // 32882
readonly TIMEOUT_EXPIRED: number; // 37147
readonly TIMEOUT_IGNORED: number; // -1
readonly TRANSFORM_FEEDBACK: number; // 36386
readonly TRANSFORM_FEEDBACK_ACTIVE: number; // 36388
readonly TRANSFORM_FEEDBACK_BINDING: number; // 36389
readonly TRANSFORM_FEEDBACK_BUFFER: number; // 35982
readonly TRANSFORM_FEEDBACK_BUFFER_BINDING: number; // 35983
readonly TRANSFORM_FEEDBACK_BUFFER_MODE: number; // 35967
readonly TRANSFORM_FEEDBACK_BUFFER_SIZE: number; // 35973
readonly TRANSFORM_FEEDBACK_BUFFER_START: number; // 35972
readonly TRANSFORM_FEEDBACK_PAUSED: number; // 36387
readonly TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: number; // 35976
readonly TRANSFORM_FEEDBACK_VARYINGS: number; // 35971
readonly UNIFORM_ARRAY_STRIDE: number; // 35388
readonly UNIFORM_BLOCK_ACTIVE_UNIFORMS: number; // 35394
readonly UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES: number; // 35395
readonly UNIFORM_BLOCK_BINDING: number; // 35391
readonly UNIFORM_BLOCK_DATA_SIZE: number; // 35392
readonly UNIFORM_BLOCK_INDEX: number; // 35386
readonly UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER: number; // 35398
readonly UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER: number; // 35396
readonly UNIFORM_BUFFER: number; // 35345
readonly UNIFORM_BUFFER_BINDING: number; // 35368
readonly UNIFORM_BUFFER_OFFSET_ALIGNMENT: number; // 35380
readonly UNIFORM_BUFFER_SIZE: number; // 35370
readonly UNIFORM_BUFFER_START: number; // 35369
readonly UNIFORM_IS_ROW_MAJOR: number; // 35390
readonly UNIFORM_MATRIX_STRIDE: number; // 35389
readonly UNIFORM_OFFSET: number; // 35387
readonly UNIFORM_SIZE: number; // 35384
readonly UNIFORM_TYPE: number; // 35383
readonly UNPACK_IMAGE_HEIGHT: number; // 32878
readonly UNPACK_ROW_LENGTH: number; // 3314
readonly UNPACK_SKIP_IMAGES: number; // 32877
readonly UNPACK_SKIP_PIXELS: number; // 3316
readonly UNPACK_SKIP_ROWS: number; // 3315
readonly UNSIGNALED: number; // 37144
readonly UNSIGNED_INT_2_10_10_10_REV: number; // 33640
readonly UNSIGNED_INT_5_9_9_9_REV: number; // 35902
readonly UNSIGNED_INT_10F_11F_11F_REV: number; // 35899
readonly UNSIGNED_INT_24_8: number; // 34042
readonly UNSIGNED_INT_SAMPLER_2D: number; // 36306
readonly UNSIGNED_INT_SAMPLER_2D_ARRAY: number; // 36311
readonly UNSIGNED_INT_SAMPLER_3D: number; // 36307
readonly UNSIGNED_INT_SAMPLER_CUBE: number; // 36308
readonly UNSIGNED_INT_VEC2: number; // 36294
readonly UNSIGNED_INT_VEC3: number; // 36295
readonly UNSIGNED_INT_VEC4: number; // 36296
readonly UNSIGNED_NORMALIZED: number; // 35863
readonly VERTEX_ARRAY_BINDING: number; // 34229
readonly VERTEX_ATTRIB_ARRAY_DIVISOR: number; // 35070
readonly VERTEX_ATTRIB_ARRAY_INTEGER: number; // 35069
readonly WAIT_FAILED: number; // 37149
// WebGL2 Compute constants
readonly ACTIVE_ATOMIC_COUNTER_BUFFERS: number; // 37593
readonly ACTIVE_RESOURCES: number; // 37621
readonly ACTIVE_VARIABLES: number; // 37637
readonly ALL_BARRIER_BITS: number; // 4294967295
readonly ARRAY_SIZE: number; // 37627
readonly ARRAY_STRIDE: number; // 37630
readonly ATOMIC_COUNTER_BARRIER_BIT: number; // 4096
readonly ATOMIC_COUNTER_BUFFER: number; // 37568
readonly ATOMIC_COUNTER_BUFFER_BINDING: number; // 37569
readonly ATOMIC_COUNTER_BUFFER_INDEX: number; // 37633
readonly ATOMIC_COUNTER_BUFFER_SIZE: number; // 37571
readonly ATOMIC_COUNTER_BUFFER_START: number; // 37570
readonly BLOCK_INDEX: number; // 37629
readonly BUFFER_BINDING: number; // 37634
readonly BUFFER_DATA_SIZE: number; // 37635
readonly BUFFER_UPDATE_BARRIER_BIT: number; // 512
readonly BUFFER_VARIABLE: number; // 37605
readonly COMMAND_BARRIER_BIT: number; // 64
readonly COMPUTE_SHADER: number; // 37305
readonly DISPATCH_INDIRECT_BUFFER: number; // 37102
readonly DISPATCH_INDIRECT_BUFFER_BINDING: number; // 37103
readonly DRAW_INDIRECT_BUFFER: number; // 36671
readonly DRAW_INDIRECT_BUFFER_BINDING: number; // 36675
readonly ELEMENT_ARRAY_BARRIER_BIT: number; // 2
readonly FRAMEBUFFER_BARRIER_BIT: number; // 1024
readonly IS_ROW_MAJOR: number; // 37632
readonly LOCATION: number; // 37646
readonly MATRIX_STRIDE: number; // 37631
readonly MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: number; // 37596
readonly MAX_ATOMIC_COUNTER_BUFFER_SIZE: number; // 37592
readonly MAX_COMBINED_ATOMIC_COUNTERS: number; // 37591
readonly MAX_COMBINED_ATOMIC_COUNTER_BUFFERS: number; // 37585
readonly MAX_COMBINED_SHADER_STORAGE_BLOCKS: number; // 37084
readonly MAX_COMPUTE_ATOMIC_COUNTERS: number; // 33381
readonly MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS: number; // 33380
readonly MAX_COMPUTE_IMAGE_UNIFORMS: number; // 37309
readonly MAX_COMPUTE_SHADER_STORAGE_BLOCKS: number; // 37083
readonly MAX_COMPUTE_SHARED_MEMORY_SIZE: number; // 33378
readonly MAX_COMPUTE_TEXTURE_IMAGE_UNITS: number; // 37308
readonly MAX_COMPUTE_UNIFORM_BLOCKS: number; // 37307
readonly MAX_COMPUTE_UNIFORM_COMPONENTS: number; // 33379
readonly MAX_COMPUTE_WORK_GROUP_COUNT: number; // 37310
readonly MAX_COMPUTE_WORK_GROUP_INVOCATIONS: number; // 37099
readonly MAX_COMPUTE_WORK_GROUP_SIZE: number; // 37311
readonly MAX_FRAGMENT_ATOMIC_COUNTERS: number; // 37590
readonly MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS: number; // 37584
readonly MAX_FRAGMENT_SHADER_STORAGE_BLOCKS: number; // 37082
readonly MAX_NAME_LENGTH: number; // 37622
readonly MAX_NUM_ACTIVE_VARIABLES: number; // 37623
readonly MAX_SHADER_STORAGE_BLOCK_SIZE: number; // 37086
readonly MAX_SHADER_STORAGE_BUFFER_BINDINGS: number; // 37085
readonly MAX_VERTEX_ATOMIC_COUNTERS: number; // 37586
readonly MAX_VERTEX_ATOMIC_COUNTER_BUFFERS: number; // 37580
readonly MAX_VERTEX_SHADER_STORAGE_BLOCKS: number; // 37078
readonly NAME_LENGTH: number; // 37625
readonly NUM_ACTIVE_VARIABLES: number; // 37636
readonly OFFSET: number; // 37628
readonly PIXEL_BUFFER_BARRIER_BIT: number; // 128
readonly PROGRAM_INPUT: number; // 37603
readonly PROGRAM_OUTPUT: number; // 37604
readonly READ_ONLY: number; // 35000
readonly READ_WRITE: number; // 35002
readonly REFERENCED_BY_COMPUTE_SHADER: number; // 37643
readonly REFERENCED_BY_FRAGMENT_SHADER: number; // 37642
readonly REFERENCED_BY_VERTEX_SHADER: number; // 37638
readonly SHADER_IMAGE_ACCESS_BARRIER_BIT: number; // 32
readonly SHADER_STORAGE_BARRIER_BIT: number; // 8192
readonly SHADER_STORAGE_BLOCK: number; // 37606
readonly SHADER_STORAGE_BUFFER: number; // 37074
readonly SHADER_STORAGE_BUFFER_BINDING: number; // 37075
readonly SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: number; // 37087
readonly SHADER_STORAGE_BUFFER_SIZE: number; // 37077
readonly SHADER_STORAGE_BUFFER_START: number; // 37076
readonly TEXTURE_FETCH_BARRIER_BIT: number; // 8
readonly TEXTURE_UPDATE_BARRIER_BIT: number; // 256
readonly TOP_LEVEL_ARRAY_SIZE: number; // 37644
readonly TOP_LEVEL_ARRAY_STRIDE: number; // 37645
readonly TRANSFORM_FEEDBACK_BARRIER_BIT: number; // 2048
readonly TRANSFORM_FEEDBACK_VARYING: number; // 37620
readonly TYPE: number; // 37626
readonly UNIFORM: number; // 37601
readonly UNIFORM_BARRIER_BIT: number; // 4
readonly UNIFORM_BLOCK: number; // 37602
readonly UNSIGNED_INT_ATOMIC_COUNTER: number; // 37595
readonly VERTEX_ATTRIB_ARRAY_BARRIER_BIT: number; // 1
readonly WRITE_ONLY: number; // 35001
}; | the_stack |
import { BaseResource, CloudError } from "ms-rest-azure";
import * as moment from "moment";
export {
BaseResource,
CloudError
};
/**
* ARM resource.
*/
export interface Resource extends BaseResource {
/**
* Resource ID.
*/
readonly id?: string;
/**
* Resource name.
*/
readonly name?: string;
/**
* Resource type.
*/
readonly type?: string;
}
/**
* ARM proxy resource.
*/
export interface ProxyResource extends Resource {
}
/**
* A recoverable database
*/
export interface RecoverableDatabase extends ProxyResource {
/**
* The edition of the database
*/
readonly edition?: string;
/**
* The service level objective name of the database
*/
readonly serviceLevelObjective?: string;
/**
* The elastic pool name of the database
*/
readonly elasticPoolName?: string;
/**
* The last available backup date of the database (ISO8601 format)
*/
readonly lastAvailableBackupDate?: Date;
}
/**
* A restorable dropped database
*/
export interface RestorableDroppedDatabase extends ProxyResource {
/**
* The geo-location where the resource lives
*/
readonly location?: string;
/**
* The name of the database
*/
readonly databaseName?: string;
/**
* The edition of the database
*/
readonly edition?: string;
/**
* The max size in bytes of the database
*/
readonly maxSizeBytes?: string;
/**
* The service level objective name of the database
*/
readonly serviceLevelObjective?: string;
/**
* The elastic pool name of the database
*/
readonly elasticPoolName?: string;
/**
* The creation date of the database (ISO8601 format)
*/
readonly creationDate?: Date;
/**
* The deletion date of the database (ISO8601 format)
*/
readonly deletionDate?: Date;
/**
* The earliest restore date of the database (ISO8601 format)
*/
readonly earliestRestoreDate?: Date;
}
/**
* ARM tracked top level resource.
*/
export interface TrackedResource extends Resource {
/**
* Resource location.
*/
location: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* A request to check whether the specified name for a resource is available.
*/
export interface CheckNameAvailabilityRequest {
/**
* The name whose availability is to be checked.
*/
name: string;
}
/**
* A response indicating whether the specified name for a resource is available.
*/
export interface CheckNameAvailabilityResponse {
/**
* True if the name is available, otherwise false.
*/
readonly available?: boolean;
/**
* A message explaining why the name is unavailable. Will be null if the name is available.
*/
readonly message?: string;
/**
* The name whose availability was checked.
*/
readonly name?: string;
/**
* The reason code explaining why the name is unavailable. Will be null if the name is available.
* Possible values include: 'Invalid', 'AlreadyExists'
*/
readonly reason?: string;
}
/**
* A server secure connection policy.
*/
export interface ServerConnectionPolicy extends ProxyResource {
/**
* Metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* Resource location.
*/
readonly location?: string;
/**
* The server connection type. Possible values include: 'Default', 'Proxy', 'Redirect'
*/
connectionType: string;
}
/**
* Contains information about a database Threat Detection policy.
*/
export interface DatabaseSecurityAlertPolicy extends ProxyResource {
/**
* The geo-location where the resource lives
*/
location?: string;
/**
* Resource kind.
*/
readonly kind?: string;
/**
* Specifies the state of the policy. If state is Enabled, storageEndpoint and
* storageAccountAccessKey are required. Possible values include: 'New', 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies the semicolon-separated list of alerts that are disabled, or empty string to disable
* no alerts. Possible values: Sql_Injection; Sql_Injection_Vulnerability; Access_Anomaly;
* Data_Exfiltration; Unsafe_Action.
*/
disabledAlerts?: string;
/**
* Specifies the semicolon-separated list of e-mail addresses to which the alert is sent.
*/
emailAddresses?: string;
/**
* Specifies that the alert is sent to the account administrators. Possible values include:
* 'Enabled', 'Disabled'
*/
emailAccountAdmins?: string;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob
* storage will hold all Threat Detection audit logs. If state is Enabled, storageEndpoint is
* required.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the Threat Detection audit storage account. If state is
* Enabled, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the Threat Detection audit logs.
*/
retentionDays?: number;
/**
* Specifies whether to use the default server policy. Possible values include: 'Enabled',
* 'Disabled'
*/
useServerDefault?: string;
}
/**
* Represents a database data masking policy.
*/
export interface DataMaskingPolicy extends ProxyResource {
/**
* The state of the data masking policy. Possible values include: 'Disabled', 'Enabled'
*/
dataMaskingState: string;
/**
* The list of the exempt principals. Specifies the semicolon-separated list of database users
* for which the data masking policy does not apply. The specified users receive data results
* without masking for all of the database queries.
*/
exemptPrincipals?: string;
/**
* The list of the application principals. This is a legacy parameter and is no longer used.
*/
readonly applicationPrincipals?: string;
/**
* The masking level. This is a legacy parameter and is no longer used.
*/
readonly maskingLevel?: string;
/**
* The location of the data masking policy.
*/
readonly location?: string;
/**
* The kind of data masking policy. Metadata, used for Azure portal.
*/
readonly kind?: string;
}
/**
* Represents a database data masking rule.
*/
export interface DataMaskingRule extends ProxyResource {
/**
* The rule Id.
*/
readonly dataMaskingRuleId?: string;
/**
* The alias name. This is a legacy parameter and is no longer used.
*/
aliasName?: string;
/**
* The rule state. Used to delete a rule. To delete an existing rule, specify the schemaName,
* tableName, columnName, maskingFunction, and specify ruleState as disabled. However, if the
* rule doesn't already exist, the rule will be created with ruleState set to enabled, regardless
* of the provided value of ruleState. Possible values include: 'Disabled', 'Enabled'
*/
ruleState?: string;
/**
* The schema name on which the data masking rule is applied.
*/
schemaName: string;
/**
* The table name on which the data masking rule is applied.
*/
tableName: string;
/**
* The column name on which the data masking rule is applied.
*/
columnName: string;
/**
* The masking function that is used for the data masking rule. Possible values include:
* 'Default', 'CCN', 'Email', 'Number', 'SSN', 'Text'
*/
maskingFunction: string;
/**
* The numberFrom property of the masking rule. Required if maskingFunction is set to Number,
* otherwise this parameter will be ignored.
*/
numberFrom?: string;
/**
* The numberTo property of the data masking rule. Required if maskingFunction is set to Number,
* otherwise this parameter will be ignored.
*/
numberTo?: string;
/**
* If maskingFunction is set to Text, the number of characters to show unmasked in the beginning
* of the string. Otherwise, this parameter will be ignored.
*/
prefixSize?: string;
/**
* If maskingFunction is set to Text, the number of characters to show unmasked at the end of the
* string. Otherwise, this parameter will be ignored.
*/
suffixSize?: string;
/**
* If maskingFunction is set to Text, the character to use for masking the unexposed part of the
* string. Otherwise, this parameter will be ignored.
*/
replacementString?: string;
/**
* The location of the data masking rule.
*/
readonly location?: string;
/**
* The kind of Data Masking Rule. Metadata, used for Azure portal.
*/
readonly kind?: string;
}
/**
* Represents a server firewall rule.
*/
export interface FirewallRule extends ProxyResource {
/**
* Kind of server that contains this firewall rule.
*/
readonly kind?: string;
/**
* Location of the server that contains this firewall rule.
*/
readonly location?: string;
/**
* The start IP address of the firewall rule. Must be IPv4 format. Use value '0.0.0.0' to
* represent all Azure-internal IP addresses.
*/
startIpAddress: string;
/**
* The end IP address of the firewall rule. Must be IPv4 format. Must be greater than or equal to
* startIpAddress. Use value '0.0.0.0' to represent all Azure-internal IP addresses.
*/
endIpAddress: string;
}
/**
* A database geo backup policy.
*/
export interface GeoBackupPolicy extends ProxyResource {
/**
* The state of the geo backup policy. Possible values include: 'Disabled', 'Enabled'
*/
state: string;
/**
* The storage type of the geo backup policy.
*/
readonly storageType?: string;
/**
* Kind of geo backup policy. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* Backup policy location.
*/
readonly location?: string;
}
/**
* Import database parameters.
*/
export interface ImportExtensionRequest {
/**
* The name of the extension.
*/
name?: string;
/**
* The type of the extension.
*/
type?: string;
/**
* The type of the storage key to use. Possible values include: 'StorageAccessKey',
* 'SharedAccessKey'
*/
storageKeyType: string;
/**
* The storage key to use. If storage key type is SharedAccessKey, it must be preceded with a
* "?."
*/
storageKey: string;
/**
* The storage uri to use.
*/
storageUri: string;
/**
* The name of the SQL administrator.
*/
administratorLogin: string;
/**
* The password of the SQL administrator.
*/
administratorLoginPassword: string;
/**
* The authentication type. Possible values include: 'SQL', 'ADPassword'
*/
authenticationType?: string;
}
/**
* Response for Import/Export Get operation.
*/
export interface ImportExportResponse extends ProxyResource {
/**
* The request type of the operation.
*/
readonly requestType?: string;
/**
* The request type of the operation.
*/
readonly requestId?: string;
/**
* The name of the server.
*/
readonly serverName?: string;
/**
* The name of the database.
*/
readonly databaseName?: string;
/**
* The status message returned from the server.
*/
readonly status?: string;
/**
* The operation status last modified time.
*/
readonly lastModifiedTime?: string;
/**
* The operation queued time.
*/
readonly queuedTime?: string;
/**
* The blob uri.
*/
readonly blobUri?: string;
/**
* The error message returned from the server.
*/
readonly errorMessage?: string;
}
/**
* Export database parameters.
*/
export interface ExportRequest {
/**
* The type of the storage key to use. Possible values include: 'StorageAccessKey',
* 'SharedAccessKey'
*/
storageKeyType: string;
/**
* The storage key to use. If storage key type is SharedAccessKey, it must be preceded with a
* "?."
*/
storageKey: string;
/**
* The storage uri to use.
*/
storageUri: string;
/**
* The name of the SQL administrator.
*/
administratorLogin: string;
/**
* The password of the SQL administrator.
*/
administratorLoginPassword: string;
/**
* The authentication type. Possible values include: 'SQL', 'ADPassword'
*/
authenticationType?: string;
}
/**
* Import database parameters.
*/
export interface ImportRequest extends ExportRequest {
/**
* The name of the database to import.
*/
databaseName: string;
/**
* The edition for the database being created. Possible values include: 'Web', 'Business',
* 'Basic', 'Standard', 'Premium', 'PremiumRS', 'Free', 'Stretch', 'DataWarehouse', 'System',
* 'System2'
*/
edition: string;
/**
* The name of the service objective to assign to the database. Possible values include:
* 'System', 'System0', 'System1', 'System2', 'System3', 'System4', 'System2L', 'System3L',
* 'System4L', 'Free', 'Basic', 'S0', 'S1', 'S2', 'S3', 'S4', 'S6', 'S7', 'S9', 'S12', 'P1',
* 'P2', 'P3', 'P4', 'P6', 'P11', 'P15', 'PRS1', 'PRS2', 'PRS4', 'PRS6', 'DW100', 'DW200',
* 'DW300', 'DW400', 'DW500', 'DW600', 'DW1000', 'DW1200', 'DW1000c', 'DW1500', 'DW1500c',
* 'DW2000', 'DW2000c', 'DW3000', 'DW2500c', 'DW3000c', 'DW6000', 'DW5000c', 'DW6000c',
* 'DW7500c', 'DW10000c', 'DW15000c', 'DW30000c', 'DS100', 'DS200', 'DS300', 'DS400', 'DS500',
* 'DS600', 'DS1000', 'DS1200', 'DS1500', 'DS2000', 'ElasticPool'
*/
serviceObjectiveName: string;
/**
* The maximum size for the newly imported database.
*/
maxSizeBytes: string;
}
/**
* Represents database metrics.
*/
export interface MetricValue {
/**
* The number of values for the metric.
*/
readonly count?: number;
/**
* The average value of the metric.
*/
readonly average?: number;
/**
* The max value of the metric.
*/
readonly maximum?: number;
/**
* The min value of the metric.
*/
readonly minimum?: number;
/**
* The metric timestamp (ISO-8601 format).
*/
readonly timestamp?: Date;
/**
* The total value of the metric.
*/
readonly total?: number;
}
/**
* A database metric name.
*/
export interface MetricName {
/**
* The name of the database metric.
*/
readonly value?: string;
/**
* The friendly name of the database metric.
*/
readonly localizedValue?: string;
}
/**
* Database metrics.
*/
export interface Metric {
/**
* The start time for the metric (ISO-8601 format).
*/
readonly startTime?: Date;
/**
* The end time for the metric (ISO-8601 format).
*/
readonly endTime?: Date;
/**
* The time step to be used to summarize the metric values.
*/
readonly timeGrain?: string;
/**
* The unit of the metric. Possible values include: 'count', 'bytes', 'seconds', 'percent',
* 'countPerSecond', 'bytesPerSecond'
*/
readonly unit?: string;
/**
* The name information for the metric.
*/
readonly name?: MetricName;
/**
* The metric values for the specified time window and timestep.
*/
readonly metricValues?: MetricValue[];
}
/**
* A metric availability value.
*/
export interface MetricAvailability {
/**
* The length of retention for the database metric.
*/
readonly retention?: string;
/**
* The granularity of the database metric.
*/
readonly timeGrain?: string;
}
/**
* A database metric definition.
*/
export interface MetricDefinition {
/**
* The name information for the metric.
*/
readonly name?: MetricName;
/**
* The primary aggregation type defining how metric values are displayed. Possible values
* include: 'None', 'Average', 'Count', 'Minimum', 'Maximum', 'Total'
*/
readonly primaryAggregationType?: string;
/**
* The resource uri of the database.
*/
readonly resourceUri?: string;
/**
* The unit of the metric. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent',
* 'CountPerSecond', 'BytesPerSecond'
*/
readonly unit?: string;
/**
* The list of database metric availabilities for the metric.
*/
readonly metricAvailabilities?: MetricAvailability[];
}
/**
* Represents recommended elastic pool metric.
*/
export interface RecommendedElasticPoolMetric {
/**
* The time of metric (ISO8601 format).
*/
dateTime?: Date;
/**
* Gets or sets the DTUs (Database Transaction Units). See
* https://azure.microsoft.com/documentation/articles/sql-database-what-is-a-dtu/
*/
dtu?: number;
/**
* Gets or sets size in gigabytes.
*/
sizeGB?: number;
}
/**
* Represents a recommended elastic pool.
*/
export interface RecommendedElasticPool extends ProxyResource {
/**
* The edition of the recommended elastic pool. The ElasticPoolEdition enumeration contains all
* the valid editions. Possible values include: 'Basic', 'Standard', 'Premium'
*/
readonly databaseEdition?: string;
/**
* The DTU for the recommended elastic pool.
*/
dtu?: number;
/**
* The minimum DTU for the database.
*/
databaseDtuMin?: number;
/**
* The maximum DTU for the database.
*/
databaseDtuMax?: number;
/**
* Gets storage size in megabytes.
*/
storageMB?: number;
/**
* The observation period start (ISO8601 format).
*/
readonly observationPeriodStart?: Date;
/**
* The observation period start (ISO8601 format).
*/
readonly observationPeriodEnd?: Date;
/**
* Gets maximum observed DTU.
*/
readonly maxObservedDtu?: number;
/**
* Gets maximum observed storage in megabytes.
*/
readonly maxObservedStorageMB?: number;
/**
* The list of databases in this pool. Expanded property
*/
readonly databases?: TrackedResource[];
/**
* The list of databases housed in the server. Expanded property
*/
readonly metrics?: RecommendedElasticPoolMetric[];
}
/**
* Represents a database replication link.
*/
export interface ReplicationLink extends ProxyResource {
/**
* Location of the server that contains this firewall rule.
*/
readonly location?: string;
/**
* Legacy value indicating whether termination is allowed. Currently always returns true.
*/
readonly isTerminationAllowed?: boolean;
/**
* Replication mode of this replication link.
*/
readonly replicationMode?: string;
/**
* The name of the server hosting the partner database.
*/
readonly partnerServer?: string;
/**
* The name of the partner database.
*/
readonly partnerDatabase?: string;
/**
* The Azure Region of the partner database.
*/
readonly partnerLocation?: string;
/**
* The role of the database in the replication link. Possible values include: 'Primary',
* 'Secondary', 'NonReadableSecondary', 'Source', 'Copy'
*/
readonly role?: string;
/**
* The role of the partner database in the replication link. Possible values include: 'Primary',
* 'Secondary', 'NonReadableSecondary', 'Source', 'Copy'
*/
readonly partnerRole?: string;
/**
* The start time for the replication link.
*/
readonly startTime?: Date;
/**
* The percentage of seeding complete for the replication link.
*/
readonly percentComplete?: number;
/**
* The replication state for the replication link. Possible values include: 'PENDING', 'SEEDING',
* 'CATCH_UP', 'SUSPENDED'
*/
readonly replicationState?: string;
}
/**
* An server Active Directory Administrator.
*/
export interface ServerAzureADAdministrator extends ProxyResource {
/**
* The server administrator login value.
*/
login: string;
/**
* The server administrator Sid (Secure ID).
*/
sid: string;
/**
* The server Active Directory Administrator tenant id.
*/
tenantId: string;
}
/**
* Server communication link.
*/
export interface ServerCommunicationLink extends ProxyResource {
/**
* The state.
*/
readonly state?: string;
/**
* The name of the partner server.
*/
partnerServer: string;
/**
* Communication link location.
*/
readonly location?: string;
/**
* Communication link kind. This property is used for Azure Portal metadata.
*/
readonly kind?: string;
}
/**
* Represents a database service objective.
*/
export interface ServiceObjective extends ProxyResource {
/**
* The name for the service objective.
*/
readonly serviceObjectiveName?: string;
/**
* Gets whether the service level objective is the default service objective.
*/
readonly isDefault?: boolean;
/**
* Gets whether the service level objective is a system service objective.
*/
readonly isSystem?: boolean;
/**
* The description for the service level objective.
*/
readonly description?: string;
/**
* Gets whether the service level objective is enabled.
*/
readonly enabled?: boolean;
}
/**
* Represents the activity on an elastic pool.
*/
export interface ElasticPoolActivity extends ProxyResource {
/**
* The geo-location where the resource lives
*/
location?: string;
/**
* The time the operation finished (ISO8601 format).
*/
readonly endTime?: Date;
/**
* The error code if available.
*/
readonly errorCode?: number;
/**
* The error message if available.
*/
readonly errorMessage?: string;
/**
* The error severity if available.
*/
readonly errorSeverity?: number;
/**
* The operation name.
*/
readonly operation?: string;
/**
* The unique operation ID.
*/
readonly operationId?: string;
/**
* The percentage complete if available.
*/
readonly percentComplete?: number;
/**
* The requested max DTU per database if available.
*/
readonly requestedDatabaseDtuMax?: number;
/**
* The requested min DTU per database if available.
*/
readonly requestedDatabaseDtuMin?: number;
/**
* The requested DTU for the pool if available.
*/
readonly requestedDtu?: number;
/**
* The requested name for the elastic pool if available.
*/
readonly requestedElasticPoolName?: string;
/**
* The requested storage limit for the pool in GB if available.
*/
readonly requestedStorageLimitInGB?: number;
/**
* The name of the elastic pool.
*/
readonly elasticPoolName?: string;
/**
* The name of the server the elastic pool is in.
*/
readonly serverName?: string;
/**
* The time the operation started (ISO8601 format).
*/
readonly startTime?: Date;
/**
* The current state of the operation.
*/
readonly state?: string;
/**
* The requested storage limit in MB.
*/
readonly requestedStorageLimitInMB?: number;
/**
* The requested per database DTU guarantee.
*/
readonly requestedDatabaseDtuGuarantee?: number;
/**
* The requested per database DTU cap.
*/
readonly requestedDatabaseDtuCap?: number;
/**
* The requested DTU guarantee.
*/
readonly requestedDtuGuarantee?: number;
}
/**
* Represents the activity on an elastic pool.
*/
export interface ElasticPoolDatabaseActivity extends ProxyResource {
/**
* The geo-location where the resource lives
*/
location?: string;
/**
* The database name.
*/
readonly databaseName?: string;
/**
* The time the operation finished (ISO8601 format).
*/
readonly endTime?: Date;
/**
* The error code if available.
*/
readonly errorCode?: number;
/**
* The error message if available.
*/
readonly errorMessage?: string;
/**
* The error severity if available.
*/
readonly errorSeverity?: number;
/**
* The operation name.
*/
readonly operation?: string;
/**
* The unique operation ID.
*/
readonly operationId?: string;
/**
* The percentage complete if available.
*/
readonly percentComplete?: number;
/**
* The name for the elastic pool the database is moving into if available.
*/
readonly requestedElasticPoolName?: string;
/**
* The name of the current elastic pool the database is in if available.
*/
readonly currentElasticPoolName?: string;
/**
* The name of the current service objective if available.
*/
readonly currentServiceObjective?: string;
/**
* The name of the requested service objective if available.
*/
readonly requestedServiceObjective?: string;
/**
* The name of the server the elastic pool is in.
*/
readonly serverName?: string;
/**
* The time the operation started (ISO8601 format).
*/
readonly startTime?: Date;
/**
* The current state of the operation.
*/
readonly state?: string;
}
/**
* The impact of an operation, both in absolute and relative terms.
*/
export interface OperationImpact {
/**
* The name of the impact dimension.
*/
readonly name?: string;
/**
* The unit in which estimated impact to dimension is measured.
*/
readonly unit?: string;
/**
* The absolute impact to dimension.
*/
readonly changeValueAbsolute?: number;
/**
* The relative impact to dimension (null if not applicable)
*/
readonly changeValueRelative?: number;
}
/**
* Represents a database recommended index.
*/
export interface RecommendedIndex extends ProxyResource {
/**
* The proposed index action. You can create a missing index, drop an unused index, or rebuild an
* existing index to improve its performance. Possible values include: 'Create', 'Drop',
* 'Rebuild'
*/
readonly action?: string;
/**
* The current recommendation state. Possible values include: 'Active', 'Pending', 'Executing',
* 'Verifying', 'Pending Revert', 'Reverting', 'Reverted', 'Ignored', 'Expired', 'Blocked',
* 'Success'
*/
readonly state?: string;
/**
* The UTC datetime showing when this resource was created (ISO8601 format).
*/
readonly created?: Date;
/**
* The UTC datetime of when was this resource last changed (ISO8601 format).
*/
readonly lastModified?: Date;
/**
* The type of index (CLUSTERED, NONCLUSTERED, COLUMNSTORE, CLUSTERED COLUMNSTORE). Possible
* values include: 'CLUSTERED', 'NONCLUSTERED', 'COLUMNSTORE', 'CLUSTERED COLUMNSTORE'
*/
readonly indexType?: string;
/**
* The schema where table to build index over resides
*/
readonly schema?: string;
/**
* The table on which to build index.
*/
readonly table?: string;
/**
* Columns over which to build index
*/
readonly columns?: string[];
/**
* The list of column names to be included in the index
*/
readonly includedColumns?: string[];
/**
* The full build index script
*/
readonly indexScript?: string;
/**
* The estimated impact of doing recommended index action.
*/
readonly estimatedImpact?: OperationImpact[];
/**
* The values reported after index action is complete.
*/
readonly reportedImpact?: OperationImpact[];
}
/**
* Represents a database transparent data encryption configuration.
*/
export interface TransparentDataEncryption extends ProxyResource {
/**
* Resource location.
*/
readonly location?: string;
/**
* The status of the database transparent data encryption. Possible values include: 'Enabled',
* 'Disabled'
*/
status?: string;
}
/**
* A Slo Usage Metric.
*/
export interface SloUsageMetric {
/**
* The serviceLevelObjective for SLO usage metric. Possible values include: 'System', 'System0',
* 'System1', 'System2', 'System3', 'System4', 'System2L', 'System3L', 'System4L', 'Free',
* 'Basic', 'S0', 'S1', 'S2', 'S3', 'S4', 'S6', 'S7', 'S9', 'S12', 'P1', 'P2', 'P3', 'P4', 'P6',
* 'P11', 'P15', 'PRS1', 'PRS2', 'PRS4', 'PRS6', 'DW100', 'DW200', 'DW300', 'DW400', 'DW500',
* 'DW600', 'DW1000', 'DW1200', 'DW1000c', 'DW1500', 'DW1500c', 'DW2000', 'DW2000c', 'DW3000',
* 'DW2500c', 'DW3000c', 'DW6000', 'DW5000c', 'DW6000c', 'DW7500c', 'DW10000c', 'DW15000c',
* 'DW30000c', 'DS100', 'DS200', 'DS300', 'DS400', 'DS500', 'DS600', 'DS1000', 'DS1200',
* 'DS1500', 'DS2000', 'ElasticPool'
*/
readonly serviceLevelObjective?: string;
/**
* The serviceLevelObjectiveId for SLO usage metric.
*/
readonly serviceLevelObjectiveId?: string;
/**
* Gets or sets inRangeTimeRatio for SLO usage metric.
*/
readonly inRangeTimeRatio?: number;
}
/**
* Represents a Service Tier Advisor.
*/
export interface ServiceTierAdvisor extends ProxyResource {
/**
* The observation period start (ISO8601 format).
*/
readonly observationPeriodStart?: Date;
/**
* The observation period start (ISO8601 format).
*/
readonly observationPeriodEnd?: Date;
/**
* The activeTimeRatio for service tier advisor.
*/
readonly activeTimeRatio?: number;
/**
* Gets or sets minDtu for service tier advisor.
*/
readonly minDtu?: number;
/**
* Gets or sets avgDtu for service tier advisor.
*/
readonly avgDtu?: number;
/**
* Gets or sets maxDtu for service tier advisor.
*/
readonly maxDtu?: number;
/**
* Gets or sets maxSizeInGB for service tier advisor.
*/
readonly maxSizeInGB?: number;
/**
* Gets or sets serviceLevelObjectiveUsageMetrics for the service tier advisor.
*/
readonly serviceLevelObjectiveUsageMetrics?: SloUsageMetric[];
/**
* Gets or sets currentServiceLevelObjective for service tier advisor.
*/
readonly currentServiceLevelObjective?: string;
/**
* Gets or sets currentServiceLevelObjectiveId for service tier advisor.
*/
readonly currentServiceLevelObjectiveId?: string;
/**
* Gets or sets usageBasedRecommendationServiceLevelObjective for service tier advisor.
*/
readonly usageBasedRecommendationServiceLevelObjective?: string;
/**
* Gets or sets usageBasedRecommendationServiceLevelObjectiveId for service tier advisor.
*/
readonly usageBasedRecommendationServiceLevelObjectiveId?: string;
/**
* Gets or sets databaseSizeBasedRecommendationServiceLevelObjective for service tier advisor.
*/
readonly databaseSizeBasedRecommendationServiceLevelObjective?: string;
/**
* Gets or sets databaseSizeBasedRecommendationServiceLevelObjectiveId for service tier advisor.
*/
readonly databaseSizeBasedRecommendationServiceLevelObjectiveId?: string;
/**
* Gets or sets disasterPlanBasedRecommendationServiceLevelObjective for service tier advisor.
*/
readonly disasterPlanBasedRecommendationServiceLevelObjective?: string;
/**
* Gets or sets disasterPlanBasedRecommendationServiceLevelObjectiveId for service tier advisor.
*/
readonly disasterPlanBasedRecommendationServiceLevelObjectiveId?: string;
/**
* Gets or sets overallRecommendationServiceLevelObjective for service tier advisor.
*/
readonly overallRecommendationServiceLevelObjective?: string;
/**
* Gets or sets overallRecommendationServiceLevelObjectiveId for service tier advisor.
*/
readonly overallRecommendationServiceLevelObjectiveId?: string;
/**
* Gets or sets confidence for service tier advisor.
*/
readonly confidence?: number;
}
/**
* Represents a database transparent data encryption Scan.
*/
export interface TransparentDataEncryptionActivity extends ProxyResource {
/**
* Resource location.
*/
readonly location?: string;
/**
* The status of the database. Possible values include: 'Encrypting', 'Decrypting'
*/
readonly status?: string;
/**
* The percent complete of the transparent data encryption scan for a database.
*/
readonly percentComplete?: number;
}
/**
* Represents server metrics.
*/
export interface ServerUsage {
/**
* Name of the server usage metric.
*/
readonly name?: string;
/**
* The name of the resource.
*/
readonly resourceName?: string;
/**
* The metric display name.
*/
readonly displayName?: string;
/**
* The current value of the metric.
*/
readonly currentValue?: number;
/**
* The current limit of the metric.
*/
readonly limit?: number;
/**
* The units of the metric.
*/
readonly unit?: string;
/**
* The next reset time for the metric (ISO8601 format).
*/
readonly nextResetTime?: Date;
}
/**
* The database usages.
*/
export interface DatabaseUsage {
/**
* The name of the usage metric.
*/
readonly name?: string;
/**
* The name of the resource.
*/
readonly resourceName?: string;
/**
* The usage metric display name.
*/
readonly displayName?: string;
/**
* The current value of the usage metric.
*/
readonly currentValue?: number;
/**
* The current limit of the usage metric.
*/
readonly limit?: number;
/**
* The units of the usage metric.
*/
readonly unit?: string;
/**
* The next reset time for the usage metric (ISO8601 format).
*/
readonly nextResetTime?: Date;
}
/**
* Automatic tuning properties for individual advisors.
*/
export interface AutomaticTuningOptions {
/**
* Automatic tuning option desired state. Possible values include: 'Off', 'On', 'Default'
*/
desiredState?: string;
/**
* Automatic tuning option actual state. Possible values include: 'Off', 'On'
*/
readonly actualState?: string;
/**
* Reason code if desired and actual state are different.
*/
readonly reasonCode?: number;
/**
* Reason description if desired and actual state are different. Possible values include:
* 'Default', 'Disabled', 'AutoConfigured', 'InheritedFromServer', 'QueryStoreOff',
* 'QueryStoreReadOnly', 'NotSupported'
*/
readonly reasonDesc?: string;
}
/**
* Database-level Automatic Tuning.
*/
export interface DatabaseAutomaticTuning extends ProxyResource {
/**
* Automatic tuning desired state. Possible values include: 'Inherit', 'Custom', 'Auto',
* 'Unspecified'
*/
desiredState?: string;
/**
* Automatic tuning actual state. Possible values include: 'Inherit', 'Custom', 'Auto',
* 'Unspecified'
*/
readonly actualState?: string;
/**
* Automatic tuning options definition.
*/
options?: { [propertyName: string]: AutomaticTuningOptions };
}
/**
* The server encryption protector.
*/
export interface EncryptionProtector extends ProxyResource {
/**
* Kind of encryption protector. This is metadata used for the Azure portal experience.
*/
kind?: string;
/**
* Resource location.
*/
readonly location?: string;
/**
* Subregion of the encryption protector.
*/
readonly subregion?: string;
/**
* The name of the server key.
*/
serverKeyName?: string;
/**
* The encryption protector type like 'ServiceManaged', 'AzureKeyVault'. Possible values include:
* 'ServiceManaged', 'AzureKeyVault'
*/
serverKeyType: string;
/**
* The URI of the server key.
*/
readonly uri?: string;
/**
* Thumbprint of the server key.
*/
readonly thumbprint?: string;
}
/**
* Read-write endpoint of the failover group instance.
*/
export interface FailoverGroupReadWriteEndpoint {
/**
* Failover policy of the read-write endpoint for the failover group. If failoverPolicy is
* Automatic then failoverWithDataLossGracePeriodMinutes is required. Possible values include:
* 'Manual', 'Automatic'
*/
failoverPolicy: string;
/**
* Grace period before failover with data loss is attempted for the read-write endpoint. If
* failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required.
*/
failoverWithDataLossGracePeriodMinutes?: number;
}
/**
* Read-only endpoint of the failover group instance.
*/
export interface FailoverGroupReadOnlyEndpoint {
/**
* Failover policy of the read-only endpoint for the failover group. Possible values include:
* 'Disabled', 'Enabled'
*/
failoverPolicy?: string;
}
/**
* Partner server information for the failover group.
*/
export interface PartnerInfo {
/**
* Resource identifier of the partner server.
*/
id: string;
/**
* Geo location of the partner server.
*/
readonly location?: string;
/**
* Replication role of the partner server. Possible values include: 'Primary', 'Secondary'
*/
readonly replicationRole?: string;
}
/**
* A failover group.
*/
export interface FailoverGroup extends ProxyResource {
/**
* Resource location.
*/
readonly location?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* Read-write endpoint of the failover group instance.
*/
readWriteEndpoint: FailoverGroupReadWriteEndpoint;
/**
* Read-only endpoint of the failover group instance.
*/
readOnlyEndpoint?: FailoverGroupReadOnlyEndpoint;
/**
* Local replication role of the failover group instance. Possible values include: 'Primary',
* 'Secondary'
*/
readonly replicationRole?: string;
/**
* Replication state of the failover group instance.
*/
readonly replicationState?: string;
/**
* List of partner server information for the failover group.
*/
partnerServers: PartnerInfo[];
/**
* List of databases in the failover group.
*/
databases?: string[];
}
/**
* A failover group update request.
*/
export interface FailoverGroupUpdate {
/**
* Read-write endpoint of the failover group instance.
*/
readWriteEndpoint?: FailoverGroupReadWriteEndpoint;
/**
* Read-only endpoint of the failover group instance.
*/
readOnlyEndpoint?: FailoverGroupReadOnlyEndpoint;
/**
* List of databases in the failover group.
*/
databases?: string[];
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Azure Active Directory identity configuration for a resource.
*/
export interface ResourceIdentity {
/**
* The Azure Active Directory principal id.
*/
readonly principalId?: string;
/**
* The identity type. Set this to 'SystemAssigned' in order to automatically create and assign an
* Azure Active Directory principal for the resource. Possible values include: 'SystemAssigned'
*/
type?: string;
/**
* The Azure Active Directory tenant id.
*/
readonly tenantId?: string;
}
/**
* The resource model definition representing SKU
*/
export interface Sku {
/**
* The name of the SKU. Ex - P3. It is typically a letter+number code
*/
name: string;
/**
* This field is required to be implemented by the Resource Provider if the service has more than
* one tier, but is not required on a PUT.
*/
tier?: string;
/**
* The SKU size. When the name field is the combination of tier and some other value, this would
* be the standalone code.
*/
size?: string;
/**
* If the service has different generations of hardware, for the same SKU, then that can be
* captured here.
*/
family?: string;
/**
* If the SKU supports scale out/in then the capacity integer should be included. If scale out/in
* is not possible for the resource this may be omitted.
*/
capacity?: number;
}
/**
* An Azure SQL managed instance.
*/
export interface ManagedInstance extends TrackedResource {
/**
* The Azure Active Directory identity of the managed instance.
*/
identity?: ResourceIdentity;
/**
* Managed instance sku
*/
sku?: Sku;
/**
* The fully qualified domain name of the managed instance.
*/
readonly fullyQualifiedDomainName?: string;
/**
* Administrator username for the managed instance. Can only be specified when the managed
* instance is being created (and is required for creation).
*/
administratorLogin?: string;
/**
* The administrator login password (required for managed instance creation).
*/
administratorLoginPassword?: string;
/**
* Subnet resource ID for the managed instance.
*/
subnetId?: string;
/**
* The state of the managed instance.
*/
readonly state?: string;
/**
* The license type. Possible values are 'LicenseIncluded' and 'BasePrice'.
*/
licenseType?: string;
/**
* The number of VCores.
*/
vCores?: number;
/**
* The maximum storage size in GB.
*/
storageSizeInGB?: number;
/**
* Collation of the managed instance.
*/
collation?: string;
/**
* The Dns Zone that the managed instance is in.
*/
readonly dnsZone?: string;
/**
* The resource id of another managed instance whose DNS zone this managed instance will share
* after creation.
*/
dnsZonePartner?: string;
/**
* Whether or not the public data endpoint is enabled.
*/
publicDataEndpointEnabled?: boolean;
/**
* Connection type used for connecting to the instance. Possible values include: 'Proxy',
* 'Redirect', 'Default'
*/
proxyOverride?: string;
/**
* Id of the timezone. Allowed values are timezones supported by Windows.
* Windows keeps details on supported timezones, including the id, in registry under
* KEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones.
* You can get those registry values via SQL Server by querying SELECT name AS timezone_id FROM
* sys.time_zone_info.
* List of Ids can also be obtained by executing [System.TimeZoneInfo]::GetSystemTimeZones() in
* PowerShell.
* An example of valid timezone id is "Pacific Standard Time" or "W. Europe Standard Time".
*/
timezoneId?: string;
}
/**
* An update request for an Azure SQL Database managed instance.
*/
export interface ManagedInstanceUpdate {
/**
* Managed instance sku
*/
sku?: Sku;
/**
* The fully qualified domain name of the managed instance.
*/
readonly fullyQualifiedDomainName?: string;
/**
* Administrator username for the managed instance. Can only be specified when the managed
* instance is being created (and is required for creation).
*/
administratorLogin?: string;
/**
* The administrator login password (required for managed instance creation).
*/
administratorLoginPassword?: string;
/**
* Subnet resource ID for the managed instance.
*/
subnetId?: string;
/**
* The state of the managed instance.
*/
readonly state?: string;
/**
* The license type. Possible values are 'LicenseIncluded' and 'BasePrice'.
*/
licenseType?: string;
/**
* The number of VCores.
*/
vCores?: number;
/**
* The maximum storage size in GB.
*/
storageSizeInGB?: number;
/**
* Collation of the managed instance.
*/
collation?: string;
/**
* The Dns Zone that the managed instance is in.
*/
readonly dnsZone?: string;
/**
* The resource id of another managed instance whose DNS zone this managed instance will share
* after creation.
*/
dnsZonePartner?: string;
/**
* Whether or not the public data endpoint is enabled.
*/
publicDataEndpointEnabled?: boolean;
/**
* Connection type used for connecting to the instance. Possible values include: 'Proxy',
* 'Redirect', 'Default'
*/
proxyOverride?: string;
/**
* Id of the timezone. Allowed values are timezones supported by Windows.
* Windows keeps details on supported timezones, including the id, in registry under
* KEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones.
* You can get those registry values via SQL Server by querying SELECT name AS timezone_id FROM
* sys.time_zone_info.
* List of Ids can also be obtained by executing [System.TimeZoneInfo]::GetSystemTimeZones() in
* PowerShell.
* An example of valid timezone id is "Pacific Standard Time" or "W. Europe Standard Time".
*/
timezoneId?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Display metadata associated with the operation.
*/
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name.
*/
readonly provider?: string;
/**
* The localized friendly form of the resource type related to this action/operation.
*/
readonly resource?: string;
/**
* The localized friendly name for the operation.
*/
readonly operation?: string;
/**
* The localized friendly description for the operation.
*/
readonly description?: string;
}
/**
* SQL REST API operation definition.
*/
export interface Operation {
/**
* The name of the operation being performed on this particular object.
*/
readonly name?: string;
/**
* The localized display information for this particular operation / action.
*/
readonly display?: OperationDisplay;
/**
* The intended executor of the operation. Possible values include: 'user', 'system'
*/
readonly origin?: string;
/**
* Additional descriptions for the operation.
*/
readonly properties?: { [propertyName: string]: any };
}
/**
* A server key.
*/
export interface ServerKey extends ProxyResource {
/**
* Kind of encryption protector. This is metadata used for the Azure portal experience.
*/
kind?: string;
/**
* Resource location.
*/
readonly location?: string;
/**
* Subregion of the server key.
*/
readonly subregion?: string;
/**
* The server key type like 'ServiceManaged', 'AzureKeyVault'. Possible values include:
* 'ServiceManaged', 'AzureKeyVault'
*/
serverKeyType: string;
/**
* The URI of the server key.
*/
uri?: string;
/**
* Thumbprint of the server key.
*/
thumbprint?: string;
/**
* The server key creation date.
*/
creationDate?: Date;
}
/**
* An Azure SQL Database server.
*/
export interface Server extends TrackedResource {
/**
* The Azure Active Directory identity of the server.
*/
identity?: ResourceIdentity;
/**
* Kind of sql server. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* Administrator username for the server. Once created it cannot be changed.
*/
administratorLogin?: string;
/**
* The administrator login password (required for server creation).
*/
administratorLoginPassword?: string;
/**
* The version of the server.
*/
version?: string;
/**
* The state of the server.
*/
readonly state?: string;
/**
* The fully qualified domain name of the server.
*/
readonly fullyQualifiedDomainName?: string;
}
/**
* An update request for an Azure SQL Database server.
*/
export interface ServerUpdate {
/**
* Administrator username for the server. Once created it cannot be changed.
*/
administratorLogin?: string;
/**
* The administrator login password (required for server creation).
*/
administratorLoginPassword?: string;
/**
* The version of the server.
*/
version?: string;
/**
* The state of the server.
*/
readonly state?: string;
/**
* The fully qualified domain name of the server.
*/
readonly fullyQualifiedDomainName?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* An Azure SQL Database sync agent.
*/
export interface SyncAgent extends ProxyResource {
/**
* Name of the sync agent.
*/
readonly syncAgentName?: string;
/**
* ARM resource id of the sync database in the sync agent.
*/
syncDatabaseId?: string;
/**
* Last alive time of the sync agent.
*/
readonly lastAliveTime?: Date;
/**
* State of the sync agent. Possible values include: 'Online', 'Offline', 'NeverConnected'
*/
readonly state?: string;
/**
* If the sync agent version is up to date.
*/
readonly isUpToDate?: boolean;
/**
* Expiration time of the sync agent version.
*/
readonly expiryTime?: Date;
/**
* Version of the sync agent.
*/
readonly version?: string;
}
/**
* Properties of an Azure SQL Database sync agent key.
*/
export interface SyncAgentKeyProperties {
/**
* Key of sync agent.
*/
readonly syncAgentKey?: string;
}
/**
* An Azure SQL Database sync agent linked database.
*/
export interface SyncAgentLinkedDatabase extends ProxyResource {
/**
* Type of the sync agent linked database. Possible values include: 'AzureSqlDatabase',
* 'SqlServerDatabase'
*/
readonly databaseType?: string;
/**
* Id of the sync agent linked database.
*/
readonly databaseId?: string;
/**
* Description of the sync agent linked database.
*/
readonly description?: string;
/**
* Server name of the sync agent linked database.
*/
readonly serverName?: string;
/**
* Database name of the sync agent linked database.
*/
readonly databaseName?: string;
/**
* User name of the sync agent linked database.
*/
readonly userName?: string;
}
/**
* Properties of the sync database id.
*/
export interface SyncDatabaseIdProperties {
/**
* ARM resource id of sync database.
*/
readonly id?: string;
}
/**
* Properties of the column in the table of database full schema.
*/
export interface SyncFullSchemaTableColumn {
/**
* Data size of the column.
*/
readonly dataSize?: string;
/**
* Data type of the column.
*/
readonly dataType?: string;
/**
* Error id of the column.
*/
readonly errorId?: string;
/**
* If there is error in the table.
*/
readonly hasError?: boolean;
/**
* If it is the primary key of the table.
*/
readonly isPrimaryKey?: boolean;
/**
* Name of the column.
*/
readonly name?: string;
/**
* Quoted name of the column.
*/
readonly quotedName?: string;
}
/**
* Properties of the table in the database full schema.
*/
export interface SyncFullSchemaTable {
/**
* List of columns in the table of database full schema.
*/
readonly columns?: SyncFullSchemaTableColumn[];
/**
* Error id of the table.
*/
readonly errorId?: string;
/**
* If there is error in the table.
*/
readonly hasError?: boolean;
/**
* Name of the table.
*/
readonly name?: string;
/**
* Quoted name of the table.
*/
readonly quotedName?: string;
}
/**
* Properties of the database full schema.
*/
export interface SyncFullSchemaProperties {
/**
* List of tables in the database full schema.
*/
readonly tables?: SyncFullSchemaTable[];
/**
* Last update time of the database schema.
*/
readonly lastUpdateTime?: Date;
}
/**
* Properties of an Azure SQL Database sync group log.
*/
export interface SyncGroupLogProperties {
/**
* Timestamp of the sync group log.
*/
readonly timestamp?: Date;
/**
* Type of the sync group log. Possible values include: 'All', 'Error', 'Warning', 'Success'
*/
readonly type?: string;
/**
* Source of the sync group log.
*/
readonly source?: string;
/**
* Details of the sync group log.
*/
readonly details?: string;
/**
* TracingId of the sync group log.
*/
readonly tracingId?: string;
/**
* OperationStatus of the sync group log.
*/
readonly operationStatus?: string;
}
/**
* Properties of column in sync group table.
*/
export interface SyncGroupSchemaTableColumn {
/**
* Quoted name of sync group table column.
*/
quotedName?: string;
/**
* Data size of the column.
*/
dataSize?: string;
/**
* Data type of the column.
*/
dataType?: string;
}
/**
* Properties of table in sync group schema.
*/
export interface SyncGroupSchemaTable {
/**
* List of columns in sync group schema.
*/
columns?: SyncGroupSchemaTableColumn[];
/**
* Quoted name of sync group schema table.
*/
quotedName?: string;
}
/**
* Properties of sync group schema.
*/
export interface SyncGroupSchema {
/**
* List of tables in sync group schema.
*/
tables?: SyncGroupSchemaTable[];
/**
* Name of master sync member where the schema is from.
*/
masterSyncMemberName?: string;
}
/**
* An Azure SQL Database sync group.
*/
export interface SyncGroup extends ProxyResource {
/**
* Sync interval of the sync group.
*/
interval?: number;
/**
* Last sync time of the sync group.
*/
readonly lastSyncTime?: Date;
/**
* Conflict resolution policy of the sync group. Possible values include: 'HubWin', 'MemberWin'
*/
conflictResolutionPolicy?: string;
/**
* ARM resource id of the sync database in the sync group.
*/
syncDatabaseId?: string;
/**
* User name for the sync group hub database credential.
*/
hubDatabaseUserName?: string;
/**
* Password for the sync group hub database credential.
*/
hubDatabasePassword?: string;
/**
* Sync state of the sync group. Possible values include: 'NotReady', 'Error', 'Warning',
* 'Progressing', 'Good'
*/
readonly syncState?: string;
/**
* Sync schema of the sync group.
*/
schema?: SyncGroupSchema;
}
/**
* An Azure SQL Database sync member.
*/
export interface SyncMember extends ProxyResource {
/**
* Database type of the sync member. Possible values include: 'AzureSqlDatabase',
* 'SqlServerDatabase'
*/
databaseType?: string;
/**
* ARM resource id of the sync agent in the sync member.
*/
syncAgentId?: string;
/**
* SQL Server database id of the sync member.
*/
sqlServerDatabaseId?: string;
/**
* Server name of the member database in the sync member
*/
serverName?: string;
/**
* Database name of the member database in the sync member.
*/
databaseName?: string;
/**
* User name of the member database in the sync member.
*/
userName?: string;
/**
* Password of the member database in the sync member.
*/
password?: string;
/**
* Sync direction of the sync member. Possible values include: 'Bidirectional',
* 'OneWayMemberToHub', 'OneWayHubToMember'
*/
syncDirection?: string;
/**
* Sync state of the sync member. Possible values include: 'SyncInProgress', 'SyncSucceeded',
* 'SyncFailed', 'DisabledTombstoneCleanup', 'DisabledBackupRestore',
* 'SyncSucceededWithWarnings', 'SyncCancelling', 'SyncCancelled', 'UnProvisioned',
* 'Provisioning', 'Provisioned', 'ProvisionFailed', 'DeProvisioning', 'DeProvisioned',
* 'DeProvisionFailed', 'Reprovisioning', 'ReprovisionFailed', 'UnReprovisioned'
*/
readonly syncState?: string;
}
/**
* Usage Metric of a Subscription in a Location.
*/
export interface SubscriptionUsage extends ProxyResource {
/**
* User-readable name of the metric.
*/
readonly displayName?: string;
/**
* Current value of the metric.
*/
readonly currentValue?: number;
/**
* Boundary value of the metric.
*/
readonly limit?: number;
/**
* Unit of the metric.
*/
readonly unit?: string;
}
/**
* An Azure SQL virtual cluster.
*/
export interface VirtualCluster extends TrackedResource {
/**
* Subnet resource ID for the virtual cluster.
*/
readonly subnetId?: string;
/**
* If the service has different generations of hardware, for the same SKU, then that can be
* captured here.
*/
family?: string;
/**
* List of resources in this virtual cluster.
*/
readonly childResources?: string[];
}
/**
* An update request for an Azure SQL Database virtual cluster.
*/
export interface VirtualClusterUpdate {
/**
* Subnet resource ID for the virtual cluster.
*/
readonly subnetId?: string;
/**
* If the service has different generations of hardware, for the same SKU, then that can be
* captured here.
*/
family?: string;
/**
* List of resources in this virtual cluster.
*/
readonly childResources?: string[];
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* A virtual network rule.
*/
export interface VirtualNetworkRule extends ProxyResource {
/**
* The ARM resource id of the virtual network subnet.
*/
virtualNetworkSubnetId: string;
/**
* Create firewall rule before the virtual network has vnet service endpoint enabled.
*/
ignoreMissingVnetServiceEndpoint?: boolean;
/**
* Virtual Network Rule State. Possible values include: 'Initializing', 'InProgress', 'Ready',
* 'Deleting', 'Unknown'
*/
readonly state?: string;
}
/**
* An extended database blob auditing policy.
*/
export interface ExtendedDatabaseBlobAuditingPolicy extends ProxyResource {
/**
* Specifies condition of where clause when creating an audit.
*/
predicateExpression?: string;
/**
* Specifies the state of the policy. If state is Enabled, storageEndpoint or
* isAzureMonitorTargetEnabled are required. Possible values include: 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state
* is Enabled, storageEndpoint is required.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the auditing storage account. If state is Enabled and
* storageEndpoint is specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the audit logs in the storage account.
*/
retentionDays?: number;
/**
* Specifies the Actions-Groups and Actions to audit.
*
* The recommended set of action groups to use is the following combination - this will audit all
* the queries and stored procedures executed against the database, as well as successful and
* failed logins:
*
* BATCH_COMPLETED_GROUP,
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
* FAILED_DATABASE_AUTHENTICATION_GROUP.
*
* This above combination is also the set that is configured by default when enabling auditing
* from the Azure portal.
*
* The supported action groups to audit are (note: choose only specific groups that cover your
* auditing needs. Using unnecessary groups could lead to very large quantities of audit
* records):
*
* APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
* BACKUP_RESTORE_GROUP
* DATABASE_LOGOUT_GROUP
* DATABASE_OBJECT_CHANGE_GROUP
* DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
* DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
* DATABASE_OPERATION_GROUP
* DATABASE_PERMISSION_CHANGE_GROUP
* DATABASE_PRINCIPAL_CHANGE_GROUP
* DATABASE_PRINCIPAL_IMPERSONATION_GROUP
* DATABASE_ROLE_MEMBER_CHANGE_GROUP
* FAILED_DATABASE_AUTHENTICATION_GROUP
* SCHEMA_OBJECT_ACCESS_GROUP
* SCHEMA_OBJECT_CHANGE_GROUP
* SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
* SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
* USER_CHANGE_PASSWORD_GROUP
* BATCH_STARTED_GROUP
* BATCH_COMPLETED_GROUP
*
* These are groups that cover all sql statements and stored procedures executed against the
* database, and should not be used in combination with other groups as this will result in
* duplicate audit logs.
*
* For more information, see [Database-Level Audit Action
* Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
*
* For Database auditing policy, specific Actions can also be specified (note that Actions cannot
* be specified for Server auditing policy). The supported actions to audit are:
* SELECT
* UPDATE
* INSERT
* DELETE
* EXECUTE
* RECEIVE
* REFERENCES
*
* The general form for defining an action to be audited is:
* {action} ON {object} BY {principal}
*
* Note that <object> in the above format can refer to an object like a table, view, or stored
* procedure, or an entire database or schema. For the latter cases, the forms
* DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively.
*
* For example:
* SELECT on dbo.myTable by public
* SELECT on DATABASE::myDatabase by public
* SELECT on SCHEMA::mySchema by public
*
* For more information, see [Database-Level Audit
* Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
*/
auditActionsAndGroups?: string[];
/**
* Specifies the blob storage subscription Id.
*/
storageAccountSubscriptionId?: string;
/**
* Specifies whether storageAccountAccessKey value is the storage's secondary key.
*/
isStorageSecondaryKeyInUse?: boolean;
/**
* Specifies whether audit events are sent to Azure Monitor.
* In order to send the events to Azure Monitor, specify 'State' as 'Enabled' and
* 'IsAzureMonitorTargetEnabled' as true.
*
* When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents'
* diagnostic logs category on the database should be also created.
* Note that for server level audit you should use the 'master' database as {databaseName}.
*
* Diagnostic Settings URI format:
* PUT
* https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
*
* For more information, see [Diagnostic Settings REST
* API](https://go.microsoft.com/fwlink/?linkid=2033207)
* or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
*/
isAzureMonitorTargetEnabled?: boolean;
}
/**
* An extended server blob auditing policy.
*/
export interface ExtendedServerBlobAuditingPolicy extends ProxyResource {
/**
* Specifies condition of where clause when creating an audit.
*/
predicateExpression?: string;
/**
* Specifies the state of the policy. If state is Enabled, storageEndpoint or
* isAzureMonitorTargetEnabled are required. Possible values include: 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state
* is Enabled, storageEndpoint is required.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the auditing storage account. If state is Enabled and
* storageEndpoint is specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the audit logs in the storage account.
*/
retentionDays?: number;
/**
* Specifies the Actions-Groups and Actions to audit.
*
* The recommended set of action groups to use is the following combination - this will audit all
* the queries and stored procedures executed against the database, as well as successful and
* failed logins:
*
* BATCH_COMPLETED_GROUP,
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
* FAILED_DATABASE_AUTHENTICATION_GROUP.
*
* This above combination is also the set that is configured by default when enabling auditing
* from the Azure portal.
*
* The supported action groups to audit are (note: choose only specific groups that cover your
* auditing needs. Using unnecessary groups could lead to very large quantities of audit
* records):
*
* APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
* BACKUP_RESTORE_GROUP
* DATABASE_LOGOUT_GROUP
* DATABASE_OBJECT_CHANGE_GROUP
* DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
* DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
* DATABASE_OPERATION_GROUP
* DATABASE_PERMISSION_CHANGE_GROUP
* DATABASE_PRINCIPAL_CHANGE_GROUP
* DATABASE_PRINCIPAL_IMPERSONATION_GROUP
* DATABASE_ROLE_MEMBER_CHANGE_GROUP
* FAILED_DATABASE_AUTHENTICATION_GROUP
* SCHEMA_OBJECT_ACCESS_GROUP
* SCHEMA_OBJECT_CHANGE_GROUP
* SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
* SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
* USER_CHANGE_PASSWORD_GROUP
* BATCH_STARTED_GROUP
* BATCH_COMPLETED_GROUP
*
* These are groups that cover all sql statements and stored procedures executed against the
* database, and should not be used in combination with other groups as this will result in
* duplicate audit logs.
*
* For more information, see [Database-Level Audit Action
* Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
*
* For Database auditing policy, specific Actions can also be specified (note that Actions cannot
* be specified for Server auditing policy). The supported actions to audit are:
* SELECT
* UPDATE
* INSERT
* DELETE
* EXECUTE
* RECEIVE
* REFERENCES
*
* The general form for defining an action to be audited is:
* {action} ON {object} BY {principal}
*
* Note that <object> in the above format can refer to an object like a table, view, or stored
* procedure, or an entire database or schema. For the latter cases, the forms
* DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively.
*
* For example:
* SELECT on dbo.myTable by public
* SELECT on DATABASE::myDatabase by public
* SELECT on SCHEMA::mySchema by public
*
* For more information, see [Database-Level Audit
* Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
*/
auditActionsAndGroups?: string[];
/**
* Specifies the blob storage subscription Id.
*/
storageAccountSubscriptionId?: string;
/**
* Specifies whether storageAccountAccessKey value is the storage's secondary key.
*/
isStorageSecondaryKeyInUse?: boolean;
/**
* Specifies whether audit events are sent to Azure Monitor.
* In order to send the events to Azure Monitor, specify 'State' as 'Enabled' and
* 'IsAzureMonitorTargetEnabled' as true.
*
* When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents'
* diagnostic logs category on the database should be also created.
* Note that for server level audit you should use the 'master' database as {databaseName}.
*
* Diagnostic Settings URI format:
* PUT
* https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
*
* For more information, see [Diagnostic Settings REST
* API](https://go.microsoft.com/fwlink/?linkid=2033207)
* or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
*/
isAzureMonitorTargetEnabled?: boolean;
}
/**
* A server blob auditing policy.
*/
export interface ServerBlobAuditingPolicy extends ProxyResource {
/**
* Specifies the state of the policy. If state is Enabled, storageEndpoint or
* isAzureMonitorTargetEnabled are required. Possible values include: 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state
* is Enabled, storageEndpoint is required.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the auditing storage account. If state is Enabled and
* storageEndpoint is specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the audit logs in the storage account.
*/
retentionDays?: number;
/**
* Specifies the Actions-Groups and Actions to audit.
*
* The recommended set of action groups to use is the following combination - this will audit all
* the queries and stored procedures executed against the database, as well as successful and
* failed logins:
*
* BATCH_COMPLETED_GROUP,
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
* FAILED_DATABASE_AUTHENTICATION_GROUP.
*
* This above combination is also the set that is configured by default when enabling auditing
* from the Azure portal.
*
* The supported action groups to audit are (note: choose only specific groups that cover your
* auditing needs. Using unnecessary groups could lead to very large quantities of audit
* records):
*
* APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
* BACKUP_RESTORE_GROUP
* DATABASE_LOGOUT_GROUP
* DATABASE_OBJECT_CHANGE_GROUP
* DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
* DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
* DATABASE_OPERATION_GROUP
* DATABASE_PERMISSION_CHANGE_GROUP
* DATABASE_PRINCIPAL_CHANGE_GROUP
* DATABASE_PRINCIPAL_IMPERSONATION_GROUP
* DATABASE_ROLE_MEMBER_CHANGE_GROUP
* FAILED_DATABASE_AUTHENTICATION_GROUP
* SCHEMA_OBJECT_ACCESS_GROUP
* SCHEMA_OBJECT_CHANGE_GROUP
* SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
* SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
* USER_CHANGE_PASSWORD_GROUP
* BATCH_STARTED_GROUP
* BATCH_COMPLETED_GROUP
*
* These are groups that cover all sql statements and stored procedures executed against the
* database, and should not be used in combination with other groups as this will result in
* duplicate audit logs.
*
* For more information, see [Database-Level Audit Action
* Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
*
* For Database auditing policy, specific Actions can also be specified (note that Actions cannot
* be specified for Server auditing policy). The supported actions to audit are:
* SELECT
* UPDATE
* INSERT
* DELETE
* EXECUTE
* RECEIVE
* REFERENCES
*
* The general form for defining an action to be audited is:
* {action} ON {object} BY {principal}
*
* Note that <object> in the above format can refer to an object like a table, view, or stored
* procedure, or an entire database or schema. For the latter cases, the forms
* DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively.
*
* For example:
* SELECT on dbo.myTable by public
* SELECT on DATABASE::myDatabase by public
* SELECT on SCHEMA::mySchema by public
*
* For more information, see [Database-Level Audit
* Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
*/
auditActionsAndGroups?: string[];
/**
* Specifies the blob storage subscription Id.
*/
storageAccountSubscriptionId?: string;
/**
* Specifies whether storageAccountAccessKey value is the storage's secondary key.
*/
isStorageSecondaryKeyInUse?: boolean;
/**
* Specifies whether audit events are sent to Azure Monitor.
* In order to send the events to Azure Monitor, specify 'State' as 'Enabled' and
* 'IsAzureMonitorTargetEnabled' as true.
*
* When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents'
* diagnostic logs category on the database should be also created.
* Note that for server level audit you should use the 'master' database as {databaseName}.
*
* Diagnostic Settings URI format:
* PUT
* https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
*
* For more information, see [Diagnostic Settings REST
* API](https://go.microsoft.com/fwlink/?linkid=2033207)
* or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
*/
isAzureMonitorTargetEnabled?: boolean;
}
/**
* A database blob auditing policy.
*/
export interface DatabaseBlobAuditingPolicy extends ProxyResource {
/**
* Resource kind.
*/
readonly kind?: string;
/**
* Specifies the state of the policy. If state is Enabled, storageEndpoint or
* isAzureMonitorTargetEnabled are required. Possible values include: 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state
* is Enabled, storageEndpoint is required.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the auditing storage account. If state is Enabled and
* storageEndpoint is specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the audit logs in the storage account.
*/
retentionDays?: number;
/**
* Specifies the Actions-Groups and Actions to audit.
*
* The recommended set of action groups to use is the following combination - this will audit all
* the queries and stored procedures executed against the database, as well as successful and
* failed logins:
*
* BATCH_COMPLETED_GROUP,
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP,
* FAILED_DATABASE_AUTHENTICATION_GROUP.
*
* This above combination is also the set that is configured by default when enabling auditing
* from the Azure portal.
*
* The supported action groups to audit are (note: choose only specific groups that cover your
* auditing needs. Using unnecessary groups could lead to very large quantities of audit
* records):
*
* APPLICATION_ROLE_CHANGE_PASSWORD_GROUP
* BACKUP_RESTORE_GROUP
* DATABASE_LOGOUT_GROUP
* DATABASE_OBJECT_CHANGE_GROUP
* DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP
* DATABASE_OBJECT_PERMISSION_CHANGE_GROUP
* DATABASE_OPERATION_GROUP
* DATABASE_PERMISSION_CHANGE_GROUP
* DATABASE_PRINCIPAL_CHANGE_GROUP
* DATABASE_PRINCIPAL_IMPERSONATION_GROUP
* DATABASE_ROLE_MEMBER_CHANGE_GROUP
* FAILED_DATABASE_AUTHENTICATION_GROUP
* SCHEMA_OBJECT_ACCESS_GROUP
* SCHEMA_OBJECT_CHANGE_GROUP
* SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP
* SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP
* SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
* USER_CHANGE_PASSWORD_GROUP
* BATCH_STARTED_GROUP
* BATCH_COMPLETED_GROUP
*
* These are groups that cover all sql statements and stored procedures executed against the
* database, and should not be used in combination with other groups as this will result in
* duplicate audit logs.
*
* For more information, see [Database-Level Audit Action
* Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups).
*
* For Database auditing policy, specific Actions can also be specified (note that Actions cannot
* be specified for Server auditing policy). The supported actions to audit are:
* SELECT
* UPDATE
* INSERT
* DELETE
* EXECUTE
* RECEIVE
* REFERENCES
*
* The general form for defining an action to be audited is:
* {action} ON {object} BY {principal}
*
* Note that <object> in the above format can refer to an object like a table, view, or stored
* procedure, or an entire database or schema. For the latter cases, the forms
* DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively.
*
* For example:
* SELECT on dbo.myTable by public
* SELECT on DATABASE::myDatabase by public
* SELECT on SCHEMA::mySchema by public
*
* For more information, see [Database-Level Audit
* Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions)
*/
auditActionsAndGroups?: string[];
/**
* Specifies the blob storage subscription Id.
*/
storageAccountSubscriptionId?: string;
/**
* Specifies whether storageAccountAccessKey value is the storage's secondary key.
*/
isStorageSecondaryKeyInUse?: boolean;
/**
* Specifies whether audit events are sent to Azure Monitor.
* In order to send the events to Azure Monitor, specify 'State' as 'Enabled' and
* 'IsAzureMonitorTargetEnabled' as true.
*
* When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents'
* diagnostic logs category on the database should be also created.
* Note that for server level audit you should use the 'master' database as {databaseName}.
*
* Diagnostic Settings URI format:
* PUT
* https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview
*
* For more information, see [Diagnostic Settings REST
* API](https://go.microsoft.com/fwlink/?linkid=2033207)
* or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043)
*/
isAzureMonitorTargetEnabled?: boolean;
}
/**
* Properties for an Azure SQL Database Vulnerability Assessment rule baseline's result.
*/
export interface DatabaseVulnerabilityAssessmentRuleBaselineItem {
/**
* The rule baseline result
*/
result: string[];
}
/**
* A database vulnerability assessment rule baseline.
*/
export interface DatabaseVulnerabilityAssessmentRuleBaseline extends ProxyResource {
/**
* The rule baseline result
*/
baselineResults: DatabaseVulnerabilityAssessmentRuleBaselineItem[];
}
/**
* Properties of a Vulnerability Assessment recurring scans.
*/
export interface VulnerabilityAssessmentRecurringScansProperties {
/**
* Recurring scans state.
*/
isEnabled?: boolean;
/**
* Specifies that the schedule scan notification will be is sent to the subscription
* administrators.
*/
emailSubscriptionAdmins?: boolean;
/**
* Specifies an array of e-mail addresses to which the scan notification is sent.
*/
emails?: string[];
}
/**
* A database vulnerability assessment.
*/
export interface DatabaseVulnerabilityAssessment extends ProxyResource {
/**
* A blob storage container path to hold the scan results (e.g.
* https://myStorage.blob.core.windows.net/VaScans/). It is required if server level
* vulnerability assessment policy doesn't set
*/
storageContainerPath?: string;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in
* 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified,
* StorageContainerSasKey is required.
*/
storageContainerSasKey?: string;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results.
* If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* The recurring scans settings
*/
recurringScans?: VulnerabilityAssessmentRecurringScansProperties;
}
/**
* An Azure SQL job agent.
*/
export interface JobAgent extends TrackedResource {
/**
* The name and tier of the SKU.
*/
sku?: Sku;
/**
* Resource ID of the database to store job metadata in.
*/
databaseId: string;
/**
* The state of the job agent. Possible values include: 'Creating', 'Ready', 'Updating',
* 'Deleting', 'Disabled'
*/
readonly state?: string;
}
/**
* An update to an Azure SQL job agent.
*/
export interface JobAgentUpdate {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* A stored credential that can be used by a job to connect to target databases.
*/
export interface JobCredential extends ProxyResource {
/**
* The credential user name.
*/
username: string;
/**
* The credential password.
*/
password: string;
}
/**
* The target that a job execution is executed on.
*/
export interface JobExecutionTarget {
/**
* The type of the target. Possible values include: 'TargetGroup', 'SqlDatabase',
* 'SqlElasticPool', 'SqlShardMap', 'SqlServer'
*/
readonly type?: string;
/**
* The server name.
*/
readonly serverName?: string;
/**
* The database name.
*/
readonly databaseName?: string;
}
/**
* An execution of a job
*/
export interface JobExecution extends ProxyResource {
/**
* The job version number.
*/
readonly jobVersion?: number;
/**
* The job step name.
*/
readonly stepName?: string;
/**
* The job step id.
*/
readonly stepId?: number;
/**
* The unique identifier of the job execution.
*/
readonly jobExecutionId?: string;
/**
* The detailed state of the job execution. Possible values include: 'Created', 'InProgress',
* 'WaitingForChildJobExecutions', 'WaitingForRetry', 'Succeeded', 'SucceededWithSkipped',
* 'Failed', 'TimedOut', 'Canceled', 'Skipped'
*/
readonly lifecycle?: string;
/**
* The ARM provisioning state of the job execution. Possible values include: 'Created',
* 'InProgress', 'Succeeded', 'Failed', 'Canceled'
*/
readonly provisioningState?: string;
/**
* The time that the job execution was created.
*/
readonly createTime?: Date;
/**
* The time that the job execution started.
*/
readonly startTime?: Date;
/**
* The time that the job execution completed.
*/
readonly endTime?: Date;
/**
* Number of times the job execution has been attempted.
*/
currentAttempts?: number;
/**
* Start time of the current attempt.
*/
readonly currentAttemptStartTime?: Date;
/**
* The last status or error message.
*/
readonly lastMessage?: string;
/**
* The target that this execution is executed on.
*/
readonly target?: JobExecutionTarget;
}
/**
* Scheduling properties of a job.
*/
export interface JobSchedule {
/**
* Schedule start time.
*/
startTime?: Date;
/**
* Schedule end time.
*/
endTime?: Date;
/**
* Schedule interval type. Possible values include: 'Once', 'Recurring'
*/
type?: string;
/**
* Whether or not the schedule is enabled.
*/
enabled?: boolean;
/**
* Value of the schedule's recurring interval, if the schedule type is recurring. ISO8601
* duration format.
*/
interval?: string;
}
/**
* A job.
*/
export interface Job extends ProxyResource {
/**
* User-defined description of the job.
*/
description?: string;
/**
* The job version number.
*/
readonly version?: number;
/**
* Schedule properties of the job.
*/
schedule?: JobSchedule;
}
/**
* The action to be executed by a job step.
*/
export interface JobStepAction {
/**
* Type of action being executed by the job step. Possible values include: 'TSql'
*/
type?: string;
/**
* The source of the action to execute. Possible values include: 'Inline'
*/
source?: string;
/**
* The action value, for example the text of the T-SQL script to execute.
*/
value: string;
}
/**
* The output configuration of a job step.
*/
export interface JobStepOutput {
/**
* The output destination type. Possible values include: 'SqlDatabase'
*/
type?: string;
/**
* The output destination subscription id.
*/
subscriptionId?: string;
/**
* The output destination resource group.
*/
resourceGroupName?: string;
/**
* The output destination server name.
*/
serverName: string;
/**
* The output destination database.
*/
databaseName: string;
/**
* The output destination schema.
*/
schemaName?: string;
/**
* The output destination table.
*/
tableName: string;
/**
* The resource ID of the credential to use to connect to the output destination.
*/
credential: string;
}
/**
* The execution options of a job step.
*/
export interface JobStepExecutionOptions {
/**
* Execution timeout for the job step.
*/
timeoutSeconds?: number;
/**
* Maximum number of times the job step will be reattempted if the first attempt fails.
*/
retryAttempts?: number;
/**
* Initial delay between retries for job step execution.
*/
initialRetryIntervalSeconds?: number;
/**
* The maximum amount of time to wait between retries for job step execution.
*/
maximumRetryIntervalSeconds?: number;
/**
* The backoff multiplier for the time between retries.
*/
retryIntervalBackoffMultiplier?: number;
}
/**
* A job step.
*/
export interface JobStep extends ProxyResource {
/**
* The job step's index within the job. If not specified when creating the job step, it will be
* created as the last step. If not specified when updating the job step, the step id is not
* modified.
*/
stepId?: number;
/**
* The resource ID of the target group that the job step will be executed on.
*/
targetGroup: string;
/**
* The resource ID of the job credential that will be used to connect to the targets.
*/
credential: string;
/**
* The action payload of the job step.
*/
action: JobStepAction;
/**
* Output destination properties of the job step.
*/
output?: JobStepOutput;
/**
* Execution options for the job step.
*/
executionOptions?: JobStepExecutionOptions;
}
/**
* A job target, for example a specific database or a container of databases that is evaluated
* during job execution.
*/
export interface JobTarget {
/**
* Whether the target is included or excluded from the group. Possible values include: 'Include',
* 'Exclude'
*/
membershipType?: string;
/**
* The target type. Possible values include: 'TargetGroup', 'SqlDatabase', 'SqlElasticPool',
* 'SqlShardMap', 'SqlServer'
*/
type: string;
/**
* The target server name.
*/
serverName?: string;
/**
* The target database name.
*/
databaseName?: string;
/**
* The target elastic pool name.
*/
elasticPoolName?: string;
/**
* The target shard map.
*/
shardMapName?: string;
/**
* The resource ID of the credential that is used during job execution to connect to the target
* and determine the list of databases inside the target.
*/
refreshCredential?: string;
}
/**
* A group of job targets.
*/
export interface JobTargetGroup extends ProxyResource {
/**
* Members of the target group.
*/
members: JobTarget[];
}
/**
* A job version.
*/
export interface JobVersion extends ProxyResource {
}
/**
* A long term retention backup.
*/
export interface LongTermRetentionBackup extends ProxyResource {
/**
* The server name that the backup database belong to.
*/
readonly serverName?: string;
/**
* The create time of the server.
*/
readonly serverCreateTime?: Date;
/**
* The name of the database the backup belong to
*/
readonly databaseName?: string;
/**
* The delete time of the database
*/
readonly databaseDeletionTime?: Date;
/**
* The time the backup was taken
*/
readonly backupTime?: Date;
/**
* The time the long term retention backup will expire.
*/
readonly backupExpirationTime?: Date;
}
/**
* A long term retention policy.
*/
export interface BackupLongTermRetentionPolicy extends ProxyResource {
/**
* The weekly retention policy for an LTR backup in an ISO 8601 format.
*/
weeklyRetention?: string;
/**
* The monthly retention policy for an LTR backup in an ISO 8601 format.
*/
monthlyRetention?: string;
/**
* The yearly retention policy for an LTR backup in an ISO 8601 format.
*/
yearlyRetention?: string;
/**
* The week of year to take the yearly backup in an ISO 8601 format.
*/
weekOfYear?: number;
}
/**
* A short term retention policy.
*/
export interface ManagedBackupShortTermRetentionPolicy extends ProxyResource {
/**
* The backup retention period in days. This is how many days Point-in-Time Restore will be
* supported.
*/
retentionDays?: number;
}
/**
* Contains the information necessary to perform a complete database restore operation.
*/
export interface CompleteDatabaseRestoreDefinition {
/**
* The last backup name to apply
*/
lastBackupName: string;
}
/**
* A managed database resource.
*/
export interface ManagedDatabase extends TrackedResource {
/**
* Collation of the managed database.
*/
collation?: string;
/**
* Status of the database. Possible values include: 'Online', 'Offline', 'Shutdown', 'Creating',
* 'Inaccessible', 'Updating'
*/
readonly status?: string;
/**
* Creation date of the database.
*/
readonly creationDate?: Date;
/**
* Earliest restore point in time for point in time restore.
*/
readonly earliestRestorePoint?: Date;
/**
* Conditional. If createMode is PointInTimeRestore, this value is required. Specifies the point
* in time (ISO8601 format) of the source database that will be restored to create the new
* database.
*/
restorePointInTime?: Date;
/**
* Geo paired region.
*/
readonly defaultSecondaryLocation?: string;
/**
* Collation of the metadata catalog. Possible values include: 'DATABASE_DEFAULT',
* 'SQL_Latin1_General_CP1_CI_AS'
*/
catalogCollation?: string;
/**
* Managed database create mode. PointInTimeRestore: Create a database by restoring a point in
* time backup of an existing database. SourceDatabaseName, SourceManagedInstanceName and
* PointInTime must be specified. RestoreExternalBackup: Create a database by restoring from
* external backup files. Collation, StorageContainerUri and StorageContainerSasToken must be
* specified. Recovery: Creates a database by restoring a geo-replicated backup.
* RecoverableDatabaseId must be specified as the recoverable database resource ID to restore.
* Possible values include: 'Default', 'RestoreExternalBackup', 'PointInTimeRestore', 'Recovery'
*/
createMode?: string;
/**
* Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the uri
* of the storage container where backups for this restore are stored.
*/
storageContainerUri?: string;
/**
* The resource identifier of the source database associated with create operation of this
* database.
*/
sourceDatabaseId?: string;
/**
* The restorable dropped database resource id to restore when creating this database.
*/
restorableDroppedDatabaseId?: string;
/**
* Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the
* storage container sas token.
*/
storageContainerSasToken?: string;
/**
* Instance Failover Group resource identifier that this managed database belongs to.
*/
readonly failoverGroupId?: string;
/**
* The resource identifier of the recoverable database associated with create operation of this
* database.
*/
recoverableDatabaseId?: string;
}
/**
* An managed database update.
*/
export interface ManagedDatabaseUpdate {
/**
* Collation of the managed database.
*/
collation?: string;
/**
* Status of the database. Possible values include: 'Online', 'Offline', 'Shutdown', 'Creating',
* 'Inaccessible', 'Updating'
*/
readonly status?: string;
/**
* Creation date of the database.
*/
readonly creationDate?: Date;
/**
* Earliest restore point in time for point in time restore.
*/
readonly earliestRestorePoint?: Date;
/**
* Conditional. If createMode is PointInTimeRestore, this value is required. Specifies the point
* in time (ISO8601 format) of the source database that will be restored to create the new
* database.
*/
restorePointInTime?: Date;
/**
* Geo paired region.
*/
readonly defaultSecondaryLocation?: string;
/**
* Collation of the metadata catalog. Possible values include: 'DATABASE_DEFAULT',
* 'SQL_Latin1_General_CP1_CI_AS'
*/
catalogCollation?: string;
/**
* Managed database create mode. PointInTimeRestore: Create a database by restoring a point in
* time backup of an existing database. SourceDatabaseName, SourceManagedInstanceName and
* PointInTime must be specified. RestoreExternalBackup: Create a database by restoring from
* external backup files. Collation, StorageContainerUri and StorageContainerSasToken must be
* specified. Recovery: Creates a database by restoring a geo-replicated backup.
* RecoverableDatabaseId must be specified as the recoverable database resource ID to restore.
* Possible values include: 'Default', 'RestoreExternalBackup', 'PointInTimeRestore', 'Recovery'
*/
createMode?: string;
/**
* Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the uri
* of the storage container where backups for this restore are stored.
*/
storageContainerUri?: string;
/**
* The resource identifier of the source database associated with create operation of this
* database.
*/
sourceDatabaseId?: string;
/**
* The restorable dropped database resource id to restore when creating this database.
*/
restorableDroppedDatabaseId?: string;
/**
* Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the
* storage container sas token.
*/
storageContainerSasToken?: string;
/**
* Instance Failover Group resource identifier that this managed database belongs to.
*/
readonly failoverGroupId?: string;
/**
* The resource identifier of the recoverable database associated with create operation of this
* database.
*/
recoverableDatabaseId?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Automatic tuning properties for individual advisors.
*/
export interface AutomaticTuningServerOptions {
/**
* Automatic tuning option desired state. Possible values include: 'Off', 'On', 'Default'
*/
desiredState?: string;
/**
* Automatic tuning option actual state. Possible values include: 'Off', 'On'
*/
readonly actualState?: string;
/**
* Reason code if desired and actual state are different.
*/
readonly reasonCode?: number;
/**
* Reason description if desired and actual state are different. Possible values include:
* 'Default', 'Disabled', 'AutoConfigured'
*/
readonly reasonDesc?: string;
}
/**
* Server-level Automatic Tuning.
*/
export interface ServerAutomaticTuning extends ProxyResource {
/**
* Automatic tuning desired state. Possible values include: 'Custom', 'Auto', 'Unspecified'
*/
desiredState?: string;
/**
* Automatic tuning actual state. Possible values include: 'Custom', 'Auto', 'Unspecified'
*/
readonly actualState?: string;
/**
* Automatic tuning options definition.
*/
options?: { [propertyName: string]: AutomaticTuningServerOptions };
}
/**
* A server DNS alias.
*/
export interface ServerDnsAlias extends ProxyResource {
/**
* The fully qualified DNS record for alias
*/
readonly azureDnsRecord?: string;
}
/**
* A server DNS alias acquisition request.
*/
export interface ServerDnsAliasAcquisition {
/**
* The id of the server alias that will be acquired to point to this server instead.
*/
oldServerDnsAliasId?: string;
}
/**
* A server security alert policy.
*/
export interface ServerSecurityAlertPolicy extends ProxyResource {
/**
* Specifies the state of the policy, whether it is enabled or disabled or a policy has not been
* applied yet on the specific database. Possible values include: 'New', 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection,
* Sql_Injection_Vulnerability, Access_Anomaly, Data_Exfiltration, Unsafe_Action
*/
disabledAlerts?: string[];
/**
* Specifies an array of e-mail addresses to which the alert is sent.
*/
emailAddresses?: string[];
/**
* Specifies that the alert is sent to the account administrators.
*/
emailAccountAdmins?: boolean;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob
* storage will hold all Threat Detection audit logs.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the Threat Detection audit storage account.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the Threat Detection audit logs.
*/
retentionDays?: number;
/**
* Specifies the UTC creation time of the policy.
*/
readonly creationTime?: Date;
}
/**
* A restorable dropped managed database resource.
*/
export interface RestorableDroppedManagedDatabase extends TrackedResource {
/**
* The name of the database.
*/
readonly databaseName?: string;
/**
* The creation date of the database (ISO8601 format).
*/
readonly creationDate?: Date;
/**
* The deletion date of the database (ISO8601 format).
*/
readonly deletionDate?: Date;
/**
* The earliest restore date of the database (ISO8601 format).
*/
readonly earliestRestoreDate?: Date;
}
/**
* Database restore points.
*/
export interface RestorePoint extends ProxyResource {
/**
* Resource location.
*/
readonly location?: string;
/**
* The type of restore point. Possible values include: 'CONTINUOUS', 'DISCRETE'
*/
readonly restorePointType?: string;
/**
* The earliest time to which this database can be restored
*/
readonly earliestRestoreDate?: Date;
/**
* The time the backup was taken
*/
readonly restorePointCreationDate?: Date;
/**
* The label of restore point for backup request by user
*/
readonly restorePointLabel?: string;
}
/**
* Contains the information necessary to perform a create database restore point operation.
*/
export interface CreateDatabaseRestorePointDefinition {
/**
* The restore point label to apply
*/
restorePointLabel: string;
}
/**
* A managed database security alert policy.
*/
export interface ManagedDatabaseSecurityAlertPolicy extends ProxyResource {
/**
* Specifies the state of the policy, whether it is enabled or disabled or a policy has not been
* applied yet on the specific database. Possible values include: 'New', 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection,
* Sql_Injection_Vulnerability, Access_Anomaly, Data_Exfiltration, Unsafe_Action
*/
disabledAlerts?: string[];
/**
* Specifies an array of e-mail addresses to which the alert is sent.
*/
emailAddresses?: string[];
/**
* Specifies that the alert is sent to the account administrators.
*/
emailAccountAdmins?: boolean;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob
* storage will hold all Threat Detection audit logs.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the Threat Detection audit storage account.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the Threat Detection audit logs.
*/
retentionDays?: number;
/**
* Specifies the UTC creation time of the policy.
*/
readonly creationTime?: Date;
}
/**
* A managed server security alert policy.
*/
export interface ManagedServerSecurityAlertPolicy extends ProxyResource {
/**
* Specifies the state of the policy, whether it is enabled or disabled or a policy has not been
* applied yet on the specific database. Possible values include: 'New', 'Enabled', 'Disabled'
*/
state: string;
/**
* Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection,
* Sql_Injection_Vulnerability, Access_Anomaly, Data_Exfiltration, Unsafe_Action
*/
disabledAlerts?: string[];
/**
* Specifies an array of e-mail addresses to which the alert is sent.
*/
emailAddresses?: string[];
/**
* Specifies that the alert is sent to the account administrators.
*/
emailAccountAdmins?: boolean;
/**
* Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob
* storage will hold all Threat Detection audit logs.
*/
storageEndpoint?: string;
/**
* Specifies the identifier key of the Threat Detection audit storage account.
*/
storageAccountAccessKey?: string;
/**
* Specifies the number of days to keep in the Threat Detection audit logs.
*/
retentionDays?: number;
/**
* Specifies the UTC creation time of the policy.
*/
readonly creationTime?: Date;
}
/**
* A sensitivity label.
*/
export interface SensitivityLabel extends ProxyResource {
/**
* The label name.
*/
labelName?: string;
/**
* The label ID.
*/
labelId?: string;
/**
* The information type.
*/
informationType?: string;
/**
* The information type ID.
*/
informationTypeId?: string;
}
/**
* A database operation.
*/
export interface DatabaseOperation extends ProxyResource {
/**
* The name of the database the operation is being performed on.
*/
readonly databaseName?: string;
/**
* The name of operation.
*/
readonly operation?: string;
/**
* The friendly name of operation.
*/
readonly operationFriendlyName?: string;
/**
* The percentage of the operation completed.
*/
readonly percentComplete?: number;
/**
* The name of the server.
*/
readonly serverName?: string;
/**
* The operation start time.
*/
readonly startTime?: Date;
/**
* The operation state. Possible values include: 'Pending', 'InProgress', 'Succeeded', 'Failed',
* 'CancelInProgress', 'Cancelled'
*/
readonly state?: string;
/**
* The operation error code.
*/
readonly errorCode?: number;
/**
* The operation error description.
*/
readonly errorDescription?: string;
/**
* The operation error severity.
*/
readonly errorSeverity?: number;
/**
* Whether or not the error is a user error.
*/
readonly isUserError?: boolean;
/**
* The estimated completion time of the operation.
*/
readonly estimatedCompletionTime?: Date;
/**
* The operation description.
*/
readonly description?: string;
/**
* Whether the operation can be cancelled.
*/
readonly isCancellable?: boolean;
}
/**
* A elastic pool operation.
*/
export interface ElasticPoolOperation extends ProxyResource {
/**
* The name of the elastic pool the operation is being performed on.
*/
readonly elasticPoolName?: string;
/**
* The name of operation.
*/
readonly operation?: string;
/**
* The friendly name of operation.
*/
readonly operationFriendlyName?: string;
/**
* The percentage of the operation completed.
*/
readonly percentComplete?: number;
/**
* The name of the server.
*/
readonly serverName?: string;
/**
* The operation start time.
*/
readonly startTime?: Date;
/**
* The operation state.
*/
readonly state?: string;
/**
* The operation error code.
*/
readonly errorCode?: number;
/**
* The operation error description.
*/
readonly errorDescription?: string;
/**
* The operation error severity.
*/
readonly errorSeverity?: number;
/**
* Whether or not the error is a user error.
*/
readonly isUserError?: boolean;
/**
* The estimated completion time of the operation.
*/
readonly estimatedCompletionTime?: Date;
/**
* The operation description.
*/
readonly description?: string;
/**
* Whether the operation can be cancelled.
*/
readonly isCancellable?: boolean;
}
/**
* The maximum size capability.
*/
export interface MaxSizeCapability {
/**
* The maximum size limit (see 'unit' for the units).
*/
readonly limit?: number;
/**
* The units that the limit is expressed in. Possible values include: 'Megabytes', 'Gigabytes',
* 'Terabytes', 'Petabytes'
*/
readonly unit?: string;
}
/**
* The log size capability.
*/
export interface LogSizeCapability {
/**
* The log size limit (see 'unit' for the units).
*/
readonly limit?: number;
/**
* The units that the limit is expressed in. Possible values include: 'Megabytes', 'Gigabytes',
* 'Terabytes', 'Petabytes', 'Percent'
*/
readonly unit?: string;
}
/**
* The maximum size range capability.
*/
export interface MaxSizeRangeCapability {
/**
* Minimum value.
*/
readonly minValue?: MaxSizeCapability;
/**
* Maximum value.
*/
readonly maxValue?: MaxSizeCapability;
/**
* Scale/step size for discrete values between the minimum value and the maximum value.
*/
readonly scaleSize?: MaxSizeCapability;
/**
* Size of transaction log.
*/
readonly logSize?: LogSizeCapability;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The performance level capability.
*/
export interface PerformanceLevelCapability {
/**
* Performance level value.
*/
readonly value?: number;
/**
* Unit type used to measure performance level. Possible values include: 'DTU', 'VCores'
*/
readonly unit?: string;
}
/**
* The license type capability
*/
export interface LicenseTypeCapability {
/**
* License type identifier.
*/
readonly name?: string;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The service objectives capability.
*/
export interface ServiceObjectiveCapability {
/**
* The unique ID of the service objective.
*/
readonly id?: string;
/**
* The service objective name.
*/
readonly name?: string;
/**
* The list of supported maximum database sizes.
*/
readonly supportedMaxSizes?: MaxSizeRangeCapability[];
/**
* The performance level.
*/
readonly performanceLevel?: PerformanceLevelCapability;
/**
* The sku.
*/
readonly sku?: Sku;
/**
* List of supported license types.
*/
readonly supportedLicenseTypes?: LicenseTypeCapability[];
/**
* The included (free) max size.
*/
readonly includedMaxSize?: MaxSizeCapability;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The edition capability.
*/
export interface EditionCapability {
/**
* The database edition name.
*/
readonly name?: string;
/**
* The list of supported service objectives for the edition.
*/
readonly supportedServiceLevelObjectives?: ServiceObjectiveCapability[];
/**
* Whether or not zone redundancy is supported for the edition.
*/
readonly zoneRedundant?: boolean;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The minimum per-database performance level capability.
*/
export interface ElasticPoolPerDatabaseMinPerformanceLevelCapability {
/**
* The minimum performance level per database.
*/
readonly limit?: number;
/**
* Unit type used to measure performance level. Possible values include: 'DTU', 'VCores'
*/
readonly unit?: string;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The max per-database performance level capability.
*/
export interface ElasticPoolPerDatabaseMaxPerformanceLevelCapability {
/**
* The maximum performance level per database.
*/
readonly limit?: number;
/**
* Unit type used to measure performance level. Possible values include: 'DTU', 'VCores'
*/
readonly unit?: string;
/**
* The list of supported min database performance levels.
*/
readonly supportedPerDatabaseMinPerformanceLevels?: ElasticPoolPerDatabaseMinPerformanceLevelCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The Elastic Pool performance level capability.
*/
export interface ElasticPoolPerformanceLevelCapability {
/**
* The performance level for the pool.
*/
readonly performanceLevel?: PerformanceLevelCapability;
/**
* The sku.
*/
readonly sku?: Sku;
/**
* List of supported license types.
*/
readonly supportedLicenseTypes?: LicenseTypeCapability[];
/**
* The maximum number of databases supported.
*/
readonly maxDatabaseCount?: number;
/**
* The included (free) max size for this performance level.
*/
readonly includedMaxSize?: MaxSizeCapability;
/**
* The list of supported max sizes.
*/
readonly supportedMaxSizes?: MaxSizeRangeCapability[];
/**
* The list of supported per database max sizes.
*/
readonly supportedPerDatabaseMaxSizes?: MaxSizeRangeCapability[];
/**
* The list of supported per database max performance levels.
*/
readonly supportedPerDatabaseMaxPerformanceLevels?: ElasticPoolPerDatabaseMaxPerformanceLevelCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The elastic pool edition capability.
*/
export interface ElasticPoolEditionCapability {
/**
* The elastic pool edition name.
*/
readonly name?: string;
/**
* The list of supported elastic pool DTU levels for the edition.
*/
readonly supportedElasticPoolPerformanceLevels?: ElasticPoolPerformanceLevelCapability[];
/**
* Whether or not zone redundancy is supported for the edition.
*/
readonly zoneRedundant?: boolean;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The server capability
*/
export interface ServerVersionCapability {
/**
* The server version name.
*/
readonly name?: string;
/**
* The list of supported database editions.
*/
readonly supportedEditions?: EditionCapability[];
/**
* The list of supported elastic pool editions.
*/
readonly supportedElasticPoolEditions?: ElasticPoolEditionCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The managed instance virtual cores capability.
*/
export interface ManagedInstanceVcoresCapability {
/**
* The virtual cores identifier.
*/
readonly name?: string;
/**
* The virtual cores value.
*/
readonly value?: number;
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The managed server family capability.
*/
export interface ManagedInstanceFamilyCapability {
/**
* Family name.
*/
readonly name?: string;
/**
* SKU name.
*/
readonly sku?: string;
/**
* List of supported license types.
*/
readonly supportedLicenseTypes?: LicenseTypeCapability[];
/**
* List of supported virtual cores values.
*/
readonly supportedVcoresValues?: ManagedInstanceVcoresCapability[];
/**
* Included size.
*/
readonly includedMaxSize?: MaxSizeCapability;
/**
* Storage size ranges.
*/
readonly supportedStorageSizes?: MaxSizeRangeCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The managed server capability
*/
export interface ManagedInstanceEditionCapability {
/**
* The managed server version name.
*/
readonly name?: string;
/**
* The supported families.
*/
readonly supportedFamilies?: ManagedInstanceFamilyCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The managed instance capability
*/
export interface ManagedInstanceVersionCapability {
/**
* The server version name.
*/
readonly name?: string;
/**
* The list of supported managed instance editions.
*/
readonly supportedEditions?: ManagedInstanceEditionCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* The location capability.
*/
export interface LocationCapabilities {
/**
* The location name.
*/
readonly name?: string;
/**
* The list of supported server versions.
*/
readonly supportedServerVersions?: ServerVersionCapability[];
/**
* The list of supported managed instance versions.
*/
readonly supportedManagedInstanceVersions?: ManagedInstanceVersionCapability[];
/**
* The status of the capability. Possible values include: 'Visible', 'Available', 'Default',
* 'Disabled'
*/
readonly status?: string;
/**
* The reason for the capability not being available.
*/
reason?: string;
}
/**
* A database resource.
*/
export interface Database extends TrackedResource {
/**
* The name and tier of the SKU.
*/
sku?: Sku;
/**
* Kind of database. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* Resource that manages the database.
*/
readonly managedBy?: string;
/**
* Specifies the mode of database creation.
*
* Default: regular database creation.
*
* Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified
* as the resource ID of the source database.
*
* Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId
* must be specified as the resource ID of the existing primary database.
*
* PointInTimeRestore: Creates a database by restoring a point in time backup of an existing
* database. sourceDatabaseId must be specified as the resource ID of the existing database, and
* restorePointInTime must be specified.
*
* Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be
* specified as the recoverable database resource ID to restore.
*
* Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must
* be specified. If sourceDatabaseId is the database's original resource ID, then
* sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the
* restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored.
* restorePointInTime may also be specified to restore from an earlier point in time.
*
* RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention
* vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point
* resource ID.
*
* Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse
* edition. Possible values include: 'Default', 'Copy', 'Secondary', 'PointInTimeRestore',
* 'Restore', 'Recovery', 'RestoreExternalBackup', 'RestoreExternalBackupSecondary',
* 'RestoreLongTermRetentionBackup', 'OnlineSecondary'
*/
createMode?: string;
/**
* The collation of the database.
*/
collation?: string;
/**
* The max size of the database expressed in bytes.
*/
maxSizeBytes?: number;
/**
* The name of the sample schema to apply when creating this database. Possible values include:
* 'AdventureWorksLT', 'WideWorldImportersStd', 'WideWorldImportersFull'
*/
sampleName?: string;
/**
* The resource identifier of the elastic pool containing this database.
*/
elasticPoolId?: string;
/**
* The resource identifier of the source database associated with create operation of this
* database.
*/
sourceDatabaseId?: string;
/**
* The status of the database. Possible values include: 'Online', 'Restoring', 'RecoveryPending',
* 'Recovering', 'Suspect', 'Offline', 'Standby', 'Shutdown', 'EmergencyMode', 'AutoClosed',
* 'Copying', 'Creating', 'Inaccessible', 'OfflineSecondary', 'Pausing', 'Paused', 'Resuming',
* 'Scaling'
*/
readonly status?: string;
/**
* The ID of the database.
*/
readonly databaseId?: string;
/**
* The creation date of the database (ISO8601 format).
*/
readonly creationDate?: Date;
/**
* The current service level objective name of the database.
*/
readonly currentServiceObjectiveName?: string;
/**
* The requested service level objective name of the database.
*/
readonly requestedServiceObjectiveName?: string;
/**
* The default secondary region for this database.
*/
readonly defaultSecondaryLocation?: string;
/**
* Failover Group resource identifier that this database belongs to.
*/
readonly failoverGroupId?: string;
/**
* Specifies the point in time (ISO8601 format) of the source database that will be restored to
* create the new database.
*/
restorePointInTime?: Date;
/**
* Specifies the time that the database was deleted.
*/
sourceDatabaseDeletionDate?: Date;
/**
* The resource identifier of the recovery point associated with create operation of this
* database.
*/
recoveryServicesRecoveryPointId?: string;
/**
* The resource identifier of the long term retention backup associated with create operation of
* this database.
*/
longTermRetentionBackupResourceId?: string;
/**
* The resource identifier of the recoverable database associated with create operation of this
* database.
*/
recoverableDatabaseId?: string;
/**
* The resource identifier of the restorable dropped database associated with create operation of
* this database.
*/
restorableDroppedDatabaseId?: string;
/**
* Collation of the metadata catalog. Possible values include: 'DATABASE_DEFAULT',
* 'SQL_Latin1_General_CP1_CI_AS'
*/
catalogCollation?: string;
/**
* Whether or not this database is zone redundant, which means the replicas of this database will
* be spread across multiple availability zones.
*/
zoneRedundant?: boolean;
/**
* The license type to apply for this database. Possible values include: 'LicenseIncluded',
* 'BasePrice'
*/
licenseType?: string;
/**
* The max log size for this database.
*/
readonly maxLogSizeBytes?: number;
/**
* This records the earliest start date and time that restore is available for this database
* (ISO8601 format).
*/
readonly earliestRestoreDate?: Date;
/**
* The state of read-only routing. If enabled, connections that have application intent set to
* readonly in their connection string may be routed to a readonly secondary replica in the same
* region. Possible values include: 'Enabled', 'Disabled'
*/
readScale?: string;
/**
* The name and tier of the SKU.
*/
readonly currentSku?: Sku;
}
/**
* A database resource.
*/
export interface DatabaseUpdate {
/**
* The name and tier of the SKU.
*/
sku?: Sku;
/**
* Specifies the mode of database creation.
*
* Default: regular database creation.
*
* Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified
* as the resource ID of the source database.
*
* Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId
* must be specified as the resource ID of the existing primary database.
*
* PointInTimeRestore: Creates a database by restoring a point in time backup of an existing
* database. sourceDatabaseId must be specified as the resource ID of the existing database, and
* restorePointInTime must be specified.
*
* Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be
* specified as the recoverable database resource ID to restore.
*
* Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must
* be specified. If sourceDatabaseId is the database's original resource ID, then
* sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the
* restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored.
* restorePointInTime may also be specified to restore from an earlier point in time.
*
* RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention
* vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point
* resource ID.
*
* Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse
* edition. Possible values include: 'Default', 'Copy', 'Secondary', 'PointInTimeRestore',
* 'Restore', 'Recovery', 'RestoreExternalBackup', 'RestoreExternalBackupSecondary',
* 'RestoreLongTermRetentionBackup', 'OnlineSecondary'
*/
createMode?: string;
/**
* The collation of the database.
*/
collation?: string;
/**
* The max size of the database expressed in bytes.
*/
maxSizeBytes?: number;
/**
* The name of the sample schema to apply when creating this database. Possible values include:
* 'AdventureWorksLT', 'WideWorldImportersStd', 'WideWorldImportersFull'
*/
sampleName?: string;
/**
* The resource identifier of the elastic pool containing this database.
*/
elasticPoolId?: string;
/**
* The resource identifier of the source database associated with create operation of this
* database.
*/
sourceDatabaseId?: string;
/**
* The status of the database. Possible values include: 'Online', 'Restoring', 'RecoveryPending',
* 'Recovering', 'Suspect', 'Offline', 'Standby', 'Shutdown', 'EmergencyMode', 'AutoClosed',
* 'Copying', 'Creating', 'Inaccessible', 'OfflineSecondary', 'Pausing', 'Paused', 'Resuming',
* 'Scaling'
*/
readonly status?: string;
/**
* The ID of the database.
*/
readonly databaseId?: string;
/**
* The creation date of the database (ISO8601 format).
*/
readonly creationDate?: Date;
/**
* The current service level objective name of the database.
*/
readonly currentServiceObjectiveName?: string;
/**
* The requested service level objective name of the database.
*/
readonly requestedServiceObjectiveName?: string;
/**
* The default secondary region for this database.
*/
readonly defaultSecondaryLocation?: string;
/**
* Failover Group resource identifier that this database belongs to.
*/
readonly failoverGroupId?: string;
/**
* Specifies the point in time (ISO8601 format) of the source database that will be restored to
* create the new database.
*/
restorePointInTime?: Date;
/**
* Specifies the time that the database was deleted.
*/
sourceDatabaseDeletionDate?: Date;
/**
* The resource identifier of the recovery point associated with create operation of this
* database.
*/
recoveryServicesRecoveryPointId?: string;
/**
* The resource identifier of the long term retention backup associated with create operation of
* this database.
*/
longTermRetentionBackupResourceId?: string;
/**
* The resource identifier of the recoverable database associated with create operation of this
* database.
*/
recoverableDatabaseId?: string;
/**
* The resource identifier of the restorable dropped database associated with create operation of
* this database.
*/
restorableDroppedDatabaseId?: string;
/**
* Collation of the metadata catalog. Possible values include: 'DATABASE_DEFAULT',
* 'SQL_Latin1_General_CP1_CI_AS'
*/
catalogCollation?: string;
/**
* Whether or not this database is zone redundant, which means the replicas of this database will
* be spread across multiple availability zones.
*/
zoneRedundant?: boolean;
/**
* The license type to apply for this database. Possible values include: 'LicenseIncluded',
* 'BasePrice'
*/
licenseType?: string;
/**
* The max log size for this database.
*/
readonly maxLogSizeBytes?: number;
/**
* This records the earliest start date and time that restore is available for this database
* (ISO8601 format).
*/
readonly earliestRestoreDate?: Date;
/**
* The state of read-only routing. If enabled, connections that have application intent set to
* readonly in their connection string may be routed to a readonly secondary replica in the same
* region. Possible values include: 'Enabled', 'Disabled'
*/
readScale?: string;
/**
* The name and tier of the SKU.
*/
readonly currentSku?: Sku;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Contains the information necessary to perform a resource move (rename).
*/
export interface ResourceMoveDefinition {
/**
* The target ID for the resource
*/
id: string;
}
/**
* Per database settings of an elastic pool.
*/
export interface ElasticPoolPerDatabaseSettings {
/**
* The minimum capacity all databases are guaranteed.
*/
minCapacity?: number;
/**
* The maximum capacity any one database can consume.
*/
maxCapacity?: number;
}
/**
* An elastic pool.
*/
export interface ElasticPool extends TrackedResource {
sku?: Sku;
/**
* Kind of elastic pool. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* The state of the elastic pool. Possible values include: 'Creating', 'Ready', 'Disabled'
*/
readonly state?: string;
/**
* The creation date of the elastic pool (ISO8601 format).
*/
readonly creationDate?: Date;
/**
* The storage limit for the database elastic pool in bytes.
*/
maxSizeBytes?: number;
/**
* The per database settings for the elastic pool.
*/
perDatabaseSettings?: ElasticPoolPerDatabaseSettings;
/**
* Whether or not this elastic pool is zone redundant, which means the replicas of this elastic
* pool will be spread across multiple availability zones.
*/
zoneRedundant?: boolean;
/**
* The license type to apply for this elastic pool. Possible values include: 'LicenseIncluded',
* 'BasePrice'
*/
licenseType?: string;
}
/**
* An elastic pool update.
*/
export interface ElasticPoolUpdate {
sku?: Sku;
/**
* The storage limit for the database elastic pool in bytes.
*/
maxSizeBytes?: number;
/**
* The per database settings for the elastic pool.
*/
perDatabaseSettings?: ElasticPoolPerDatabaseSettings;
/**
* Whether or not this elastic pool is zone redundant, which means the replicas of this elastic
* pool will be spread across multiple availability zones.
*/
zoneRedundant?: boolean;
/**
* The license type to apply for this elastic pool. Possible values include: 'LicenseIncluded',
* 'BasePrice'
*/
licenseType?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Properties of a vulnerability assessment scan error.
*/
export interface VulnerabilityAssessmentScanError {
/**
* The error code.
*/
readonly code?: string;
/**
* The error message.
*/
readonly message?: string;
}
/**
* A vulnerability assessment scan record.
*/
export interface VulnerabilityAssessmentScanRecord extends ProxyResource {
/**
* The scan ID.
*/
readonly scanId?: string;
/**
* The scan trigger type. Possible values include: 'OnDemand', 'Recurring'
*/
readonly triggerType?: string;
/**
* The scan status. Possible values include: 'Passed', 'Failed', 'FailedToRun', 'InProgress'
*/
readonly state?: string;
/**
* The scan start time (UTC).
*/
readonly startTime?: Date;
/**
* The scan end time (UTC).
*/
readonly endTime?: Date;
/**
* The scan errors.
*/
readonly errors?: VulnerabilityAssessmentScanError[];
/**
* The scan results storage container path.
*/
readonly storageContainerPath?: string;
/**
* The number of failed security checks.
*/
readonly numberOfFailedSecurityChecks?: number;
}
/**
* A database Vulnerability Assessment scan export resource.
*/
export interface DatabaseVulnerabilityAssessmentScansExport extends ProxyResource {
/**
* Location of the exported report (e.g.
* https://myStorage.blob.core.windows.net/VaScans/scans/serverName/databaseName/scan_scanId.xlsx).
*/
readonly exportedReportLocation?: string;
}
/**
* Read-write endpoint of the failover group instance.
*/
export interface InstanceFailoverGroupReadWriteEndpoint {
/**
* Failover policy of the read-write endpoint for the failover group. If failoverPolicy is
* Automatic then failoverWithDataLossGracePeriodMinutes is required. Possible values include:
* 'Manual', 'Automatic'
*/
failoverPolicy: string;
/**
* Grace period before failover with data loss is attempted for the read-write endpoint. If
* failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required.
*/
failoverWithDataLossGracePeriodMinutes?: number;
}
/**
* Read-only endpoint of the failover group instance.
*/
export interface InstanceFailoverGroupReadOnlyEndpoint {
/**
* Failover policy of the read-only endpoint for the failover group. Possible values include:
* 'Disabled', 'Enabled'
*/
failoverPolicy?: string;
}
/**
* Partner region information for the failover group.
*/
export interface PartnerRegionInfo {
/**
* Geo location of the partner managed instances.
*/
location?: string;
/**
* Replication role of the partner managed instances. Possible values include: 'Primary',
* 'Secondary'
*/
readonly replicationRole?: string;
}
/**
* Pairs of Managed Instances in the failover group.
*/
export interface ManagedInstancePairInfo {
/**
* Id of Primary Managed Instance in pair.
*/
primaryManagedInstanceId?: string;
/**
* Id of Partner Managed Instance in pair.
*/
partnerManagedInstanceId?: string;
}
/**
* An instance failover group.
*/
export interface InstanceFailoverGroup extends ProxyResource {
/**
* Read-write endpoint of the failover group instance.
*/
readWriteEndpoint: InstanceFailoverGroupReadWriteEndpoint;
/**
* Read-only endpoint of the failover group instance.
*/
readOnlyEndpoint?: InstanceFailoverGroupReadOnlyEndpoint;
/**
* Local replication role of the failover group instance. Possible values include: 'Primary',
* 'Secondary'
*/
readonly replicationRole?: string;
/**
* Replication state of the failover group instance.
*/
readonly replicationState?: string;
/**
* Partner region information for the failover group.
*/
partnerRegions: PartnerRegionInfo[];
/**
* List of managed instance pairs in the failover group.
*/
managedInstancePairs: ManagedInstancePairInfo[];
}
/**
* A short term retention policy.
*/
export interface BackupShortTermRetentionPolicy extends ProxyResource {
/**
* The backup retention period in days. This is how many days Point-in-Time Restore will be
* supported.
*/
retentionDays?: number;
}
/**
* A TDE certificate that can be uploaded into a server.
*/
export interface TdeCertificate extends ProxyResource {
/**
* The base64 encoded certificate private blob.
*/
privateBlob: string;
/**
* The certificate password.
*/
certPassword?: string;
}
/**
* A managed instance key.
*/
export interface ManagedInstanceKey extends ProxyResource {
/**
* Kind of encryption protector. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* The key type like 'ServiceManaged', 'AzureKeyVault'. Possible values include:
* 'ServiceManaged', 'AzureKeyVault'
*/
serverKeyType: string;
/**
* The URI of the key. If the ServerKeyType is AzureKeyVault, then the URI is required.
*/
uri?: string;
/**
* Thumbprint of the key.
*/
readonly thumbprint?: string;
/**
* The key creation date.
*/
readonly creationDate?: Date;
}
/**
* The managed instance encryption protector.
*/
export interface ManagedInstanceEncryptionProtector extends ProxyResource {
/**
* Kind of encryption protector. This is metadata used for the Azure portal experience.
*/
readonly kind?: string;
/**
* The name of the managed instance key.
*/
serverKeyName?: string;
/**
* The encryption protector type like 'ServiceManaged', 'AzureKeyVault'. Possible values include:
* 'ServiceManaged', 'AzureKeyVault'
*/
serverKeyType: string;
/**
* The URI of the server key.
*/
readonly uri?: string;
/**
* Thumbprint of the server key.
*/
readonly thumbprint?: string;
}
/**
* A recoverable managed database resource.
*/
export interface RecoverableManagedDatabase extends ProxyResource {
/**
* The last available backup date.
*/
readonly lastAvailableBackupDate?: string;
}
/**
* A managed instance vulnerability assessment.
*/
export interface ManagedInstanceVulnerabilityAssessment extends ProxyResource {
/**
* A blob storage container path to hold the scan results (e.g.
* https://myStorage.blob.core.windows.net/VaScans/).
*/
storageContainerPath: string;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in
* 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified,
* StorageContainerSasKey is required.
*/
storageContainerSasKey?: string;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results.
* If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* The recurring scans settings
*/
recurringScans?: VulnerabilityAssessmentRecurringScansProperties;
}
/**
* A server vulnerability assessment.
*/
export interface ServerVulnerabilityAssessment extends ProxyResource {
/**
* A blob storage container path to hold the scan results (e.g.
* https://myStorage.blob.core.windows.net/VaScans/).
*/
storageContainerPath: string;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in
* 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified,
* StorageContainerSasKey is required.
*/
storageContainerSasKey?: string;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results.
* If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required.
*/
storageAccountAccessKey?: string;
/**
* The recurring scans settings
*/
recurringScans?: VulnerabilityAssessmentRecurringScansProperties;
}
/**
* The response to a list recoverable databases request
*/
export interface RecoverableDatabaseListResult extends Array<RecoverableDatabase> {
}
/**
* The response to a list restorable dropped databases request
*/
export interface RestorableDroppedDatabaseListResult extends Array<RestorableDroppedDatabase> {
}
/**
* A list of servers.
*/
export interface ServerListResult extends Array<Server> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* The response to a list data masking rules request.
*/
export interface DataMaskingRuleListResult extends Array<DataMaskingRule> {
}
/**
* Represents the response to a List Firewall Rules request.
*/
export interface FirewallRuleListResult extends Array<FirewallRule> {
}
/**
* The response to a list geo backup policies request.
*/
export interface GeoBackupPolicyListResult extends Array<GeoBackupPolicy> {
}
/**
* The response to a list database metrics request.
*/
export interface MetricListResult extends Array<Metric> {
}
/**
* The response to a list database metric definitions request.
*/
export interface MetricDefinitionListResult extends Array<MetricDefinition> {
}
/**
* A list of databases.
*/
export interface DatabaseListResult extends Array<Database> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* The result of an elastic pool list request.
*/
export interface ElasticPoolListResult extends Array<ElasticPool> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* Represents the response to a list recommended elastic pool request.
*/
export interface RecommendedElasticPoolListResult extends Array<RecommendedElasticPool> {
}
/**
* Represents the response to a list recommended elastic pool metrics request.
*/
export interface RecommendedElasticPoolListMetricsResult extends
Array<RecommendedElasticPoolMetric> {
}
/**
* Represents the response to a List database replication link request.
*/
export interface ReplicationLinkListResult extends Array<ReplicationLink> {
}
/**
* The response to a list Active Directory Administrators request.
*/
export interface ServerAdministratorListResult extends Array<ServerAzureADAdministrator> {
}
/**
* A list of server communication links.
*/
export interface ServerCommunicationLinkListResult extends Array<ServerCommunicationLink> {
}
/**
* Represents the response to a get database service objectives request.
*/
export interface ServiceObjectiveListResult extends Array<ServiceObjective> {
}
/**
* Represents the response to a list elastic pool activity request.
*/
export interface ElasticPoolActivityListResult extends Array<ElasticPoolActivity> {
}
/**
* Represents the response to a list elastic pool database activity request.
*/
export interface ElasticPoolDatabaseActivityListResult extends Array<ElasticPoolDatabaseActivity> {
}
/**
* Represents the response to a list service tier advisor request.
*/
export interface ServiceTierAdvisorListResult extends Array<ServiceTierAdvisor> {
}
/**
* Represents the response to a list database transparent data encryption activity request.
*/
export interface TransparentDataEncryptionActivityListResult extends
Array<TransparentDataEncryptionActivity> {
}
/**
* Represents the response to a list server metrics request.
*/
export interface ServerUsageListResult extends Array<ServerUsage> {
}
/**
* The response to a list database metrics request.
*/
export interface DatabaseUsageListResult extends Array<DatabaseUsage> {
}
/**
* A list of server encryption protectors.
*/
export interface EncryptionProtectorListResult extends Array<EncryptionProtector> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of failover groups.
*/
export interface FailoverGroupListResult extends Array<FailoverGroup> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of managed instances.
*/
export interface ManagedInstanceListResult extends Array<ManagedInstance> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* Result of the request to list SQL operations.
*/
export interface OperationListResult extends Array<Operation> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of server keys.
*/
export interface ServerKeyListResult extends Array<ServerKey> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync agents.
*/
export interface SyncAgentListResult extends Array<SyncAgent> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync agent linked databases.
*/
export interface SyncAgentLinkedDatabaseListResult extends Array<SyncAgentLinkedDatabase> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync database ID properties.
*/
export interface SyncDatabaseIdListResult extends Array<SyncDatabaseIdProperties> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync schema properties.
*/
export interface SyncFullSchemaPropertiesListResult extends Array<SyncFullSchemaProperties> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync group log properties.
*/
export interface SyncGroupLogListResult extends Array<SyncGroupLogProperties> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sync groups.
*/
export interface SyncGroupListResult extends Array<SyncGroup> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of Azure SQL Database sync members.
*/
export interface SyncMemberListResult extends Array<SyncMember> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of subscription usage metrics in a location.
*/
export interface SubscriptionUsageListResult extends Array<SubscriptionUsage> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of virtual clusters.
*/
export interface VirtualClusterListResult extends Array<VirtualCluster> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of virtual network rules.
*/
export interface VirtualNetworkRuleListResult extends Array<VirtualNetworkRule> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the database's vulnerability assessments.
*/
export interface DatabaseVulnerabilityAssessmentListResult extends
Array<DatabaseVulnerabilityAssessment> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of Azure SQL job agents.
*/
export interface JobAgentListResult extends Array<JobAgent> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of job credentials.
*/
export interface JobCredentialListResult extends Array<JobCredential> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of job executions.
*/
export interface JobExecutionListResult extends Array<JobExecution> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of jobs.
*/
export interface JobListResult extends Array<Job> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of job steps.
*/
export interface JobStepListResult extends Array<JobStep> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of target groups.
*/
export interface JobTargetGroupListResult extends Array<JobTargetGroup> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of job versions.
*/
export interface JobVersionListResult extends Array<JobVersion> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of long term retention backups.
*/
export interface LongTermRetentionBackupListResult extends Array<LongTermRetentionBackup> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of short term retention policies.
*/
export interface ManagedBackupShortTermRetentionPolicyListResult extends
Array<ManagedBackupShortTermRetentionPolicy> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of managed databases.
*/
export interface ManagedDatabaseListResult extends Array<ManagedDatabase> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of server DNS aliases.
*/
export interface ServerDnsAliasListResult extends Array<ServerDnsAlias> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the server's security alert policies.
*/
export interface LogicalServerSecurityAlertPolicyListResult extends
Array<ServerSecurityAlertPolicy> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of restorable dropped managed databases.
*/
export interface RestorableDroppedManagedDatabaseListResult extends
Array<RestorableDroppedManagedDatabase> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of long term retention backups.
*/
export interface RestorePointListResult extends Array<RestorePoint> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the managed database's security alert policies.
*/
export interface ManagedDatabaseSecurityAlertPolicyListResult extends
Array<ManagedDatabaseSecurityAlertPolicy> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the managed Server's security alert policies.
*/
export interface ManagedServerSecurityAlertPolicyListResult extends
Array<ManagedServerSecurityAlertPolicy> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of sensitivity labels.
*/
export interface SensitivityLabelListResult extends Array<SensitivityLabel> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* The response to a list database operations request
*/
export interface DatabaseOperationListResult extends Array<DatabaseOperation> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* The response to a list elastic pool operations request
*/
export interface ElasticPoolOperationListResult extends Array<ElasticPoolOperation> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of vulnerability assessment scan records.
*/
export interface VulnerabilityAssessmentScanRecordListResult extends
Array<VulnerabilityAssessmentScanRecord> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of instance failover groups.
*/
export interface InstanceFailoverGroupListResult extends Array<InstanceFailoverGroup> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of short term retention policies.
*/
export interface BackupShortTermRetentionPolicyListResult extends
Array<BackupShortTermRetentionPolicy> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of managed instance keys.
*/
export interface ManagedInstanceKeyListResult extends Array<ManagedInstanceKey> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of managed instance encryption protectors.
*/
export interface ManagedInstanceEncryptionProtectorListResult extends
Array<ManagedInstanceEncryptionProtector> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of recoverable managed databases.
*/
export interface RecoverableManagedDatabaseListResult extends Array<RecoverableManagedDatabase> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the ManagedInstance's vulnerability assessments.
*/
export interface ManagedInstanceVulnerabilityAssessmentListResult extends
Array<ManagedInstanceVulnerabilityAssessment> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
}
/**
* A list of the server's vulnerability assessments.
*/
export interface ServerVulnerabilityAssessmentListResult extends
Array<ServerVulnerabilityAssessment> {
/**
* Link to retrieve next page of results.
*/
readonly nextLink?: string;
} | the_stack |
import adaptor, { Adaptor, FirebaseWriteBatch } from '../adaptor'
import { Collection } from '../collection'
import { Ref } from '../ref'
import { unwrapData } from '../data'
import { UpdateModel } from '../update'
import { Field } from '../field'
import { SetModel } from '../set'
import { UpsetModel } from '../upset'
/**
* The batch API object. It unions a set of functions ({@link Batch.set|set},
* {@link Batch.update|update}, {@link Batch.remove|remove}) that are
* similar to regular set, update and remove with the only difference that
* the batch counterparts do not return a promise and perform operations only
* when {@link Batch.commit|commit} function is called.
*/
export interface Batch {
/**
* Sets a document to the given data.
*
* ```ts
* import { batch, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* const { set, commit } = batch()
*
* for (let count = 0; count < 500; count++) {
* set(counters, count.toString(), { count })
* }
*
* commit()
* ```
*
* @param ref - The reference to the document to set
* @param data - The document data
*/
set<Model>(ref: Ref<Model>, data: SetModel<Model>): void
/**
* @param collection - The collection to set document in
* @param id - The id of the document to set
* @param data - The document data
*/
set<Model>(
collection: Collection<Model>,
id: string,
data: SetModel<Model>
): void
/**
* Sets or updates a document with the given data.
*
* ```ts
* import { batch, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* const { upset, commit } = batch()
*
* for (let count = 0; count < 500; count++) {
* upset(counters, count.toString(), { count })
* }
*
* commit()
* ```
*
* @param ref - The reference to the document to set or update
* @param data - The document data
*/
upset<Model>(ref: Ref<Model>, data: UpsetModel<Model>): void
/**
* @param collection - The collection to set or update document in
* @param id - The id of the document to set or update
* @param data - The document data
*/
upset<Model>(
collection: Collection<Model>,
id: string,
data: UpsetModel<Model>
): void
/**
* Updates a document.
*
* ```ts
* import { batch, field, collection } from 'typesaurus'
*
* type Counter = { count: number, meta: { updatedAt: number } }
* const counters = collection<Counter>('counters')
*
* const { update, commit } = batch()
*
* for (let count = 0; count < 500; count++) {
* update(counters, count.toString(), { count: count + 1 })
* // or using field paths:
* update(counters, count.toString(), [
* field('count', count + 1),
* field(['meta', 'updatedAt'], Date.now())
* ])
* }
*
* commit()
* ```
*
* @returns void
*
* @param collection - The collection to update document in
* @param id - The id of the document to update
* @param data - The document data to update
*/
update<Model>(
collection: Collection<Model>,
id: string,
data: Field<Model>[]
): void
/**
* @param ref - The reference to the document to set
* @param data - The document data to update
*/
update<Model>(ref: Ref<Model>, data: Field<Model>[]): void
/**
* @param collection - The collection to update document in
* @param id - The id of the document to update
* @param data - The document data to update
*/
update<Model>(
collection: Collection<Model>,
id: string,
data: UpdateModel<Model>
): void
/**
* @param ref - The reference to the document to set
* @param data - The document data to update
*/
update<Model>(ref: Ref<Model>, data: UpdateModel<Model>): void
/**
* Removes a document.
*
* ```ts
* import { batch, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* const { remove, commit } = batch()
*
* for (let count = 0; count < 500; count++) {
* remove(counters, count.toString())
* }
*
* commit()
* ```
*
* @returns A promise that resolves when the operation is complete
*
* @param collection - The collection to remove document in
* @param id - The id of the documented to remove
*/
remove<Model>(collection: Collection<Model>, id: string): void
/**
* @param ref - The reference to the document to remove
*/
remove<Model>(ref: Ref<Model>): void
/**
* Starts the execution of the operations in the batch.
*
* @returns A promise that resolves when the operations are finished
*/
commit(): Promise<void>
}
/**
* Creates {@link Batch|batch API} with a set of functions ({@link Batch.set|set},
* {@link Batch.upset|upset}, {@link Batch.update|update}, {@link Batch.remove|remove})
* that are similar to regular set, update and remove with the only difference
* that the batch counterparts do not return a promise and perform operations
* only when {@link Batch.commit|commit} function is called.
*
* ```ts
* import { batch, collection } from 'typesaurus'
*
* type Counter = { count: number }
* const counters = collection<Counter>('counters')
*
* const { set, update, remove, commit } = batch()
*
* for (let count = 0; count < 500; count++) {
* // Each batch can be up to 500 set, update and remove operations
* set(counters, count.toString(), { count })
* }
*
* // Set 500 documents
* commit().then(() => console.log('Done!'))
* ```
*
* @returns The batch API object.
*/
export function batch(): Batch {
const commands: BatchCommand[] = []
const firestoreBatch = lazy(async () => {
const { firestore } = await adaptor()
return firestore.batch()
})
function set<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | SetModel<Model>,
maybeData?: SetModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: SetModel<Model>
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as SetModel<Model>
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as SetModel<Model>
}
commands.push((adaptor, firestoreBatch) => {
const firestoreDoc = adaptor.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above and below because is all the same as in the regular set function
firestoreBatch.set(firestoreDoc, unwrapData(adaptor, data))
})
}
function upset<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | UpsetModel<Model>,
maybeData?: UpsetModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: UpsetModel<Model>
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as UpsetModel<Model>
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as UpsetModel<Model>
}
commands.push((adaptor, firestoreBatch) => {
const firestoreDoc = adaptor.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above and below because is all the same as in the regular set function
firestoreBatch.set(firestoreDoc, unwrapData(adaptor, data), {
merge: true
})
})
}
function update<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
idOrData: string | Field<Model>[] | UpdateModel<Model>,
maybeData?: Field<Model>[] | UpdateModel<Model>
): void {
let collection: Collection<Model>
let id: string
let data: Model
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = idOrData as string
data = maybeData as Model
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
data = idOrData as Model
}
commands.push((adaptor, firestoreBatch) => {
const firebaseDoc = adaptor.firestore.collection(collection.path).doc(id)
const updateData = Array.isArray(data)
? data.reduce(
(acc, { key, value }) => {
acc[Array.isArray(key) ? key.join('.') : key] = value
return acc
},
{} as { [key: string]: any }
)
: data
// ^ above
// TODO: Refactor code above because is all the same as in the regular update function
firestoreBatch.update(firebaseDoc, unwrapData(adaptor, updateData))
})
}
function remove<Model>(
collectionOrRef: Collection<Model> | Ref<Model>,
maybeId?: string
): void {
let collection: Collection<Model>
let id: string
if (collectionOrRef.__type__ === 'collection') {
collection = collectionOrRef as Collection<Model>
id = maybeId as string
} else {
const ref = collectionOrRef as Ref<Model>
collection = ref.collection
id = ref.id
}
commands.push((adaptor, firestoreBatch) => {
const firebaseDoc = adaptor.firestore.collection(collection.path).doc(id)
// ^ above
// TODO: Refactor code above because is all the same as in the regular remove function
firestoreBatch.delete(firebaseDoc)
})
}
async function commit() {
const a = await adaptor()
const b = a.firestore.batch()
commands.forEach(fn => fn(a, b))
await b.commit()
}
return { set, upset, update, remove, commit }
}
type BatchCommand = (adaptor: Adaptor, batch: FirebaseWriteBatch) => void
function lazy<Type>(fn: () => Promise<Type>): () => Promise<Type> {
let instance: Type | undefined = undefined
return async () => {
if (instance === undefined) instance = await fn()
return instance
}
} | the_stack |
require('es6-promise').polyfill();
import * as Bacon from "../..";
import { expect } from "chai";
import { TickScheduler } from "./TickScheduler";
import { mockFunction } from "./Mock"
import { fail } from "assert";
export const sc = TickScheduler();
Bacon.setScheduler(sc);
export const expectError = (errorText: string, f: any) => expect(f).to.throw(Error, errorText);
export const lessThan = (limit: number) => (x: number) => x < limit;
export const times = (x: number, y: number) => x * y;
export const add = (x: number, y: number) => x + y;
export const id = (x: any) => x;
export const activate = (obs: Bacon.Observable<any>) => {
obs.onValue(() => undefined);
return obs;
};
export const take = (count: number, obs: Bacon.Observable<any>) => obs.take(count);
export const map = (obs: Bacon.Observable<any>, f: any) => obs.map(f);
export const skip = (count: number, obs: Bacon.Observable<any>) => obs.skip(count);
export const later = (delay: number, value: any = "defaultEvent") => Bacon.later(delay, value);
export const fromPoll = Bacon.fromPoll;
export const sequentially = Bacon.sequentially;
export const repeatedly = Bacon.repeatedly;
export const fromArray = Bacon.fromArray;
export const once = Bacon.once;
export const mergeAll = Bacon.mergeAll;
export const testSideEffects = (wrapper: Function, method: string) => () =>
it("(f) calls function with property value", () => {
const f = mockFunction()
wrapper("kaboom")[method](f)
deferred(() => f.verify("kaboom"))
})
export const t = id
let seqs: any[] = [];
const verifyCleanup_ = () => {
for (let seq of seqs) {
expect(seq.source.dispatcher.hasSubscribers()).to.deep.equal(false);
}
seqs = [];
};
function regSrc<V>(source: Bacon.EventStream<V>) {
seqs.push({ source });
return source;
};
export function series<V>(interval: number, values: (V | Bacon.Event<V>)[]): Bacon.EventStream<V> { return regSrc(sequentially<V>(t(interval), values)) }
export function repeat<V>(interval: number, values: (V | Bacon.Event<V>)[]): Bacon.EventStream<V> { return regSrc(repeatedly<V>(t(interval), values)) }
export function error(msg: string = "") { return new Bacon.Error(msg) }
export function soon(f: any) { setTimeout(f, t(1)) };
declare global {
interface Array<T> {
extraTest: string
}
}
Array.prototype.extraTest = "Testing how this works with extra fields in Array prototype";
// Some streams are (semi)unstable when testing with verifySwitching2.
// Generally, all flatMap-based streams are at least semi-unstable because flatMap discards
// child streams on unsubscribe.
//
// semiunstable=events may be lost if subscribers are removed altogether between events
// unstable=events may be inconsistent for subscribers that are added between events
export const unstable = { unstable: true, semiunstable: true };
export const semiunstable = { semiunstable: true };
export const atGivenTimes = (timesAndValues: any[]) => {
const startTime = sc.now();
return Bacon.fromBinder((sink) => {
let shouldStop = false;
var schedule = (timeOffset: number, index: number) => {
const first = timesAndValues[index];
const scheduledTime = first[0];
const delay = (scheduledTime - sc.now()) + startTime;
const push = () => {
if (shouldStop) {
return;
}
const value = first[1];
sink(new Bacon.Next(value));
if (!shouldStop && ((index+1) < timesAndValues.length)) {
return schedule(scheduledTime, index+1);
} else {
return sink(new Bacon.End());
}
};
return sc.setTimeout(push, delay);
};
schedule(0, 0);
return () => shouldStop = true;
});
};
const browser = (typeof window === "object");
if (browser) {
console.log("Running in browser, narrowing test set");
}
export const expectStreamTimings = (src: () => Bacon.EventStream<any>, expectedEventsAndTimings: any[], options: any = undefined) => {
const srcWithRelativeTime = () => {
const { now } = sc;
const t0 = now();
const relativeTime = () => Math.floor(now() - t0);
const withRelativeTime = (x: any) => [relativeTime(), x];
return src().transform((e, sink) => {
e = e.fmap(withRelativeTime);
return sink(e);
});
};
return expectStreamEvents(srcWithRelativeTime, expectedEventsAndTimings, options);
};
export const expectStreamEvents = (src: () => Bacon.Observable<any>, expectedEvents: any[], param: any = undefined) => {
return verifySingleSubscriber(src, expectedEvents);
};
export const expectPropertyEvents = (src: () => Bacon.Observable<any>, expectedEvents: any[], param: any = {}) => {
const {unstable, semiunstable, extraCheck} = param;
expect(expectedEvents.length > 0).to.deep.equal(true, "at least one expected event is specified");
verifyPSingleSubscriber(src, expectedEvents, extraCheck);
if (!browser) {
verifyPLateEval(src, expectedEvents);
if (!unstable) {
verifyPIntermittentSubscriber(src, expectedEvents);
verifyPSwitching(src, justValues(expectedEvents));
}
if (!(unstable || semiunstable)) {
return verifyPSwitchingAggressively(src, justValues(expectedEvents));
}
}
};
var verifyPSingleSubscriber = (srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[], extraCheck: (Function | undefined) = undefined) =>
verifyPropertyWith("(single subscriber)", srcF, expectedEvents, ((src: Bacon.Observable<any>, events: Bacon.Event<any>[], done: (err: (Error | void)) => any) => {
let gotInitial = false;
let gotNext = false;
let sync = true;
src.subscribe((event: Bacon.Event<any>) => {
if (event.isEnd) {
done(undefined);
return Bacon.noMore;
} else {
if (event.isInitial) {
if (gotInitial) { done(new Error(`got more than one Initial event: ${toValue(event)}`)); }
if (gotNext) { done(new Error(`got Initial event after the Next one: ${toValue(event)}`)); }
if (!sync) { done(new Error(`got async Initial event: ${toValue(event)}`)); }
gotInitial = true;
} else if (event.hasValue) {
gotNext = true;
}
events.push(event);
return Bacon.more
}
});
return sync = false;
}), extraCheck)
;
var verifyPLateEval = (srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[]) =>
verifyPropertyWith("(late eval)", srcF, expectedEvents, (src: Bacon.Observable<any>, events: Bacon.Event<any>[], done: () => any) =>
src.subscribe((event) => {
if (event.isEnd) {
return done();
} else {
return events.push(event);
}
})
)
;
var verifyPIntermittentSubscriber = (srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[]) =>
verifyPropertyWith("(with intermittent subscriber)", srcF, expectedEvents, (src, events, done) => {
const otherEvents: Bacon.Event<any>[] = [];
take(1, src).subscribe((e: Bacon.Event<any>) => {
otherEvents.push(e)
return undefined;
});
return src.subscribe((event: Bacon.Event<any>) => {
if (event.isEnd) {
const expectedValues = events.filter(e => e.hasValue).slice(0, 1);
const gotValues = otherEvents.filter(e => e.hasValue);
// verify that the "side subscriber" got expected values
expect(toValues(gotValues)).to.deep.equal(toValues(expectedValues));
done();
return Bacon.noMore
} else {
events.push(event);
return Bacon.more
}
});
})
;
const verifyPSwitching = (srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[]) =>
verifyPropertyWith("(switching subscribers)", srcF, expectedEvents, (src, events, done) =>
src.subscribe((event: Bacon.Event<any>) => {
if (event.isEnd) {
done();
return Bacon.noMore;
} else {
if (event.hasValue) {
src.subscribe((event: Bacon.Event<any>) => {
if (Bacon.isInitial(event)) {
events.push(event);
}
return Bacon.noMore;
});
}
}
})
)
;
const verifyPSwitchingAggressively = (srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[]) =>
describe("(switching aggressively)", () => {
let src: Bacon.Observable<any>;
const events: Bacon.Event<any>[] = [];
let idCounter = 0;
before(() => src = srcF());
before((done) => {
let unsub: (Bacon.Unsub | null);
var newSink = () => {
const myId = ++idCounter;
//console.log "new sub", myId
unsub = null;
let gotMine = false;
return (event: Bacon.Event<any>) => {
//console.log "at", sc.now(), "got", event, "for", myId
if (event.isEnd && (myId === idCounter)) {
done();
return Bacon.noMore
} else if (event.hasValue) {
if (gotMine) {
//console.log " -> ditch it"
if (unsub != null) {
unsub();
}
unsub = src.subscribe(newSink());
return Bacon.noMore;
} else {
//console.log " -> take it"
gotMine = true;
events.push(toValue(event));
return Bacon.more
}
}
};
};
return unsub = src.subscribe(newSink());
});
it("outputs expected values in order", () => expect(events).to.deep.equal(toValues(expectedEvents)));
})
;
const verifyPropertyWith = (description: string, srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[], collectF: (src: Bacon.Observable<any>, events: Bacon.Event<any>[], done: () => void) => void, extraCheck: (Function | undefined) = undefined) =>
describe(description, () => {
let src: Bacon.Observable<any>;
const events: Bacon.Event<any>[] = [];
before(() => src = srcF());
before(done => collectF(src, events, done));
it("is a Property", () => expect((<any>src)._isProperty).to.deep.equal(true));
it("outputs expected events in order", () => expect(toValues(events)).to.deep.equal(toValues(expectedEvents)));
it("has correct final state", () => verifyFinalState(src, lastNonError(expectedEvents)));
it("cleans up observers", verifyCleanup_);
if (extraCheck != undefined) {
extraCheck();
}
})
;
export const verifySingleSubscriber = (srcF: () => Bacon.Observable<any>, expectedEvents: any[]) => {
return verifyStreamWith("(single subscriber)", srcF, expectedEvents, (src, events, done) =>
src.subscribe((event: Bacon.Event<any>) => {
if (Bacon.isInitial(event)) {
fail("Got Initial event from stream")
}
if (event.isEnd) {
done();
return undefined;
} else {
expect(event.isInitial).to.deep.equal(false, "no Initial events");
events.push(toValue(event));
return undefined;
}
})
)
};
const verifyStreamWith = (description: string, srcF: () => Bacon.Observable<any>, expectedEvents: Bacon.Event<any>[], collectF: (src: Bacon.Observable<any>, events: Bacon.Event<any>[], done: () => void) => any) =>
describe(description, () => {
let src: Bacon.Observable<any>;
const events: Bacon.Event<any>[] = [];
before(() => {
src = srcF();
expect((<any>src)._isEventStream).to.equal(true, "is an EventStream");
});
before(done => collectF(src, events, done));
it("outputs expected values in order", () => expect(toValues(events)).to.deep.equal(toValues(expectedEvents)));
it("the stream is exhausted", () => verifyExhausted(src));
it("cleans up observers", verifyCleanup_);
})
;
const verifyExhausted = (src: Bacon.Observable<any>) => {
const events: Bacon.Event<any>[] = [];
src.subscribe((event: Bacon.Event<any>) => {
if (event === undefined) {
throw new Error("got undefined event");
}
events.push(event);
return Bacon.more
});
if (events.length === 0) {
throw new Error("got zero events");
}
expect(events[0].isEnd).to.deep.equal(true);
};
export const verifyCleanup = () =>
deferred(() => {
for (let seq of seqs) {
expect(seq.source.dispatcher.hasSubscribers()).to.deep.equal(false);
}
return seqs = [];
})
var lastNonError = (events: Bacon.Event<any>[]) => Bacon._.last(Bacon._.filter((e => toValue(e) !== "<error>"), events));
var verifyFinalState = (property: Bacon.Observable<any>, value: any) => {
const events: Bacon.Event<any>[] = [];
property.subscribe((event: Bacon.Event<any>) => {
events.push(event)
return Bacon.more;
});
return expect(toValues(events)).to.deep.equal(toValues([value, "<end>"]));
};
export const toValues = (xs: any[]) => xs.map(toValue);
export const toValue = (x: any) => {
switch (true) {
case !(x != null ? x.isEvent : undefined): return x;
case x.isError: return "<error>";
case x.isEnd: return "<end>";
default: return x.value;
}
};
var justValues = (xs: any[]) => Bacon._.filter(hasValue, xs);
var hasValue = (x: any) => toValue(x) !== "<error>";
declare var Promise: any
export const deferred = (f: () => any) =>
new Promise((resolve: () => void) => {
return setTimeout((() => {
f();
return resolve();
}), 1);
})
export const onUnsub: (stream: Bacon.EventStream<any>, f: () => any) => Bacon.EventStream<any> = (stream, f) => {
const desc = new Bacon.Desc(stream, "onUnsub", []);
new Bacon.EventStream(desc, (sink: Bacon.EventSink<any>) => {
const unsub = stream.subscribe(sink);
return () => {
f();
unsub();
};
});
return stream;
};
export function range(left: number, right: number, inclusive: boolean) {
let range = [];
let ascending = left < right;
let end = !inclusive ? right : ascending ? right + 1 : right - 1;
for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) {
range.push(i);
}
return range;
} | the_stack |
import { TreeNode, TreeIterator } from "../Base/Tree";
import { ContainerIterator, ContainerType } from "../Base/Base";
export interface SetType<T> extends ContainerType<T> {
/**
* Inserts element to Set.
*/
insert: (element: T) => void;
/**
* @return An iterator to the first element not less than the given key.
*/
lowerBound: (key: T) => ContainerIterator<T>;
/**
* @return An iterator to the first element greater than the given key.
*/
upperBound: (key: T) => ContainerIterator<T>;
/**
* @return An iterator to the first element not greater than the given key.
*/
reverseLowerBound: (key: T) => ContainerIterator<T>;
/**
* @return An iterator to the first element less than the given key.
*/
reverseUpperBound: (key: T) => ContainerIterator<T>;
/**
* Union the other Set to self.
*/
union: (other: SetType<T>) => void;
/**
* @return The height of the RB-tree.
*/
getHeight: () => number;
}
function Set<T>(this: SetType<T>, container: { forEach: (callback: (element: T) => void) => void } = [], cmp: (x: T, y: T) => number) {
cmp = cmp || ((x, y) => {
if (x < y) return -1;
if (x > y) return 1;
return 0;
});
let len = 0;
let root = new TreeNode<T, undefined>();
root.color = TreeNode.TreeNodeColorType.black;
const header = new TreeNode<T, undefined>();
header.parent = root;
root.parent = header;
this.size = function () {
return len;
};
this.empty = function () {
return len === 0;
};
this.clear = function () {
len = 0;
root.key = undefined;
root.leftChild = root.rightChild = root.brother = undefined;
header.leftChild = header.rightChild = undefined;
};
this.begin = function () {
return new TreeIterator(header.leftChild || header, header);
};
this.end = function () {
return new TreeIterator(header, header);
};
this.rBegin = function () {
return new TreeIterator(header.rightChild || header, header);
}
this.rEnd = function () {
return new TreeIterator(header, header);
}
const findSubTreeMinNode: (curNode: TreeNode<T, undefined>) => TreeNode<T, undefined> = function (curNode: TreeNode<T, undefined>) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
};
const findSubTreeMaxNode: (curNode: TreeNode<T, undefined>) => TreeNode<T, undefined> = function (curNode: TreeNode<T, undefined>) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
};
this.front = function () {
return header.leftChild?.key;
};
this.back = function () {
return header.rightChild?.key;
};
this.forEach = function (callback: (element: T, index: number) => void) {
let index = 0;
for (const element of this) callback(element, index++);
};
this.getElementByPos = function (pos: number) {
if (pos < 0 || pos >= this.size()) throw new Error("pos must more than 0 and less than set's size");
let index = 0;
for (const element of this) {
if (index === pos) return element;
++index;
}
throw new Error("unknown error");
};
const eraseNodeSelfBalance = function (curNode: TreeNode<T, undefined>) {
const parentNode = curNode.parent;
if (!parentNode || parentNode === header) {
if (curNode === root) return;
throw new Error("unknown error");
}
if (curNode.color === TreeNode.TreeNodeColorType.red) {
curNode.color = TreeNode.TreeNodeColorType.black;
return;
}
const brotherNode = curNode.brother;
if (!brotherNode) throw new Error("unknown error");
if (curNode === parentNode.leftChild) {
if (brotherNode.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.black;
parentNode.color = TreeNode.TreeNodeColorType.red;
const newRoot = parentNode.rotateLeft();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if (brotherNode.color === TreeNode.TreeNodeColorType.black) {
if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = parentNode.color;
parentNode.color = TreeNode.TreeNodeColorType.black;
if (brotherNode.rightChild) brotherNode.rightChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = parentNode.rotateLeft();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
curNode.color = TreeNode.TreeNodeColorType.black;
} else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
if (brotherNode.leftChild) brotherNode.leftChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = brotherNode.rotateRight();
if (root === brotherNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black)) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
eraseNodeSelfBalance(parentNode);
}
}
} else if (curNode === parentNode.rightChild) {
if (brotherNode.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.black;
parentNode.color = TreeNode.TreeNodeColorType.red;
const newRoot = parentNode.rotateRight();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if (brotherNode.color === TreeNode.TreeNodeColorType.black) {
if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = parentNode.color;
parentNode.color = TreeNode.TreeNodeColorType.black;
if (brotherNode.leftChild) brotherNode.leftChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = parentNode.rotateRight();
if (root === parentNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
curNode.color = TreeNode.TreeNodeColorType.black;
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode.TreeNodeColorType.red) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
if (brotherNode.rightChild) brotherNode.rightChild.color = TreeNode.TreeNodeColorType.black;
const newRoot = brotherNode.rotateLeft();
if (root === brotherNode) {
root = newRoot;
header.parent = root;
root.parent = header;
}
eraseNodeSelfBalance(curNode);
} else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode.TreeNodeColorType.black)) {
brotherNode.color = TreeNode.TreeNodeColorType.red;
eraseNodeSelfBalance(parentNode);
}
}
}
};
const eraseNode = function (curNode: TreeNode<T, undefined>) {
let swapNode: TreeNode<T, undefined> = curNode;
while (swapNode.leftChild || swapNode.rightChild) {
if (swapNode.rightChild) {
swapNode = findSubTreeMinNode(swapNode.rightChild);
const tmpKey = curNode.key;
curNode.key = swapNode.key;
swapNode.key = tmpKey;
curNode = swapNode;
}
if (swapNode.leftChild) {
swapNode = findSubTreeMaxNode(swapNode.leftChild);
const tmpKey = curNode.key;
curNode.key = swapNode.key;
swapNode.key = tmpKey;
curNode = swapNode;
}
}
if (swapNode.key === undefined) throw new Error("unknown error");
if (header.leftChild && header.leftChild.key !== undefined && cmp(header.leftChild.key, swapNode.key) === 0) {
if (header.leftChild !== root) header.leftChild = header.leftChild?.parent;
else if (header.leftChild?.rightChild) header.leftChild = header.leftChild?.rightChild;
else header.leftChild = undefined;
}
if (header.rightChild && header.rightChild.key !== undefined && cmp(header.rightChild.key, swapNode.key) === 0) {
if (header.rightChild !== root) header.rightChild = header.rightChild?.parent;
else if (header.rightChild?.leftChild) header.rightChild = header.rightChild?.leftChild;
else header.rightChild = undefined;
}
eraseNodeSelfBalance(swapNode);
if (swapNode) swapNode.remove();
--len;
root.color = TreeNode.TreeNodeColorType.black;
};
const inOrderTraversal: (curNode: TreeNode<T, undefined> | undefined, callback: (curNode: TreeNode<T, undefined>) => boolean) => boolean = function (curNode: TreeNode<T, undefined> | undefined, callback: (curNode: TreeNode<T, undefined>) => boolean) {
if (!curNode || curNode.key === undefined) return false;
const ifReturn = inOrderTraversal(curNode.leftChild, callback);
if (ifReturn) return true;
if (callback(curNode)) return true;
return inOrderTraversal(curNode.rightChild, callback);
};
this.eraseElementByPos = function (pos: number) {
if (pos < 0 || pos >= len) throw new Error("pos must more than 0 and less than set's size");
let index = 0;
inOrderTraversal(root, curNode => {
if (pos === index) {
eraseNode(curNode);
return true;
}
++index;
return false;
});
};
this.eraseElementByValue = function (value: T) {
if (this.empty()) return;
const curNode = findElementPos(root, value);
if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, value) !== 0) return;
eraseNode(curNode);
};
const findInsertPos: (curNode: TreeNode<T, undefined>, element: T) => TreeNode<T, undefined> = function (curNode: TreeNode<T, undefined>, element: T) {
if (!curNode || curNode.key === undefined) throw new Error("unknown error");
const cmpResult = cmp(element, curNode.key);
if (cmpResult < 0) {
if (!curNode.leftChild) {
curNode.leftChild = new TreeNode<T, undefined>();
curNode.leftChild.parent = curNode;
curNode.leftChild.brother = curNode.rightChild;
if (curNode.rightChild) curNode.rightChild.brother = curNode.leftChild;
return curNode.leftChild;
}
return findInsertPos(curNode.leftChild, element);
} else if (cmpResult > 0) {
if (!curNode.rightChild) {
curNode.rightChild = new TreeNode<T, undefined>();
curNode.rightChild.parent = curNode;
curNode.rightChild.brother = curNode.leftChild;
if (curNode.leftChild) curNode.leftChild.brother = curNode.rightChild;
return curNode.rightChild;
}
return findInsertPos(curNode.rightChild, element);
}
return curNode;
};
const insertNodeSelfBalance = function (curNode: TreeNode<T, undefined>) {
const parentNode = curNode.parent;
if (!parentNode || parentNode === header) {
if (curNode === root) return;
throw new Error("unknown error");
}
if (parentNode.color === TreeNode.TreeNodeColorType.black) return;
if (parentNode.color === TreeNode.TreeNodeColorType.red) {
const uncleNode = parentNode.brother;
const grandParent = parentNode.parent;
if (!grandParent) throw new Error("unknown error");
if (uncleNode && uncleNode.color === TreeNode.TreeNodeColorType.red) {
uncleNode.color = parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
insertNodeSelfBalance(grandParent);
} else if (!uncleNode || uncleNode.color === TreeNode.TreeNodeColorType.black) {
if (parentNode === grandParent.leftChild) {
if (curNode === parentNode.leftChild) {
parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
const newRoot = grandParent.rotateRight();
if (grandParent === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
} else if (curNode === parentNode.rightChild) {
const newRoot = parentNode.rotateLeft();
if (parentNode === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
insertNodeSelfBalance(parentNode);
}
} else if (parentNode === grandParent.rightChild) {
if (curNode === parentNode.leftChild) {
const newRoot = parentNode.rotateRight();
if (parentNode === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
insertNodeSelfBalance(parentNode);
} else if (curNode === parentNode.rightChild) {
parentNode.color = TreeNode.TreeNodeColorType.black;
grandParent.color = TreeNode.TreeNodeColorType.red;
const newRoot = grandParent.rotateLeft();
if (grandParent === root) {
root = newRoot;
header.parent = root;
root.parent = header;
}
}
}
}
}
};
this.insert = function (element: T) {
if (element === null || element === undefined) {
throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
}
if (this.empty()) {
++len;
root.key = element;
root.color = TreeNode.TreeNodeColorType.black;
header.leftChild = root;
header.rightChild = root;
return;
}
const curNode = findInsertPos(root, element);
if (curNode.key !== undefined && cmp(curNode.key, element) === 0) return;
++len;
curNode.key = element;
if (header.leftChild === undefined || header.leftChild.key === undefined || cmp(header.leftChild.key, element) > 0) {
header.leftChild = curNode;
}
if (header.rightChild === undefined || header.rightChild.key === undefined || cmp(header.rightChild.key, element) < 0) {
header.rightChild = curNode;
}
insertNodeSelfBalance(curNode);
root.color = TreeNode.TreeNodeColorType.black;
};
const findElementPos: (curNode: TreeNode<T, undefined> | undefined, element: T) => TreeNode<T, undefined> | undefined = function (curNode: TreeNode<T, undefined> | undefined, element: T) {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(element, curNode.key);
if (cmpResult < 0) return findElementPos(curNode.leftChild, element);
else if (cmpResult > 0) return findElementPos(curNode.rightChild, element);
return curNode;
};
this.find = function (element: T) {
const curNode = findElementPos(root, element);
if (curNode !== undefined && curNode.key !== undefined) return new TreeIterator(curNode, header);
return this.end();
};
const _lowerBound: (curNode: TreeNode<T, undefined> | undefined, key: T) => TreeNode<T, undefined> | undefined = (curNode: TreeNode<T, undefined> | undefined, key: T) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult === 0) return curNode;
if (cmpResult < 0) return _lowerBound(curNode.rightChild, key);
const resNode = _lowerBound(curNode.leftChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.lowerBound = function (key: T) {
const resNode = _lowerBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _upperBound: (curNode: TreeNode<T, undefined> | undefined, key: T) => TreeNode<T, undefined> | undefined = (curNode: TreeNode<T, undefined> | undefined, key: T) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult <= 0) return _upperBound(curNode.rightChild, key);
const resNode = _upperBound(curNode.leftChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.upperBound = function (key: T) {
const resNode = _upperBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _reverseLowerBound: (curNode: TreeNode<T, undefined> | undefined, key: T) => TreeNode<T, undefined> | undefined = (curNode: TreeNode<T, undefined> | undefined, key: T) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult === 0) return curNode;
if (cmpResult > 0) return _reverseLowerBound(curNode.leftChild, key);
const resNode = _reverseLowerBound(curNode.rightChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.reverseLowerBound = function (key: T) {
const resNode = _reverseLowerBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
const _reverseUpperBound: (curNode: TreeNode<T, undefined> | undefined, key: T) => TreeNode<T, undefined> | undefined = (curNode: TreeNode<T, undefined> | undefined, key: T) => {
if (!curNode || curNode.key === undefined) return undefined;
const cmpResult = cmp(curNode.key, key);
if (cmpResult >= 0) return _reverseUpperBound(curNode.leftChild, key);
const resNode = _reverseUpperBound(curNode.rightChild, key);
if (resNode === undefined) return curNode;
return resNode;
};
this.reverseUpperBound = function (key: T) {
const resNode = _reverseUpperBound(root, key);
return resNode === undefined ? this.end() : new TreeIterator(resNode, header);
};
// waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
// (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
this.union = function (other: SetType<T>) {
other.forEach((element) => this.insert(element));
};
this.getHeight = function () {
if (this.empty()) return 0;
const traversal: (curNode: TreeNode<T, undefined> | undefined) => number = function (curNode: TreeNode<T, undefined> | undefined) {
if (!curNode) return 1;
return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
};
return traversal(root);
};
if (typeof Symbol.iterator === 'symbol') {
const iterationFunc: (curNode: TreeNode<T, undefined> | undefined) => Generator<T, void, undefined> = function* (curNode: TreeNode<T, undefined> | undefined) {
if (!curNode || curNode.key === undefined) return;
yield* iterationFunc(curNode.leftChild);
yield curNode.key;
yield* iterationFunc(curNode.rightChild);
};
this[Symbol.iterator] = function () {
return iterationFunc(root);
};
}
container.forEach(element => this.insert(element));
}
export default (Set as unknown as { new <T>(container?: { forEach: (callback: (element: T) => void) => void }, cmp?: (x: T, y: T) => number): SetType<T> }); | the_stack |
import {assert} from 'chai';
import * as dom5 from 'dom5/lib/index-next';
import * as parse5 from 'parse5';
import * as path from 'path';
import {htmlTransform} from '../html-transform';
import {assertEqualIgnoringWhitespace} from './util';
/**
* Replaces the Babel helpers, Require.js AMD loader, and WCT hack inline
* scripts into just some comments, to make test comparison simpler.
*/
function replaceGiantScripts(html: string): string {
const document = parse5.parse(html);
for (const script of dom5.queryAll(
document, dom5.predicates.hasTagName('script'))) {
const js = dom5.getTextContent(script);
if (js.includes('window.define=')) {
dom5.setTextContent(script, '// amd loader');
} else if (js.includes('wrapNativeSuper=')) {
dom5.setTextContent(script, '// babel helpers full');
} else if (js.includes('interopRequireDefault=')) {
dom5.setTextContent(script, '// babel helpers amd');
} else if (js.includes('regeneratorRuntime')) {
dom5.setTextContent(script, '// regenerator runtime');
} else if (js.includes('window._wctCallback =')) {
dom5.setTextContent(script, '// wct hack 1/2');
} else if (js.includes('window._wctCallback()')) {
dom5.setTextContent(script, '// wct hack 2/2');
}
}
return parse5.serialize(document);
}
suite('htmlTransform', () => {
const fixtureRoot =
path.join(__dirname, '..', '..', 'test-fixtures', 'npm-modules');
test('minifies html', () => {
const input = `
<html>
<body>
<!-- pointless comment -->
<p>Hello World!</p>
</body>
</html>`;
const expected = `<html><body><p>Hello World!</p></body></html>`;
assert.equal(htmlTransform(input, {minifyHtml: true}), expected);
});
test('does not add unnecessary tags', () => {
const input = `<p>Just me</p>`;
assert.equal(htmlTransform(input, {}), input);
});
test('compiles inline JavaScript to ES5', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>var foo = 3;</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {js: {compile: true}}), expected);
});
test('minifies inline JavaScript', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>const foo=3;</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {js: {minify: true}}), expected);
});
test('injects full babel helpers', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>// babel helpers full</script>
<script>const foo = 3;</script>
</body></html>`;
const result = htmlTransform(input, {injectBabelHelpers: 'full'});
assertEqualIgnoringWhitespace(replaceGiantScripts(result), expected);
});
test('injects AMD babel helpers', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>// babel helpers amd</script>
<script>const foo = 3;</script>
</body></html>`;
const result = htmlTransform(input, {injectBabelHelpers: 'amd'});
assertEqualIgnoringWhitespace(replaceGiantScripts(result), expected);
});
test('injects regenerator runtime', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>// regenerator runtime</script>
<script>const foo = 3;</script>
</body></html>`;
const result = htmlTransform(input, {injectRegeneratorRuntime: true});
assertEqualIgnoringWhitespace(replaceGiantScripts(result), expected);
});
test('rewrites bare module specifiers to paths', () => {
const filePath = path.join(fixtureRoot, 'foo.html');
const input = `
<html><head></head><body>
<script type="module">
import { dep1 } from 'dep1';
</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script type="module">
import { dep1 } from "./node_modules/dep1/index.js";
</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {js: {moduleResolution: 'node', filePath}}),
expected);
});
suite('transform ES modules to AMD', () => {
test('external script', () => {
const input = `
<html><head></head><body>
<script type="module" src="depA.js"></script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>define(['depA.js']);</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {
js: {
transformModulesToAmd: true,
}
}),
expected);
});
test('inline script', () => {
const input = `
<html><head></head><body>
<script type="module">
import { depA } from './depA.js';
console.log(depA);
</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>
define(["./depA.js"], function (_depA) {
"use strict";
console.log(_depA.depA);
});
</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {
js: {
transformModulesToAmd: true,
filePath: path.join(fixtureRoot, 'foo.html'),
rootDir: fixtureRoot,
},
}),
expected);
});
test('chains inline and external module scripts', () => {
const input = `
<html><head></head><body>
<script type="module">import { depA } from './depA.js';</script>
<script type="module" src="./depB.js"></script>
<script type="module">import { depC } from './depC.js';</script>
<script type="module">'no imports';</script>
<script type="module" src="./depD.js"></script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>define(["./depA.js"], function (_depA) {"use strict";});</script>
<script>define(['./depB.js']);</script>
<script>define(["./depC.js"], function (_depC) {"use strict";});</script>
<script>define([], function () {"use strict";'no imports';});</script>
<script>define(['./depD.js']);</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {
js: {
transformModulesToAmd: true,
filePath: path.join(fixtureRoot, 'foo.html'),
rootDir: fixtureRoot,
}
}),
expected);
});
test('resolves names and does AMD transform', () => {
const input = `
<html><head></head><body>
<script type="module">import { dep1 } from 'dep1';</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>define(["./node_modules/dep1/index.js"], function (_index) {"use strict";});</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {
js: {
transformModulesToAmd: true,
moduleResolution: 'node',
filePath: path.join(fixtureRoot, 'foo.html'),
rootDir: fixtureRoot,
}
}),
expected);
});
test('compiles non-module script without AMD plugin', () => {
const input = `
<html><head></head><body>
<script>const foo = 3;</script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>var foo = 3;</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {
js: {
compile: true,
transformModulesToAmd: true,
}
}),
expected);
});
test('does not transform when "nomodule" script present', () => {
const input = `
<html><head></head><body>
<script type="module">
import { depA } from './depA.js';
console.log(depA);
</script>
<script nomodule="">
// Handle browsers without ES modules some other way.
</script>
</body></html>`;
assertEqualIgnoringWhitespace(
htmlTransform(input, {js: {transformModulesToAmd: true}}), input);
});
test('adds AMD loader to entry point before first module', () => {
const input = `
<html><head></head><body>
<script>console.log('non-module');</script>
<script type="module" src="depA.js"></script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>console.log('non-module');</script>
<script>// amd loader</script>
<script>define(['depA.js']);</script>
</body></html>`;
const result = htmlTransform(input, {
injectAmdLoader: true,
js: {
transformModulesToAmd: true,
},
});
assertEqualIgnoringWhitespace(replaceGiantScripts(result), expected);
});
test('does not add AMD loader when no modules', () => {
const input = `
<html><head></head><body>
<script>console.log('non-module');</script>
<script src="depA.js"></script>
</body></html>`;
const result = htmlTransform(input, {
injectAmdLoader: true,
js: {
transformModulesToAmd: true,
},
});
assertEqualIgnoringWhitespace(result, input);
});
test('adds hack for Web Component Tester', () => {
const input = `
<html><head></head><body>
<script src="web-component-tester/browser.js"></script>
<script type="module" src="depA.js"></script>
</body></html>`;
const expected = `
<html><head></head><body>
<script>// wct hack 1/2</script>
<script src="web-component-tester/browser.js"></script>
<script>// amd loader</script>
<script>// wct hack 2/2</script>
<script>define(['depA.js']);</script>
</body></html>`;
const result = htmlTransform(input, {
injectAmdLoader: true,
js: {
transformModulesToAmd: true,
},
});
assertEqualIgnoringWhitespace(replaceGiantScripts(result), expected);
});
});
}); | the_stack |
import {ListNode, Location, ListItemNode} from '../../node'
import isNumeric from '../is-numeric'
import Tokenizer from '../tokenizer'
import {Parser} from '../parser'
import {TAB_SIZE, ruleMarkers} from '../shared-constants'
/*
* A set of characters which can be used to mark
* list-items.
*/
const listUnorderedMarkers = new Set(['*', '+', '-'])
/*
* A set of characters which can be used to mark
* list-items after a digit.
*/
const listOrderedMarkers = new Set(['.'])
/*
* A set of characters which can be used to mark
* list-items after a digit.
*/
const listOrderedCommonmarkMarkers = new Set(['.', ')'])
/**
* Tokenise a list.
*
* @example
* tokenizeList(eat, '- Foo')
*
* @param {function(string)} eat - Eater.
* @param {string} value - Rest of content.
* @param {boolean?} [silent] - Whether this is a dry run.
* @return {Node?|boolean} - `list` node.
*/
const tokenizeList: Tokenizer = function (parser, value, silent) {
const commonmark = parser.options.commonmark
const pedantic = parser.options.pedantic
let index = 0
let length = value.length
let start: number = null
let queue: string
let ordered: boolean
let character: string
let marker: string
let nextIndex: number
let startIndex: number
let prefixed: boolean
let currentMarker: string
let empty: boolean
let allLines: any
while (index < length) {
character = value.charAt(index)
if (character !== ' ' && character !== '\t') {
break
}
index++
}
character = value.charAt(index)
const markers = commonmark
? listOrderedCommonmarkMarkers
: listOrderedMarkers
if (listUnorderedMarkers.has(character)) {
marker = character
ordered = false
} else {
ordered = true
queue = ''
while (index < length) {
character = value.charAt(index)
if (!isNumeric(character)) {
break
}
queue += character
index++
}
character = value.charAt(index)
if (!queue || !markers.has(character)) {
return
}
start = parseInt(queue, 10)
marker = character
}
character = value.charAt(++index)
if (character !== ' ' && character !== '\t') {
return
}
if (silent) {
return true
}
index = 0
const items: any = []
allLines = []
let emptyLines: string[] = []
let item: any
return tokenizeEach(index)
.then(() => parser.eat(allLines.join('\n'))
.reset({
type: 'list',
ordered,
start,
loose: null,
children: [],
})
)
.then((node: ListNode) => {
parser.context.inList = false
parser.context.inBlock = true
let isLoose = false
length = items.length
const parent = node
return tokenizeEach(items)
.then(() => {
parser.context.inList = true
parser.context.inBlock = false
node.loose = isLoose
return node
})
function tokenizeEach (items: any): any {
const rawItem = items.shift()
if (!rawItem) {
return
}
item = rawItem.value.join('\n')
const now = parser.eat.now()
return parser.eat(item)(renderListItem(parser, item, now), parent)
.then(item => {
if ((item as ListNode).loose) {
isLoose = true
}
let joinedTrail = rawItem.trail.join('\n')
if (items.length) {
joinedTrail += '\n'
}
parser.eat(joinedTrail)
return tokenizeEach(items)
})
}
})
function tokenizeEach (index: number): any {
if (index >= length) {
return Promise.resolve()
}
nextIndex = value.indexOf('\n', index)
startIndex = index
prefixed = false
let indented = false
if (nextIndex === -1) {
nextIndex = length
}
let end = index + TAB_SIZE
let size = 0
while (index < length) {
character = value.charAt(index)
if (character === '\t') {
size += TAB_SIZE - size % TAB_SIZE
} else if (character === ' ') {
size++
} else {
break
}
index++
}
if (size >= TAB_SIZE) {
indented = true
}
if (item && size >= item.indent) {
indented = true
}
character = value.charAt(index)
currentMarker = null
if (!indented) {
if (listUnorderedMarkers.has(character)) {
currentMarker = character
index++
size++
} else {
queue = ''
while (index < length) {
character = value.charAt(index)
if (!isNumeric(character)) {
break
}
queue += character
index++
}
character = value.charAt(index)
index++
if (queue && markers.has(character)) {
currentMarker = character
size += queue.length + 1
}
}
if (currentMarker) {
character = value.charAt(index)
if (character === '\t') {
size += TAB_SIZE - size % TAB_SIZE
index++
} else if (character === ' ') {
end = index + TAB_SIZE
while (index < end) {
if (value.charAt(index) !== ' ') {
break
}
index++
size++
}
if (index === end && value.charAt(index) === ' ') {
index -= TAB_SIZE - 1
size -= TAB_SIZE - 1
}
} else if (
character !== '\n' &&
character !== ''
) {
currentMarker = null
}
}
}
if (currentMarker) {
if (commonmark && marker !== currentMarker) {
return Promise.resolve()
}
prefixed = true
} else {
if (
!commonmark &&
!indented &&
value.charAt(startIndex) === ' '
) {
indented = true
} else if (
commonmark &&
item
) {
indented = size >= item.indent || size > TAB_SIZE
}
prefixed = false
index = startIndex
}
let line = value.slice(startIndex, nextIndex)
let content = startIndex === index ? line : value.slice(index, nextIndex)
if (currentMarker && ruleMarkers.has(currentMarker)) {
return parser.tryTokenizeBlock(parser.eat, 'thematicBreak', line, true)
.then(found => {
if (found) {
return
}
return notRuleMarker()
})
}
return notRuleMarker()
function defaultEnd () {
index = nextIndex + 1
return tokenizeEach(index)
}
function next () {
item.value = item.value.concat(emptyLines, line)
allLines = allLines.concat(emptyLines, line)
emptyLines = []
return defaultEnd()
}
function notCommonmarkNext () {
if (!commonmark) {
return parser.tryTokenizeBlock(parser.eat, 'definition', line, true)
.then(found => {
if (found) {
return false
}
return parser.tryTokenizeBlock(parser.eat, 'footnote', line, true)
.then(found => {
if (found) {
return false
}
return next()
})
})
}
return next()
}
function notRuleMarker () {
const prevEmpty = empty
empty = !content.trim().length
if (indented && item) {
item.value = item.value.concat(emptyLines, line)
allLines = allLines.concat(emptyLines, line)
emptyLines = []
} else if (prefixed) {
if (emptyLines.length) {
item.value.push('')
item.trail = emptyLines.concat()
}
item = {
// 'bullet': value.slice(startIndex, index),
value: [line],
indent: size,
trail: [],
}
items.push(item)
allLines = allLines.concat(emptyLines, line)
emptyLines = []
} else if (empty) {
// TODO: disable when in pedantic-mode.
if (prevEmpty) {
return Promise.resolve()
}
emptyLines.push(line)
} else {
if (prevEmpty) {
return Promise.resolve()
}
if (!pedantic) {
return parser.tryTokenizeBlock(parser.eat, 'fencedCode', line, true)
.then(found => {
if (found) {
return false
}
return parser.tryTokenizeBlock(parser.eat, 'thematicBreak', line, true)
.then(found => {
if (found) {
return false
}
return notCommonmarkNext()
})
})
}
return notCommonmarkNext()
}
return defaultEnd()
}
}
}
export default tokenizeList
/*
* A map of two functions which can create list items.
*/
const LIST_ITEM_MAP = {
true: renderPedanticListItem,
false: renderNormalListItem,
}
const EXPRESSION_BULLET = /^([ \t]*)([*+-]|\d+[.)])( {1,4}(?! )| |\t|$|(?=\n))([^\n]*)/
const EXPRESSION_PEDANTIC_BULLET = /^([ \t]*)([*+-]|\d+[.)])([ \t]+)/
const EXPRESSION_LOOSE_LIST_ITEM = /\n\n(?!\s*$)/
const EXPRESSION_INITIAL_INDENT = /^( {1,4}|\t)?/gm
/**
* Create a list-item using overly simple mechanics.
*
* @example
* renderPedanticListItem('- _foo_', now())
*
* @param {string} value - List-item.
* @param {Object} position - List-item location.
* @return {string} - Cleaned `value`.
*/
function renderPedanticListItem (parser: Parser, value: string, position: Location): string {
let indent = parser.indent(position.line)
/**
* A simple replacer which removed all matches,
* and adds their length to `offset`.
*
* @param {string} $0 - Indentation to subtract.
* @return {string} - An empty string.
*/
function replacer ($0: string): string {
indent($0.length)
return ''
}
/*
* Remove the list-item’s bullet.
*/
value = value.replace(EXPRESSION_PEDANTIC_BULLET, replacer)
/*
* The initial line was also matched by the below, so
* we reset the `line`.
*/
indent = parser.indent(position.line)
return value.replace(EXPRESSION_INITIAL_INDENT, replacer)
}
/*
* Numeric constants.
*/
const SPACE_SIZE = 1
/*
* A map of characters, and their column length,
* which can be used as indentation.
*/
const INDENTATION_CHARACTERS = {
' ': SPACE_SIZE,
'\t': TAB_SIZE,
}
type Stops = { [stop: number]: number }
type IndentInfo = { indent: number, stops: Stops }
/**
* Gets indentation information for a line.
*
* @example
* getIndent(' foo')
* // {indent: 2, stops: {1: 0, 2: 1}}
*
* getIndent('\tfoo')
* // {indent: 4, stops: {4: 0}}
*
* getIndent(' \tfoo')
* // {indent: 4, stops: {1: 0, 2: 1, 4: 2}}
*
* getIndent('\t foo')
* // {indent: 6, stops: {4: 0, 5: 1, 6: 2}}
*
* @param {string} value - Indented line.
* @return {Object} - Indetation information.
*/
function getIndent (value: string): IndentInfo {
let index = 0
let indent = 0
let character = value.charAt(index)
const stops: Stops = {}
while (character in INDENTATION_CHARACTERS) {
const size = INDENTATION_CHARACTERS[character]
indent += size
if (size > 1) {
indent = Math.floor(indent / size) * size
}
stops[indent] = index
character = value.charAt(++index)
}
return { indent, stops }
}
/**
* Remove the minimum indent from every line in `value`.
* Supports both tab, spaced, and mixed indentation (as
* well as possible).
*
* @example
* removeIndentation(' foo') // 'foo'
* removeIndentation(' foo', 2) // ' foo'
* removeIndentation('\tfoo', 2) // ' foo'
* removeIndentation(' foo\n bar') // ' foo\n bar'
*
* @param {string} value - Value to trim.
* @param {number?} [maximum] - Maximum indentation
* to remove.
* @return {string} - Unindented `value`.
*/
function removeIndentation (value: string, maximum?: number): string {
const values = value.split('\n')
let position = values.length + 1
let minIndent = Infinity
const matrix: { [position: number]: Stops } = []
let index: number
let stops: Stops
let padding: string
values.unshift(`${' '.repeat(maximum)}!`)
while (position--) {
const indentation = getIndent(values[position])
matrix[position] = indentation.stops
if (values[position].trim().length === 0) {
continue
}
if (indentation.indent) {
if (indentation.indent > 0 && indentation.indent < minIndent) {
minIndent = indentation.indent
}
} else {
minIndent = Infinity
break
}
}
if (minIndent !== Infinity) {
position = values.length
while (position--) {
stops = matrix[position]
index = minIndent
while (index && !(index in stops)) {
index--
}
if (
values[position].trim().length !== 0 &&
minIndent &&
index !== minIndent
) {
padding = '\t'
} else {
padding = ''
}
values[position] = padding + values[position].slice(
index in stops ? stops[index] + 1 : 0
)
}
}
values.shift()
return values.join('\n')
}
/**
* Create a list-item using sane mechanics.
*
* @example
* renderNormalListItem('- _foo_', now())
*
* @param {string} value - List-item.
* @param {Object} position - List-item location.
* @return {string} - Cleaned `value`.
*/
function renderNormalListItem (parser: Parser, value: string, position: Location): string {
const indent = parser.indent(position.line)
let max: string
let bullet: string
let rest: string
let lines: string[]
let trimmedLines: string[]
let index: number
let length: number
/*
* Remove the list-item’s bullet.
*/
value = value.replace(EXPRESSION_BULLET, ($0: string, $1: string, $2: string, $3: string, $4: string): string => {
bullet = $1 + $2 + $3
rest = $4
/*
* Make sure that the first nine numbered list items
* can indent with an extra space. That is, when
* the bullet did not receive an extra final space.
*/
if (Number($2) < 10 && bullet.length % 2 === 1) {
$2 = ` ${$2}`
}
max = $1 + ' '.repeat($2.length) + $3
return max + rest
})
lines = value.split('\n')
trimmedLines = removeIndentation(
value, getIndent(max).indent
).split('\n')
/*
* We replaced the initial bullet with something
* else above, which was used to trick
* `removeIndentation` into removing some more
* characters when possible. However, that could
* result in the initial line to be stripped more
* than it should be.
*/
trimmedLines[0] = rest
indent(bullet.length)
index = 0
length = lines.length
while (++index < length) {
indent(lines[index].length - trimmedLines[index].length)
}
return trimmedLines.join('\n')
}
const EXPRESSION_TASK_ITEM = /^\[([ \t]|x|X)\][ \t]/
/**
* Create a list-item node.
*
* @example
* renderListItem('- _foo_', now())
*
* @param {Object} value - List-item.
* @param {Object} position - List-item location.
* @return {Object} - `listItem` node.
*/
function renderListItem (parser: Parser, value: string, position: Location): Promise<ListItemNode> {
let checked: boolean = null
value = LIST_ITEM_MAP[parser.options.pedantic ? 'true' : 'false'].apply(parser, arguments)
if (parser.options.gfm) {
const task = value.match(EXPRESSION_TASK_ITEM)
if (task) {
const indent = task[0].length
checked = task[1].toLowerCase() === 'x'
parser.indent(position.line)(indent)
value = value.slice(indent)
}
}
return parser.tokenizeBlock(value, position)
.then(children => (<ListItemNode>{
type: 'listItem',
loose: EXPRESSION_LOOSE_LIST_ITEM.test(value) ||
value.charAt(value.length - 1) === '\n',
checked,
children,
}))
} | the_stack |
import * as GObject from "@gi-types/gobject";
import * as Gio from "@gi-types/gio";
import * as GLib from "@gi-types/glib";
export const MAJOR_VERSION: number;
export const MICRO_VERSION: number;
export const MINOR_VERSION: number;
export const VERSION_S: string;
export function boxed_can_deserialize(gboxed_type: GObject.GType, node_type: NodeType): boolean;
export function boxed_can_serialize(gboxed_type: GObject.GType): [boolean, NodeType];
export function boxed_deserialize(gboxed_type: GObject.GType, node: Node): any | null;
export function boxed_serialize(gboxed_type: GObject.GType, boxed?: any | null): Node | null;
export function construct_gobject<T = GObject.Object>(gtype: GObject.GType, data: string, length: number): T;
export function from_string(str: string): Node | null;
export function gobject_deserialize<T = GObject.Object>(gtype: GObject.GType, node: Node): T;
export function gobject_from_data<T = GObject.Object>(gtype: GObject.GType, data: string, length: number): T;
export function gobject_serialize(gobject: GObject.Object): Node;
export function gobject_to_data(gobject: GObject.Object): [string, number];
export function gvariant_deserialize(json_node: Node, signature?: string | null): GLib.Variant;
export function gvariant_deserialize_data(json: string, length: number, signature?: string | null): GLib.Variant;
export function gvariant_serialize(variant: GLib.Variant): Node;
export function gvariant_serialize_data(variant: GLib.Variant): [string, number | null];
export function parser_error_quark(): GLib.Quark;
export function path_error_quark(): GLib.Quark;
export function reader_error_quark(): GLib.Quark;
export function serialize_gobject(gobject: GObject.Object): [string, number];
export function string_compare(a: string, b: string): number;
export function string_equal(a: string, b: string): boolean;
export function string_hash(key: string): number;
export function to_string(node: Node, pretty: boolean): string;
export type ArrayForeach = (array: Array, index_: number, element_node: Node) => void;
export type BoxedDeserializeFunc = (node: Node) => any | null;
export type BoxedSerializeFunc = (boxed?: any | null) => Node;
export type ObjectForeach = (object: Object, member_name: string, member_node: Node) => void;
export namespace NodeType {
export const $gtype: GObject.GType<NodeType>;
}
export enum NodeType {
OBJECT = 0,
ARRAY = 1,
VALUE = 2,
NULL = 3,
}
export class ParserError extends GLib.Error {
static $gtype: GObject.GType<ParserError>;
constructor(options: { message: string; code: number });
constructor(copy: ParserError);
// Properties
static PARSE: number;
static TRAILING_COMMA: number;
static MISSING_COMMA: number;
static MISSING_COLON: number;
static INVALID_BAREWORD: number;
static EMPTY_MEMBER_NAME: number;
static INVALID_DATA: number;
static UNKNOWN: number;
// Members
static quark(): GLib.Quark;
}
export class PathError extends GLib.Error {
static $gtype: GObject.GType<PathError>;
constructor(options: { message: string; code: number });
constructor(copy: PathError);
// Properties
static QUERY: number;
// Members
static quark(): GLib.Quark;
}
export class ReaderError extends GLib.Error {
static $gtype: GObject.GType<ReaderError>;
constructor(options: { message: string; code: number });
constructor(copy: ReaderError);
// Properties
static NO_ARRAY: number;
static INVALID_INDEX: number;
static NO_OBJECT: number;
static INVALID_MEMBER: number;
static INVALID_NODE: number;
static NO_VALUE: number;
static INVALID_TYPE: number;
// Members
static quark(): GLib.Quark;
}
export module Builder {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
immutable: boolean;
}
}
export class Builder extends GObject.Object {
static $gtype: GObject.GType<Builder>;
constructor(properties?: Partial<Builder.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Builder.ConstructorProperties>, ...args: any[]): void;
// Properties
immutable: boolean;
// Constructors
static ["new"](): Builder;
static new_immutable(): Builder;
// Members
add_boolean_value(value: boolean): Builder | null;
add_double_value(value: number): Builder | null;
add_int_value(value: number): Builder | null;
add_null_value(): Builder | null;
add_string_value(value: string): Builder | null;
add_value(node: Node): Builder | null;
begin_array(): Builder | null;
begin_object(): Builder | null;
end_array(): Builder | null;
end_object(): Builder | null;
get_root(): Node | null;
reset(): void;
set_member_name(member_name: string): Builder | null;
}
export module Generator {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
indent: number;
indent_char: number;
indentChar: number;
pretty: boolean;
root: Node;
}
}
export class Generator extends GObject.Object {
static $gtype: GObject.GType<Generator>;
constructor(properties?: Partial<Generator.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Generator.ConstructorProperties>, ...args: any[]): void;
// Properties
indent: number;
indent_char: number;
indentChar: number;
pretty: boolean;
root: Node;
// Constructors
static ["new"](): Generator;
// Members
get_indent(): number;
get_indent_char(): number;
get_pretty(): boolean;
get_root(): Node | null;
set_indent(indent_level: number): void;
set_indent_char(indent_char: number): void;
set_pretty(is_pretty: boolean): void;
set_root(node: Node): void;
to_data(): [string, number];
to_file(filename: string): boolean;
to_gstring(string: GLib.String): GLib.String;
to_stream(stream: Gio.OutputStream, cancellable?: Gio.Cancellable | null): boolean;
}
export module Parser {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
immutable: boolean;
}
}
export class Parser extends GObject.Object {
static $gtype: GObject.GType<Parser>;
constructor(properties?: Partial<Parser.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Parser.ConstructorProperties>, ...args: any[]): void;
// Properties
immutable: boolean;
// Signals
connect(id: string, callback: (...args: any[]) => any): number;
connect_after(id: string, callback: (...args: any[]) => any): number;
emit(id: string, ...args: any[]): void;
connect(signal: "array-element", callback: (_source: this, array: Array, index_: number) => void): number;
connect_after(signal: "array-element", callback: (_source: this, array: Array, index_: number) => void): number;
emit(signal: "array-element", array: Array, index_: number): void;
connect(signal: "array-end", callback: (_source: this, array: Array) => void): number;
connect_after(signal: "array-end", callback: (_source: this, array: Array) => void): number;
emit(signal: "array-end", array: Array): void;
connect(signal: "array-start", callback: (_source: this) => void): number;
connect_after(signal: "array-start", callback: (_source: this) => void): number;
emit(signal: "array-start"): void;
connect(signal: "error", callback: (_source: this, error: any | null) => void): number;
connect_after(signal: "error", callback: (_source: this, error: any | null) => void): number;
emit(signal: "error", error: any | null): void;
connect(signal: "object-end", callback: (_source: this, object: Object) => void): number;
connect_after(signal: "object-end", callback: (_source: this, object: Object) => void): number;
emit(signal: "object-end", object: Object): void;
connect(signal: "object-member", callback: (_source: this, object: Object, member_name: string) => void): number;
connect_after(
signal: "object-member",
callback: (_source: this, object: Object, member_name: string) => void
): number;
emit(signal: "object-member", object: Object, member_name: string): void;
connect(signal: "object-start", callback: (_source: this) => void): number;
connect_after(signal: "object-start", callback: (_source: this) => void): number;
emit(signal: "object-start"): void;
connect(signal: "parse-end", callback: (_source: this) => void): number;
connect_after(signal: "parse-end", callback: (_source: this) => void): number;
emit(signal: "parse-end"): void;
connect(signal: "parse-start", callback: (_source: this) => void): number;
connect_after(signal: "parse-start", callback: (_source: this) => void): number;
emit(signal: "parse-start"): void;
// Constructors
static ["new"](): Parser;
static new_immutable(): Parser;
// Members
get_current_line(): number;
get_current_pos(): number;
get_root(): Node | null;
has_assignment(): [boolean, string | null];
load_from_data(data: string, length: number): boolean;
load_from_file(filename: string): boolean;
load_from_mapped_file(filename: string): boolean;
load_from_stream(stream: Gio.InputStream, cancellable?: Gio.Cancellable | null): boolean;
load_from_stream_async(stream: Gio.InputStream, cancellable?: Gio.Cancellable | null): Promise<boolean>;
load_from_stream_async(
stream: Gio.InputStream,
cancellable: Gio.Cancellable | null,
callback: Gio.AsyncReadyCallback<this> | null
): void;
load_from_stream_async(
stream: Gio.InputStream,
cancellable?: Gio.Cancellable | null,
callback?: Gio.AsyncReadyCallback<this> | null
): Promise<boolean> | void;
load_from_stream_finish(result: Gio.AsyncResult): boolean;
steal_root(): Node | null;
vfunc_array_element(array: Array, index_: number): void;
vfunc_array_end(array: Array): void;
vfunc_array_start(): void;
vfunc_error(error: GLib.Error): void;
vfunc_object_end(object: Object): void;
vfunc_object_member(object: Object, member_name: string): void;
vfunc_object_start(): void;
vfunc_parse_end(): void;
vfunc_parse_start(): void;
}
export module Path {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
}
}
export class Path extends GObject.Object {
static $gtype: GObject.GType<Path>;
constructor(properties?: Partial<Path.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Path.ConstructorProperties>, ...args: any[]): void;
// Constructors
static ["new"](): Path;
// Members
compile(expression: string): boolean;
match(root: Node): Node;
static query(expression: string, root: Node): Node;
}
export module Reader {
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
[key: string]: any;
root: Node;
}
}
export class Reader extends GObject.Object {
static $gtype: GObject.GType<Reader>;
constructor(properties?: Partial<Reader.ConstructorProperties>, ...args: any[]);
_init(properties?: Partial<Reader.ConstructorProperties>, ...args: any[]): void;
// Properties
root: Node;
// Constructors
static ["new"](node?: Node | null): Reader;
// Members
count_elements(): number;
count_members(): number;
end_element(): void;
end_member(): void;
get_boolean_value(): boolean;
get_double_value(): number;
get_error(): GLib.Error | null;
get_int_value(): number;
get_member_name(): string | null;
get_null_value(): boolean;
get_string_value(): string;
get_value(): Node | null;
is_array(): boolean;
is_object(): boolean;
is_value(): boolean;
list_members(): string[];
read_element(index_: number): boolean;
read_member(member_name: string): boolean;
set_root(root?: Node | null): void;
}
export class Array {
static $gtype: GObject.GType<Array>;
constructor();
constructor(copy: Array);
// Constructors
static ["new"](): Array;
static sized_new(n_elements: number): Array;
// Members
add_array_element(value?: Array | null): void;
add_boolean_element(value: boolean): void;
add_double_element(value: number): void;
add_element(node: Node): void;
add_int_element(value: number): void;
add_null_element(): void;
add_object_element(value: Object): void;
add_string_element(value: string): void;
dup_element(index_: number): Node;
equal(b: Array): boolean;
foreach_element(func: ArrayForeach): void;
get_array_element(index_: number): Array;
get_boolean_element(index_: number): boolean;
get_double_element(index_: number): number;
get_element(index_: number): Node;
get_elements(): Node[];
get_int_element(index_: number): number;
get_length(): number;
get_null_element(index_: number): boolean;
get_object_element(index_: number): Object;
get_string_element(index_: number): string;
hash(): number;
is_immutable(): boolean;
ref(): Array;
remove_element(index_: number): void;
seal(): void;
unref(): void;
}
export class BuilderPrivate {
static $gtype: GObject.GType<BuilderPrivate>;
constructor(copy: BuilderPrivate);
}
export class GeneratorPrivate {
static $gtype: GObject.GType<GeneratorPrivate>;
constructor(copy: GeneratorPrivate);
}
export class Node {
static $gtype: GObject.GType<Node>;
constructor();
constructor(copy: Node);
// Constructors
static alloc(): Node;
static ["new"](type: NodeType): Node;
// Members
copy(): Node;
dup_array(): Array | null;
dup_object(): Object | null;
dup_string(): string | null;
equal(b: Node): boolean;
free(): void;
get_array(): Array | null;
get_boolean(): boolean;
get_double(): number;
get_int(): number;
get_node_type(): NodeType;
get_object(): Object | null;
get_parent(): Node | null;
get_string(): string | null;
get_value(): unknown;
get_value_type(): GObject.GType;
hash(): number;
init(type: NodeType): Node;
init_array(array?: Array | null): Node;
init_boolean(value: boolean): Node;
init_double(value: number): Node;
init_int(value: number): Node;
init_null(): Node;
init_object(object?: Object | null): Node;
init_string(value?: string | null): Node;
is_immutable(): boolean;
is_null(): boolean;
ref(): Node;
seal(): void;
set_array(array: Array): void;
set_boolean(value: boolean): void;
set_double(value: number): void;
set_int(value: number): void;
set_object(object?: Object | null): void;
set_parent(parent: Node): void;
set_string(value: string): void;
set_value(value: any): void;
take_array(array: Array): void;
take_object(object: Object): void;
type_name(): string;
unref(): void;
}
export class Object {
static $gtype: GObject.GType<Object>;
constructor();
constructor(copy: Object);
// Constructors
static ["new"](): Object;
// Members
add_member(member_name: string, node: Node): void;
dup_member(member_name: string): Node | null;
equal(b: Object): boolean;
foreach_member(func: ObjectForeach): void;
get_array_member(member_name: string): Array;
get_boolean_member(member_name: string): boolean;
get_boolean_member_with_default(member_name: string, default_value: boolean): boolean;
get_double_member(member_name: string): number;
get_double_member_with_default(member_name: string, default_value: number): number;
get_int_member(member_name: string): number;
get_int_member_with_default(member_name: string, default_value: number): number;
get_member(member_name: string): Node | null;
get_members(): string[] | null;
get_null_member(member_name: string): boolean;
get_object_member(member_name: string): Object | null;
get_size(): number;
get_string_member(member_name: string): string;
get_string_member_with_default(member_name: string, default_value: string): string;
get_values(): Node[] | null;
has_member(member_name: string): boolean;
hash(): number;
is_immutable(): boolean;
ref(): Object;
remove_member(member_name: string): void;
seal(): void;
set_array_member(member_name: string, value: Array): void;
set_boolean_member(member_name: string, value: boolean): void;
set_double_member(member_name: string, value: number): void;
set_int_member(member_name: string, value: number): void;
set_member(member_name: string, node: Node): void;
set_null_member(member_name: string): void;
set_object_member(member_name: string, value: Object): void;
set_string_member(member_name: string, value: string): void;
unref(): void;
}
export class ObjectIter {
static $gtype: GObject.GType<ObjectIter>;
constructor(copy: ObjectIter);
// Fields
priv_pointer: any[];
priv_int: number[];
priv_boolean: boolean[];
// Members
init(object: Object): void;
init_ordered(object: Object): void;
next(): [boolean, string | null, Node | null];
next_ordered(): [boolean, string | null, Node | null];
}
export class ParserPrivate {
static $gtype: GObject.GType<ParserPrivate>;
constructor(copy: ParserPrivate);
}
export class ReaderPrivate {
static $gtype: GObject.GType<ReaderPrivate>;
constructor(copy: ReaderPrivate);
}
export interface SerializableNamespace {
$gtype: GObject.GType<Serializable>;
prototype: SerializablePrototype;
}
export type Serializable = SerializablePrototype;
export interface SerializablePrototype extends GObject.Object {
// Members
default_deserialize_property(
property_name: string,
value: any,
pspec: GObject.ParamSpec,
property_node: Node
): boolean;
default_serialize_property(property_name: string, value: any, pspec: GObject.ParamSpec): Node | null;
deserialize_property(property_name: string, pspec: GObject.ParamSpec, property_node: Node): [boolean, unknown];
find_property(name: string): GObject.ParamSpec | null;
get_property(pspec: GObject.ParamSpec): unknown;
get_property(...args: never[]): never;
list_properties(): GObject.ParamSpec[];
serialize_property(property_name: string, value: any, pspec: GObject.ParamSpec): Node;
set_property(pspec: GObject.ParamSpec, value: any): void;
set_property(...args: never[]): never;
vfunc_deserialize_property(
property_name: string,
pspec: GObject.ParamSpec,
property_node: Node
): [boolean, unknown];
vfunc_find_property(name: string): GObject.ParamSpec | null;
vfunc_get_property(pspec: GObject.ParamSpec): unknown;
vfunc_get_property(...args: never[]): never;
vfunc_serialize_property(property_name: string, value: any, pspec: GObject.ParamSpec): Node;
vfunc_set_property(pspec: GObject.ParamSpec, value: any): void;
vfunc_set_property(...args: never[]): never;
}
export const Serializable: SerializableNamespace; | the_stack |
import {fixture} from '../../helper';
import test from 'ava';
import {List} from 'immutable';
import TimelineState, {DefaultTimelineState, TimelineKind} from '../../../../renderer/states/timeline';
import Item from '../../../../renderer/item/item';
import Tweet from '../../../../renderer/item/tweet';
import Activity from '../../../../renderer/item/timeline_activity';
import Separator from '../../../../renderer/item/separator';
import Config from '../../../../renderer/config';
import PM from '../../../../renderer/plugin_manager';
const DefaultMuteConfig = Config.mute;
const TWEETS = [
fixture.tweet(),
fixture.retweet(),
fixture.media(),
fixture.retweet_media(),
fixture.quote(),
fixture.quote_media(),
fixture.in_reply_to(),
];
// Generates a [0, n) integer
function randN(n: number) {
return Math.floor(Math.random() * n);
}
function getRandomTweet() {
return TWEETS[randN(TWEETS.length)];
}
function getRandomTweets() {
const len = randN(100);
let tweets = [] as Item[];
for (let i = 0; i < len; ++i) {
tweets.push(getRandomTweet());
}
return tweets;
}
function getState(
home: Item[] = [],
kind: TimelineKind = 'home',
mention: Item[] = [],
) {
return DefaultTimelineState.update({
kind,
user: fixture.user(),
home: List<Item>(home),
mention: List<Item>(mention),
});
}
function setMuteConfig(c: {home?: boolean, mention?: boolean}) {
const mute = {home: !!c.home, mention: !!c.mention};
/* tslint:disable */
(Config['remote_config_memo'] as any).mute = mute;
Config['mute_memo'] = mute;
/* tslint:enable */
}
type FilterFunc = (tw: Tweet, s: TimelineState) => boolean;
function setPluginFilters(home_timeline?: FilterFunc, mention_timeline?: FilterFunc) {
PM.addPluginDirectly({
filter: {
home_timeline,
mention_timeline,
},
});
}
test.afterEach(() => {
setMuteConfig(DefaultMuteConfig);
PM.reset();
});
test('getTimeline() returns corresponding timeline', t => {
const home = List<number>([]);
const mention = List<number>([]);
const s = DefaultTimelineState.update({home, mention});
t.is(s.getTimeline('home'), home);
t.is(s.getTimeline('mention'), mention);
});
test('getCurrentTimeline() selects current displayed timeline', t => {
const tw = fixture.tweet();
const rp = fixture.in_reply_to();
const s = getState(
[tw, tw, tw],
'home',
[rp, rp],
);
t.is(s.getCurrentTimeline().size, 3);
t.is((s.getCurrentTimeline().get(0) as Tweet).id, tw.id);
const s2 = getState(
[tw, tw, tw],
'mention',
[rp, rp],
);
t.is(s2.getCurrentTimeline().size, 2);
t.is((s2.getCurrentTimeline().get(0) as Tweet).id, rp.id);
});
test('switchTimeline() changes current timeline kind', t => {
const tw = fixture.tweet();
const rp = fixture.in_reply_to();
const s = getState(
[tw, tw, tw],
'home',
[rp, rp],
);
t.is(s.kind, 'home');
t.is(s.switchTimeline('mention').kind, 'mention');
t.is(s.switchTimeline('home').kind, 'home');
t.is(s.switchTimeline('mention').switchTimeline('home').kind, 'home');
t.is(s.switchTimeline('mention').switchTimeline('mention').kind, 'mention');
const n = s.addNewTweet(rp).switchTimeline('mention').notified;
t.false(n.mention);
});
test('shouldAddToTimeline() should reject muted or blocked tweets', t => {
const tw = fixture.tweet_other();
const rp = fixture.in_reply_to_from_other();
const s = getState().update({
rejected_ids: List<number>([tw.user.id, rp.user.id]),
});
// Post condition
t.true(tw.user.id !== s.user.id);
t.true(rp.user.id !== s.user.id);
{
const should_add_to = s.shouldAddToTimeline(tw);
t.false(should_add_to.home);
t.false(should_add_to.mention);
}
{
const should_add_to = s.shouldAddToTimeline(rp);
t.false(should_add_to.home);
t.true(should_add_to.mention);
}
});
test('shouldAddToTimeline() only adds mentions to mention timeline', t => {
const s = getState();
const non_mentions = [
fixture.tweet(),
fixture.tweet_other(),
fixture.quote(),
fixture.retweet_media(),
];
for (const tw of non_mentions) {
const should_add_to = s.shouldAddToTimeline(tw);
t.true(should_add_to.home);
t.false(should_add_to.mention);
}
const mentions = [
fixture.in_reply_to_from_other(),
];
for (const tw of mentions) {
const should_add_to = s.shouldAddToTimeline(tw);
t.true(should_add_to.home);
t.true(should_add_to.mention);
}
// Edge case: Self mention
{
const should_add_to = s.shouldAddToTimeline(fixture.reply_myself());
t.true(should_add_to.home);
t.false(should_add_to.mention);
}
});
test('shouldAddToTimeline() should reject RT also', t => {
const rt = fixture.retweet_other();
const s = getState();
// Note: by both retweeted status and retweet itself
const each_ids = [rt.user.id, rt.retweeted_status.user.id];
for (const id of each_ids) {
const should_add_to =
s.update({rejected_ids: List<number>([id])})
.shouldAddToTimeline(rt);
t.false(should_add_to.home);
t.false(should_add_to.mention);
}
});
test('shouldAddToTimeline() considers mute config', t => {
const tw = fixture.in_reply_to_from_other();
const s = getState().update({rejected_ids: List<number>([tw.user.id])});
const configs = [
{home: true, mention: true},
{home: true, mention: false},
{home: false, mention: true},
{home: false, mention: false},
];
for (const c of configs) {
setMuteConfig(c);
const should_add_to = s.shouldAddToTimeline(tw);
t.is(should_add_to.home, !c.home);
t.is(should_add_to.mention, !c.mention);
}
});
test('shouldAddToTimeline() considers plugin', t => {
const tw = fixture.tweet_other();
const rp = fixture.in_reply_to_from_other();
const s = getState();
// Note:
// Plugin's filtering has higher priority than user's configuration.
setMuteConfig({home: false, mention: false});
setPluginFilters(
(tweet: Tweet) => tw.id !== tweet.id,
(tweet: Tweet) => rp.id !== tweet.id,
);
const should_add_tweet_to = s.shouldAddToTimeline(tw);
t.false(should_add_tweet_to.home);
const should_add_other_tweet_to = s.shouldAddToTimeline(fixture.tweet());
t.true(should_add_other_tweet_to.home);
const should_add_reply_to = s.shouldAddToTimeline(rp);
t.true(should_add_reply_to.home);
t.false(should_add_reply_to.mention);
});
test('focusOn() focuses on an item', t => {
const s = getState([fixture.tweet(), fixture.tweet(), fixture.tweet()]);
t.is(s.focus_index, null);
t.is(s.focusOn(0).focus_index, 0);
t.is(s.focusOn(1).focus_index, 1);
t.is(s.focusOn(-1).focus_index, null);
t.is(s.focusOn(3).focus_index, null);
t.is(getState().focusOn(0).focus_index, null);
});
test('focusNext() and focusPrevious() moves focus relatively', t => {
const s = getState([fixture.tweet(), fixture.tweet(), fixture.tweet()]);
t.is(s.focusNext().focus_index, 0);
t.is(s.focusNext().focusNext().focus_index, 1);
t.is(s.focusNext().focusNext().focusPrevious().focus_index, 0);
t.is(s.focusPrevious().focus_index, null);
t.is(s.focusNext().focusPrevious().focus_index, 0);
t.is(s.focusNext().focusNext().focusNext().focusNext().focus_index, 2);
t.is(getState().focusNext().focus_index, null);
t.is(getState().focusPrevious().focus_index, null);
});
test('focusTop() and focusBottom() moves focus to edges of timeline', t => {
const s = getState([fixture.tweet(), fixture.tweet(), fixture.tweet()]);
t.is(s.focusTop().focus_index, 0);
t.is(s.focusBottom().focus_index, 2);
t.is(s.focusNext().focusTop().focus_index, 0);
t.is(s.focusNext().focusBottom().focus_index, 2);
t.is(getState().focusTop().focus_index, null);
t.is(getState().focusBottom().focus_index, null);
});
test('moveing focus randomly doesnot raise an error', t => {
let s = getState(getRandomTweets(), 'home', getRandomTweets());
for (let i = 0; i < 5000; ++i) {
const prev = s;
const r = randN(6);
switch (r) {
case 0:
s = s.focusOn(randN(s.getCurrentTimeline().size));
break;
case 1:
s = s.focusNext();
break;
case 2:
s = s.focusPrevious();
break;
case 3:
s = s.focusTop();
break;
case 4:
s = s.focusBottom();
break;
case 5:
s = s.focusOn(null);
break;
default:
break;
}
if (randN(20) === 0) {
s = s.switchTimeline(s.kind === 'home' ? 'mention' : 'home');
}
t.true(
s.focus_index !== undefined,
`before: ${prev.focus_index}, after: ${s.focus_index}, r: ${r}`,
);
}
});
test('addNewTweet() adds tweet to timelines', t => {
const tw = fixture.tweet();
const s = getState();
const s1 = s.addNewTweet(tw).addNewTweet(tw).addNewTweet(tw);
t.is(s1.home.size, 3);
t.is((s1.home.get(0) as Tweet).id, tw.id);
t.is(s1.mention.size, 0);
const rp = fixture.in_reply_to_from_other();
const s2 = s.addNewTweet(rp).addNewTweet(tw).addNewTweet(rp);
t.is(s2.home.size, 3);
t.is(s2.mention.size, 2);
t.is((s2.mention.get(0) as Tweet).id, rp.id);
const rt = fixture.retweeted();
const s3 = s2.addNewTweet(rt);
t.is(s3.mention.size, 3);
t.true(s3.mention.first() instanceof Activity);
t.is((s3.mention.first() as Activity).by[0].id, rt.user.id);
const rt2 = fixture.retweeted();
const s4 = s3.addNewTweet(rt2);
t.is(s3.mention.size, s4.mention.size);
t.true(s4.mention.first() instanceof Activity);
});
test('addNewTweet() updates retweets in home timeline', t => {
const tw = fixture.tweet();
const rt = fixture.retweet();
const s = getState([tw, rt, tw]);
const s1 = s.addNewTweet(rt);
t.is(s1.home.size, 3);
t.is((s1.home.first() as Tweet).id, rt.id);
});
test('addNewTweet() moves focus on adding tweet to home timeline', t => {
const tw = fixture.tweet();
for (let i = 0; i < 3; ++i) {
let s = getState([tw, tw, tw]);
s = s.focusOn(i);
s = s.addNewTweet(tw);
t.is(s.focus_index, i + 1);
}
});
test('addNewTweet() handle focus on retweet is updated', t => {
const tw = fixture.tweet();
const rt = fixture.retweet();
const s = getState([tw, rt, tw]);
t.is(s.focusOn(2).addNewTweet(rt).focus_index, 2);
t.is(s.focusOn(1).addNewTweet(rt).focus_index, 1);
t.is(s.focusOn(0).addNewTweet(rt).focus_index, 1); // Edge case
});
test('addNewTweet() moves focus on adding mentions to mention timeline', t => {
const rp = fixture.in_reply_to_from_other();
const state = getState([], 'mention', [rp, rp, rp]);
for (let i = 0; i < state.mention.size; ++i) {
const s = state.focusOn(i).addNewTweet(rp);
t.is(s.focus_index, i + 1);
}
});
test('addNewTweet() moves focus on adding retweet activity to mention timeline', t => {
const rt = fixture.retweeted();
const rp = fixture.in_reply_to_from_other();
const state = getState([], 'mention', [rp, rp, rp]);
for (let i = 0; i < 3; ++i) {
let s = state.focusOn(i).addNewTweet(rt);
t.is(s.focus_index, i + 1);
s = s.addNewTweet(rp);
t.is(s.focus_index, i + 2);
}
// TODO: Add tests of multiple users retweets your same tweet.
});
test('addNewTweet() notifies behind timeline updates', t => {
const tw = fixture.tweet();
const rt = fixture.retweeted();
const rp = fixture.in_reply_to_from_other();
const s1 = getState();
t.false(s1.notified.home);
t.false(s1.notified.mention);
const n1 = s1.addNewTweet(rt).notified;
t.false(n1.home);
t.true(n1.mention);
const n2 = s1.addNewTweet(rp).notified;
t.false(n2.home);
t.true(n2.mention);
const s2 = getState([], 'mention');
const n3 = s2.addNewTweet(tw).notified;
t.true(n3.home);
t.false(n3.mention);
const n4 = s2.addNewTweet(rt).notified;
t.true(n4.home);
t.false(n4.mention);
});
test('addSeparator() adds one separator at once', t => {
const s1 = getState().addSeparator();
t.true(s1.home.first() instanceof Separator);
t.is(s1.home.size, 1);
t.true(s1.mention.first() instanceof Separator);
t.is(s1.mention.size, 1);
const s2 = s1.addSeparator();
t.is(s2.home.size, 1);
t.is(s2.mention.size, 1);
const s3 = s2.addNewTweet(fixture.tweet()).addSeparator();
t.is(s3.home.size, 3);
t.is(s3.mention.size, 1);
});
test('addNewTweets() and addMentions() adds multiple tweets', t => {
const tw = fixture.tweet();
const rp = fixture.in_reply_to_from_other();
const rt = fixture.retweeted();
const s1 = getState().addNewTweets([tw, rp, tw, rp, tw]);
t.is(s1.home.size, 5);
t.is(s1.mention.size, 2);
t.true(s1.notified.mention);
const s2 = getState().addMentions([rp, rp, rt]);
t.is(s2.home.size, 0);
t.is(s2.mention.size, 3);
t.true(s2.notified.mention);
const s3 = getState([], 'mention', [rp]).focusOn(0).addMentions([rt, rp, rt]);
t.is(s3.focus_index, 2); // RT does not duplicate
const s4 = getState([tw], 'home', [rp]).focusOn(0).addMentions([rt, rp, rt]);
t.is(s4.focus_index, 0);
});
test('deleteStatusWithId() deletes statuses in timelines', t => {
const tw = fixture.tweet();
const tw2 = fixture.tweet_other();
const rp = fixture.in_reply_to_from_other();
const rt = fixture.retweeted();
const tw3 = rt.retweeted_status;
const s = getState([rt.retweeted_status, rp, tw, tw2, rt], 'home', [rp, rt]);
const s1 = s.deleteStatusWithId(tw.id);
t.is(s1.home.size, 4);
t.is(s1.mention.size, 2);
t.deepEqual(
s1.home.map(i => (i as Tweet).id).toArray(),
[tw3.id, rp.id, tw2.id, rt.id],
);
const s2 = s.deleteStatusWithId(tw2.id);
t.is(s2.home.size, 4);
t.is(s2.mention.size, 2);
t.deepEqual(
s2.home.map(i => (i as Tweet).id).toArray(),
[tw3.id, rp.id, tw.id, rt.id],
);
const s3 = s.deleteStatusWithId(rt.retweeted_status.id);
t.is(s3.home.size, 3);
t.is(s3.mention.size, 1);
t.deepEqual(
s3.home.map(i => (i as Tweet).id).toArray(),
[rp.id, tw.id, tw2.id],
);
t.deepEqual(
s3.mention.map(i => (i as Tweet).id).toArray(),
[rp.id],
);
const s4 = s.deleteStatusWithId('123456');
t.deepEqual(
s4.home.map(i => (i as Tweet).id).toArray(),
s.home.map(i => (i as Tweet).id).toArray(),
);
t.deepEqual(
s4.mention.map(i => (i as Tweet).id).toArray(),
s.mention.map(i => (i as Tweet).id).toArray(),
);
});
test('updateStatus() replaces all status in home timelines', t => {
const rt = fixture.retweet();
const tw = rt.retweeted_status;
const tw2 = fixture.tweet();
const s = getState([tw, rt, tw2]);
const s2 = s.updateStatus(tw.clone());
t.not(s2.home.get(0), tw);
t.not(s2.home.get(1), rt);
t.is(s2.home.get(2), tw2);
});
test('updateStatus() replaces all status in mention timelines', t => {
const rp = fixture.in_reply_to_from_other();
const rt = fixture.retweeted();
const s = getState([], 'home', [rt, rp]);
const s2 = s.updateStatus(rp.clone());
t.not(s2.mention.get(1), rp);
const s3 = s.addNewTweet(rt);
const s4 = s3.updateStatus(rt.retweeted_status.clone());
t.not(s4.mention.get(0), s3.mention.get(0));
});
test('addRejectedIds() adds ids as "marked or blocked"', t => {
let s = getState();
t.is(s.rejected_ids.size, 0);
s = s.addRejectedIds([1111, 2222]);
t.is(s.rejected_ids.size, 2);
t.true(s.rejected_ids.contains(1111));
t.true(s.rejected_ids.contains(2222));
// Remove duplicate
s = s.addRejectedIds([3333, 1111, 4444]);
t.is(s.rejected_ids.size, 4);
t.is(s.rejected_ids.count(e => e === 1111), 1);
});
test('addRejectedIds() removes statuses having newly added IDs from timelines', t => {
const tw = fixture.tweet_other();
const rt = fixture.retweeted();
const tw2 = rt.retweeted_status;
const s = getState([tw, rt, tw2, tw], 'home', [rt]);
const s1 = s.addRejectedIds([tw.user.id]);
t.is(s1.home.size, 2);
t.is((s1.home.get(0) as Tweet).id, rt.id);
t.is((s1.home.get(1) as Tweet).id, tw2.id);
const s2 = s.addRejectedIds([rt.user.id]);
t.is(s2.home.size, 3);
const s3 = s.addRejectedIds([tw2.user.id]);
t.is(s3.home.size, 2);
t.is((s3.home.get(1) as Tweet).id, tw.id);
t.is(s3.mention.size, 0);
});
test('removeRejectedIds() removes specified IDs from rejected IDs', t => {
const s1 = DefaultTimelineState.removeRejectedIds([1111, 2222, 3333]);
t.is(s1.rejected_ids.size, 0);
const s2 = DefaultTimelineState
.update({rejected_ids: List<number>([1111, 2222])})
.removeRejectedIds([2222, 3333]);
t.deepEqual(s2.rejected_ids.toArray(), [1111]);
});
test('addFriends() add IDs to friend list', t => {
const s1 = getState().addFriends([1111, 2222, 3333]);
t.deepEqual(s1.friend_ids.toArray(), [1111, 2222, 3333]);
t.is(s1.addFriends([]), s1);
t.is(s1.addFriends([2222]), s1);
const s2 = s1.addFriends([2222, 4444]);
t.deepEqual(s2.friend_ids.toArray(), [1111, 2222, 3333, 4444]);
});
test('removeFriends() removes IDs from friend list', t => {
const s = getState().addFriends([1111, 2222, 3333]);
t.is(s.removeFriends([]).friend_ids.size, s.friend_ids.size);
const s1 = s.removeFriends([2222, 3333, 4444]);
t.deepEqual(s1.friend_ids.toArray(), [1111]);
});
test('resetFriends() replaces friend IDs with specified ones', t => {
const s = getState().addFriends([1111, 2222, 3333]);
t.is(s.resetFriends([]).friend_ids.size, 0);
const s1 = s.resetFriends([4444, 5555, 6666]);
t.deepEqual(s1.friend_ids.toArray(), [4444, 5555, 6666]);
});
test('addNoRetweetUserIds() adds IDs to no-retweet ID list', t => {
const s = getState();
t.is(s.no_retweet_ids.size, 0);
const s1 = s.addNoRetweetUserIds([1111, 2222, 3333]);
t.deepEqual(s1.no_retweet_ids.toArray(), [1111, 2222, 3333]);
const s2 = s1.addNoRetweetUserIds([2222, 3333, 4444]);
t.deepEqual(s2.no_retweet_ids.toArray(), [1111, 2222, 3333, 4444]);
});
test('addNoRetweetUserIds() removes retweets retweeted by the ID users', t => {
const rt = fixture.retweeted();
const tw = fixture.tweet_other();
const tw2 = fixture.tweet();
const s1 = getState([tw, rt, tw2]);
const home = s1.addNoRetweetUserIds([tw.user.id, rt.user.id]).home.toArray();
t.deepEqual(home.map(i => (i as Tweet).id), [tw.id, tw2.id]);
});
test('updateActivity() adds "liked" status to mention', t => {
const tw = fixture.tweet();
const u = fixture.other_user();
const u2 = fixture.other_user2();
const s1 = getState().updateActivity('liked', tw, u);
t.is(s1.mention.size, 1);
const l = s1.mention.get(0) as Activity;
t.true(l instanceof Activity);
t.is(l.kind, 'liked');
t.is(l.by.length, 1);
t.is(l.by[0].id, u.id);
t.is(l.status.id, tw.id);
t.true(s1.notified.mention);
t.false(s1.notified.home);
const s2 = s1.update({notified: {home: false, mention: false}}).updateActivity('liked', tw, u2);
t.is(s2.mention.size, 1);
const l2 = s2.mention.get(0) as Activity;
t.is(l2.by.length, 2);
t.is(l2.by[0].id, u2.id);
t.true(s2.notified.mention);
t.false(s2.notified.home);
});
test('updateActivity() updates activity count of related status in timeline', t => {
const tw = fixture.tweet();
const tw2 = fixture.tweet_other();
const updated = tw.clone();
const rp = fixture.in_reply_to_from_other();
const s1 = getState([tw2, tw]).updateActivity('liked', updated, fixture.other_user());
t.is(s1.home.get(1), updated);
t.is(s1.home.get(0), tw2);
const s2 = getState()
.updateActivity('liked', tw, fixture.other_user())
.addMentions([rp]);
t.is(s2.mention.size, 2);
t.true(s2.mention.get(0) instanceof Tweet);
t.true(s2.mention.get(1) instanceof Activity);
// Updated activity will be put on the top of mention
const s3 = s2.updateActivity('liked', tw, fixture.other_user2());
t.is(s3.mention.size, 2);
t.true(s3.mention.get(0) instanceof Activity);
t.true(s3.mention.get(1) instanceof Tweet);
});
test('updateActivity() does not move focus on updating activity in timeline', t => {
const tw = fixture.tweet();
const rp = fixture.in_reply_to_from_other();
const s = getState([], 'mention', [tw])
.updateActivity('liked', tw, fixture.other_user())
.addMentions([rp]);
const s1 = s.focusOn(0).updateActivity('liked', tw, fixture.other_user2());
// Continue to focus on the tweet as before activity updated
t.is(s1.focus_index, 1);
const s2 = s.focusOn(2).updateActivity('liked', tw, fixture.other_user2());
t.is(s2.focus_index, 2);
});
test('replaceSeparatorWithItems() replaces separator with items', t => {
const tw = fixture.tweet();
const tw2 = fixture.tweet_other();
const rp = fixture.in_reply_to_from_other();
const rt = fixture.retweeted();
const s = getState([tw, new Separator(), tw2]);
const s1 = s.replaceSeparatorWithItems('home', 1, [tw, tw2, tw]);
t.is(s1.home.size, 5);
t.deepEqual(s1.home.toArray().map(i => (i as Tweet).id), [tw.id, tw.id, tw2.id, tw.id, tw2.id]);
const s2 = getState().addSeparator().addNewTweets([rp, rt]);
t.is(s2.mention.size, 3);
const s3 = s2.replaceSeparatorWithItems('mention', 2, [rp, tw, tw2]);
t.deepEqual(s3.mention.toArray().map(i => {
if (i instanceof Activity) {
return i.status.id;
} else if (i instanceof Tweet) {
return i.id;
} else {
return null;
}
}), [rt.retweeted_status.id, rp.id, rp.id, tw.id, tw2.id]);
});
test("replaceSeparatorWithItems() filters rejected ID users' tweets", t => {
const tw = fixture.tweet_other();
const rp = fixture.in_reply_to_from_other();
const s1 = getState([new Separator()]).addRejectedIds([tw.user.id]);
const s2 = s1.replaceSeparatorWithItems('home', 0, [tw]);
t.is(s2.home.size, 0);
setMuteConfig({home: true, mention: true});
const s3 = getState([], 'mention', [new Separator()]).addRejectedIds([rp.user.id]);
const s4 = s3.replaceSeparatorWithItems('mention', 0, [rp]);
t.is(s4.mention.size, 0);
setMuteConfig({home: false, mention: false});
const s5 = getState([], 'mention', [new Separator()]).addRejectedIds([rp.user.id]);
const s6 = s5.replaceSeparatorWithItems('mention', 0, [rp]);
t.is(s6.mention.size, 1);
}); | the_stack |
import * as React from 'react';
import * as ReactModal from 'react-modal';
import { connect } from 'react-redux';
import {Datum} from 'vega';
import {addPipeline, derivePipeline} from '../../actions/pipelineActions';
import {Dataset, DatasetRecord, ValuesDatasetRecord} from '../../store/factory/Dataset';
import {Pipeline, PipelineRecord} from '../../store/factory/Pipeline';
import * as dsUtils from '../../util/dataset-utils';
import {get, read} from '../../util/io';
import DataTable from './DataTable';
import DataURL from './DataURL';
import {State} from '../../store';
const NAME_REGEX = /([\w\d_-]*)\.?[^\\\/]*$/i;
const vegaDatasets = require('vega-datasets');
const highlightedDatasets = [
{
label: 'Cars',
name: 'cars.json',
description: 'Vehicular data which consists of names, cylinders and displacement',
},
{
label: 'Seattle Weather',
name: 'seattle-weather.csv',
description: 'Seattle weather data, including temperature, precipitation, and type of weather',
},
{
label: 'Stocks',
name: 'stocks.csv',
description: 'Stock data including symbols, dates, and prices',
},
{
label: 'Budgets',
name: 'budgets.json',
description: 'Projected and real U.S. national budgets, from NYT’s Amanda Cox',
},
{
label: 'S&P 500',
name: 'sp500.csv',
description: 'Date and price data for the S&P 500 stock index',
},
];
const vegaDatasetFilenames = Object.keys(vegaDatasets).filter(n => n.endsWith('.csv') || n.endsWith('.tsv') || n.endsWith('.json'))
.filter(n => {
return ![
// remove the ones that are already in highlightedDatasets
...highlightedDatasets.map(d => d.name),
// remove because format doesn't work with createDataset
'annual-precip.json',
'miserables.json',
'londonBoroughs.json',
'us-10m.json',
'volcano.json',
'weather.json',
'world-110m.json',
// remove because it looks weird
'movies.json',
'budget.json',
// remove because too large for lyra
'earthquakes.json',
].includes(n);
}).sort();
const vegaDatasetUrls = vegaDatasetFilenames.map(n => vegaDatasets[n].url);
interface OwnProps {
closeModal: () => void;
modalIsOpen: boolean;
}
interface StateProps {
datasets: Map<string, DatasetRecord>;
pipelines: PipelineRecord[];
}
interface DispatchProps {
addPipeline: (pipeline: PipelineRecord, dataset: DatasetRecord, values: Datum[]) => void;
derivePipeline: (pipelineId: number) => void;
}
function mapStateToProps(state: State): StateProps {
const pipelines = state.getIn(['vis', 'present', 'pipelines']).valueSeq().toArray();
const datasets = state.getIn(['vis', 'present', 'datasets']);
return {
pipelines,
datasets,
}
}
const mapDispatch: DispatchProps = {
addPipeline,
derivePipeline
};
export interface OwnState {
error: string;
success: any;
loading: boolean;
showPreview: boolean;
selectedExample: string;
selectedVegaDataset: string;
name: string;
pipeline: PipelineRecord;
dataset: DatasetRecord;
values: Datum[];
isDerived: boolean; // for deriving pipelines
}
export class PipelineModal extends React.Component<OwnProps & StateProps & DispatchProps, OwnState> {
private initialState: OwnState = {
error: null,
success: null,
loading: false,
showPreview: false,
selectedExample: null,
selectedVegaDataset: vegaDatasetUrls.length ? vegaDatasetUrls[0] : '',
name: null,
pipeline: null,
dataset: null,
values: null,
isDerived: false
};
constructor(props) {
super(props);
this.state = this.initialState;
this.loadURL = this.loadURL.bind(this);
this.fopen = this.fopen.bind(this);
}
public createPipeline(id: string) {
const name = id.match(NAME_REGEX)[1];
this.setState({name, pipeline: Pipeline({name})});
}
public createDataset(data: string) {
const parsed = dsUtils.parseRaw(data);
const values = parsed.values;
this.setState({
values,
dataset: Dataset({
name: this.state.name,
format: parsed.format,
_schema: dsUtils.schema(values)
})
});
}
public success(msg: string | boolean, selectedExample?: string) {
this.setState({
error: null,
success: msg || null,
showPreview: true,
selectedExample,
isDerived: false
});
}
public error(err) {
this.setState({
error: err.statusText || err.message || 'An error occurred!',
success: null,
selectedExample: null,
isDerived: false
});
}
public done(save) {
const state = this.state;
if (save && state.error === null) {
if (this.state.isDerived) {
this.props.derivePipeline(state.pipeline._id);
}
else {
this.props.addPipeline(state.pipeline, state.dataset, state.values);
}
}
this.setState(this.initialState);
this.props.closeModal();
}
public loadURL(url: string, example?: boolean) {
this.createPipeline(url);
this.setState({loading: true});
get(url, (data, err) => {
this.setState({loading: false});
if (err) {
this.error(err);
} else {
this.createDataset(data);
this.success(example ? null : `Successfully imported ${url}`);
this.setState({selectedExample: url});
}
});
}
public selectPipelineToDerive(pipeline: PipelineRecord) {
const dataset = this.props.datasets.get(String(pipeline._source));
this.setState({
name: pipeline.name,
pipeline,
dataset,
values: dsUtils.output(dataset._id),
isDerived: true,
showPreview: true,
selectedExample: String(pipeline._id)
});
}
public fopen(evt) {
read(evt.target.files, (data, file) => {
this.createPipeline(file.name);
this.createDataset(data);
this.success(`Successfully imported ${file.name}`);
});
}
public render() {
const props = this.props;
const state = this.state;
const loading = state.loading;
const error = state.error;
const success = state.success;
const preview = state.showPreview;
const close = this.done.bind(this, false);
const style = {
overlay: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
content: {
// position: null,
overflow: 'hidden',
top: null, bottom: null, left: null, right: null,
width: '550px',
height: 'auto',
padding: null
}
};
return (
<ReactModal isOpen={props.modalIsOpen} onRequestClose={close} contentLabel='Pipeline Modal'
style={style}>
<div className='pipelineModal'>
<span className='closeModal' onClick={close}>close</span>
<div className='row'>
<div className='examples'>
<h2>Example Datasets</h2>
<ul>
{highlightedDatasets.map(function(example) {
const name = example.label;
const description = example.description;
const url = vegaDatasets[example.name].url;
const className = state.selectedExample === url ? 'selected' : null;
return (
<li key={name} onClick={this.loadURL.bind(this, url, true)}
className={className}>
<p className='example-name'>{name}</p>
<p>{description}</p>
</li>
);
}, this)}
<li className={vegaDatasetUrls.includes(state.selectedExample) ? 'selected' : null}
onClick={this.loadURL.bind(this, state.selectedVegaDataset, true)}>
<p className='example-name'>More Example Datasets</p>
<select value={state.selectedVegaDataset} onChange={(e) => {this.setState({selectedVegaDataset: e.target.value})}}>
{
vegaDatasetFilenames.map(name => {
return <option key={name} value={vegaDatasets[name].url}>{name}</option>
})
}
</select>
</li>
</ul>
</div>
<div className='load'>
<h2>Import a Dataset</h2>
<p>
Data must be in a tabular form. Supported import
formats include <abbr title='JavaScript Object Notation'>json</abbr>, <abbr title='Comma-Separated Values'>csv</abbr> and <abbr title='Tab-Separated Values'>tsv</abbr>
</p>
<p><input type='file' accept='.json,.tsv,.csv' onChange={this.fopen} /></p>
<p>or</p>
<DataURL loadURL={this.loadURL} />
</div>
</div>
{
this.props.pipelines.length ? (
<div className='row'>
<div className='derive'>
<h2>Derive from Existing Dataset</h2>
<ul>
{this.props.pipelines.map(function(pipeline) {
const name = pipeline.name;
const className = state.selectedExample === String(pipeline._id) ? 'selected' : null;
return (
<li key={name} onClick={() => this.selectPipelineToDerive(pipeline)}
className={className}>
<p className='pipeline-name'>{name}</p>
{/* <p>{description}</p> */}
</li>
);
}, this)}
</ul>
</div>
</div>
) : null
}
{error ? <div className='error-message'>{error}</div> : null}
{success ? <div className='success-message'>{success}</div> : null}
{!preview && loading ? <div className='loading-message'>Loading dataset...</div> : null}
{!preview || error ? null : (
<div className='row'>
<div className='preview'>
<h2>Preview</h2>
{loading ? <div className='loading-message'>Loading dataset...</div> : null}
<DataTable className='source'
values={state.values} schema={state.dataset._schema} limit={20} />
<button className='button button-success'
onClick={this.done.bind(this, true)}>
Import
</button>
</div>
</div>
)}
</div>
</ReactModal>
);
}
}
export default connect(mapStateToProps, mapDispatch)(PipelineModal); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [codeguru-reviewer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncodegurureviewer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class CodeguruReviewer extends PolicyStatement {
public servicePrefix = 'codeguru-reviewer';
/**
* Statement provider for service [codeguru-reviewer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncodegurureviewer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to associates a repository with Amazon CodeGuru Reviewer
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* Dependent actions:
* - codecommit:ListRepositories
* - codecommit:TagResource
* - events:PutRule
* - events:PutTargets
* - iam:CreateServiceLinkedRole
* - s3:CreateBucket
* - s3:ListBucket
* - s3:PutBucketPolicy
* - s3:PutLifecycleConfiguration
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_AssociateRepository.html
*/
public toAssociateRepository() {
return this.to('AssociateRepository');
}
/**
* Grants permission to create a code review
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* Dependent actions:
* - s3:GetObject
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_CreateCodeReview.html
*/
public toCreateCodeReview() {
return this.to('CreateCodeReview');
}
/**
* Grants permission to perform webbased oauth handshake for 3rd party providers
*
* Access Level: Read
*/
public toCreateConnectionToken() {
return this.to('CreateConnectionToken');
}
/**
* Grants permission to describe a code review
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_DescribeCodeReview.html
*/
public toDescribeCodeReview() {
return this.to('DescribeCodeReview');
}
/**
* Grants permission to describe a recommendation feedback on a code review
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_DescribeRecommendationFeedback.html
*/
public toDescribeRecommendationFeedback() {
return this.to('DescribeRecommendationFeedback');
}
/**
* Grants permission to describe a repository association
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_DescribeRepositoryAssociation.html
*/
public toDescribeRepositoryAssociation() {
return this.to('DescribeRepositoryAssociation');
}
/**
* Grants permission to disassociate a repository with Amazon CodeGuru Reviewer
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* Dependent actions:
* - codecommit:UntagResource
* - events:DeleteRule
* - events:RemoveTargets
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_DisassociateRepository.html
*/
public toDisassociateRepository() {
return this.to('DisassociateRepository');
}
/**
* Grants permission to view pull request metrics in console
*
* Access Level: Read
*/
public toGetMetricsData() {
return this.to('GetMetricsData');
}
/**
* Grants permission to list summary of code reviews
*
* Access Level: List
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_ListCodeReviews.html
*/
public toListCodeReviews() {
return this.to('ListCodeReviews');
}
/**
* Grants permission to list summary of recommendation feedback on a code review
*
* Access Level: List
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_ListRecommendationFeedback.html
*/
public toListRecommendationFeedback() {
return this.to('ListRecommendationFeedback');
}
/**
* Grants permission to list summary of recommendations on a code review
*
* Access Level: List
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_ListRecommendations.html
*/
public toListRecommendations() {
return this.to('ListRecommendations');
}
/**
* Grants permission to list summary of repository associations
*
* Access Level: List
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_ListRepositoryAssociations.html
*/
public toListRepositoryAssociations() {
return this.to('ListRepositoryAssociations');
}
/**
* Grants permission to list the resource attached to a associated repository ARN
*
* Access Level: List
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list 3rd party providers repositories in console
*
* Access Level: Read
*/
public toListThirdPartyRepositories() {
return this.to('ListThirdPartyRepositories');
}
/**
* Grants permission to put feedback for a recommendation on a code review
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_PutRecommendationFeedback.html
*/
public toPutRecommendationFeedback() {
return this.to('PutRecommendationFeedback');
}
/**
* Grants permission to attach resource tags to an associated repository ARN
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to disassociate resource tags from an associated repository ARN
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_UnTagResource.html
*/
public toUnTagResource() {
return this.to('UnTagResource');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateRepository",
"CreateCodeReview",
"DisassociateRepository",
"PutRecommendationFeedback"
],
"Read": [
"CreateConnectionToken",
"DescribeCodeReview",
"DescribeRecommendationFeedback",
"DescribeRepositoryAssociation",
"GetMetricsData",
"ListThirdPartyRepositories"
],
"List": [
"ListCodeReviews",
"ListRecommendationFeedback",
"ListRecommendations",
"ListRepositoryAssociations",
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UnTagResource"
]
};
/**
* Adds a resource of type association to the statement
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onAssociation(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codeguru-reviewer:${Region}:${Account}:association:${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type codereview to the statement
*
* @param codeReviewUuid - Identifier for the codeReviewUuid.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onCodereview(codeReviewUuid: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codeguru-reviewer:${Region}:${Account}:code-review:${CodeReviewUuid}';
arn = arn.replace('${CodeReviewUuid}', codeReviewUuid);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type repository to the statement
*
* https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/auth-and-access-control-iam-access-control-identity-based.html#arn-formats
*
* @param repositoryName - Identifier for the repositoryName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onRepository(repositoryName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codecommit:${Region}:${Account}:${RepositoryName}';
arn = arn.replace('${RepositoryName}', repositoryName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type connection to the statement
*
* @param connectionId - Identifier for the connectionId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onConnection(connectionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codestar-connections:${Region}:${Account}:connection/${ConnectionId}';
arn = arn.replace('${ConnectionId}', connectionId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import * as child_process from 'child_process';
import { ExecException } from 'child_process';
import * as fs from 'fs';
import { stat } from 'fs/promises';
import * as https from 'https';
import * as path from 'path';
import { match } from 'ts-pattern';
import { promisify } from 'util';
import { ConfigurationTarget, ExtensionContext, ProgressLocation, window, workspace, WorkspaceFolder } from 'vscode';
import { Logger } from 'vscode-languageclient';
import { HlsError, MissingToolError, NoMatchingHls } from './errors';
import {
addPathToProcessPath,
comparePVP,
executableExists,
httpsGetSilently,
IEnvVars,
resolvePathPlaceHolders,
resolveServerEnvironmentPATH,
} from './utils';
export { IEnvVars };
type Tool = 'hls' | 'ghc' | 'cabal' | 'stack';
type ToolConfig = Map<Tool, string>;
type ManageHLS = 'GHCup' | 'PATH';
let manageHLS = workspace.getConfiguration('haskell').get('manageHLS') as ManageHLS;
// On Windows the executable needs to be stored somewhere with an .exe extension
const exeExt = process.platform === 'win32' ? '.exe' : '';
/**
* Callback invoked on process termination.
*/
type ProcessCallback = (
error: ExecException | null,
stdout: string,
stderr: string,
resolve: (value: string | PromiseLike<string>) => void,
reject: (reason?: any) => void
) => void;
/**
* Call a process asynchronously.
* While doing so, update the windows with progress information.
* If you need to run a process, consider preferring this over running
* the command directly.
*
* @param binary Name of the binary to invoke.
* @param args Arguments passed directly to the binary.
* @param dir Directory in which the process shall be executed.
* @param logger Logger for progress updates.
* @param title Title of the action, shown to users if available.
* @param cancellable Can the user cancel this process invocation?
* @param envAdd Extra environment variables for this process only.
* @param callback Upon process termination, execute this callback. If given, must resolve promise. On error, stderr and stdout are logged regardless of whether the callback has been specified.
* @returns Stdout of the process invocation, trimmed off newlines, or whatever the `callback` resolved to.
*/
async function callAsync(
binary: string,
args: string[],
logger: Logger,
dir?: string,
title?: string,
cancellable?: boolean,
envAdd?: IEnvVars,
callback?: ProcessCallback
): Promise<string> {
let newEnv: IEnvVars = resolveServerEnvironmentPATH(
workspace.getConfiguration('haskell').get('serverEnvironment') || {}
);
newEnv = { ...(process.env as IEnvVars), ...newEnv, ...(envAdd || {}) };
return window.withProgress(
{
location: ProgressLocation.Notification,
title,
cancellable,
},
async (_, token) => {
return new Promise<string>((resolve, reject) => {
const command: string = binary + ' ' + args.join(' ');
logger.info(`Executing '${command}' in cwd '${dir ? dir : process.cwd()}'`);
token.onCancellationRequested(() => {
logger.warn(`User canceled the execution of '${command}'`);
});
// Need to set the encoding to 'utf8' in order to get back a string
// We execute the command in a shell for windows, to allow use .cmd or .bat scripts
const childProcess = child_process
.execFile(
process.platform === 'win32' ? `"${binary}"` : binary,
args,
{ encoding: 'utf8', cwd: dir, shell: process.platform === 'win32', env: newEnv },
(err, stdout, stderr) => {
if (err) {
logger.error(`Error executing '${command}' with error code ${err.code}`);
logger.error(`stderr: ${stderr}`);
if (stdout) {
logger.error(`stdout: ${stdout}`);
}
}
if (callback) {
callback(err, stdout, stderr, resolve, reject);
} else {
if (err) {
reject(
Error(`\`${command}\` exited with exit code ${err.code}.
Consult the [Extensions Output](https://github.com/haskell/vscode-haskell#investigating-and-reporting-problems)
for details.`)
);
} else {
resolve(stdout?.trim());
}
}
}
)
.on('exit', (code, signal) => {
const msg =
`Execution of '${command}' terminated with code ${code}` + (signal ? `and signal ${signal}` : '');
logger.log(msg);
})
.on('error', (err) => {
if (err) {
logger.error(`Error executing '${command}': name = ${err.name}, message = ${err.message}`);
reject(err);
}
});
token.onCancellationRequested(() => childProcess.kill());
});
}
);
}
/** Gets serverExecutablePath and fails if it's not set.
*/
async function findServerExecutable(
logger: Logger,
folder?: WorkspaceFolder
): Promise<string> {
let exePath = workspace.getConfiguration('haskell').get('serverExecutablePath') as string;
logger.info(`Trying to find the server executable in: ${exePath}`);
exePath = resolvePathPlaceHolders(exePath, folder);
logger.log(`Location after path variables substitution: ${exePath}`);
if (executableExists(exePath)) {
return exePath;
} else {
const msg = `Could not find a HLS binary at ${exePath}! Consider installing HLS via ghcup or change "haskell.manageHLS" in your settings.`;
throw new Error(msg);
}
}
/** Searches the PATH. Fails if nothing is found.
*/
async function findHLSinPATH(_context: ExtensionContext, logger: Logger): Promise<string> {
// try PATH
const exes: string[] = ['haskell-language-server-wrapper', 'haskell-language-server'];
logger.info(`Searching for server executables ${exes.join(',')} in $PATH`);
logger.info(`$PATH environment variable: ${process.env.PATH}`);
for (const exe of exes) {
if (executableExists(exe)) {
logger.info(`Found server executable in $PATH: ${exe}`);
return exe;
}
}
throw new MissingToolError('hls');
}
/**
* Downloads the latest haskell-language-server binaries via GHCup.
* Makes sure that either `ghcup` is available locally, otherwise installs
* it into an isolated location.
* If we figure out the correct GHC version, but it isn't compatible with
* the latest HLS executables, we download the latest compatible HLS binaries
* as a fallback.
*
* @param context Context of the extension, required for metadata.
* @param logger Logger for progress updates.
* @param workingDir Working directory in VSCode.
* @returns Path to haskell-language-server-wrapper
*/
export async function findHaskellLanguageServer(
context: ExtensionContext,
logger: Logger,
workingDir: string,
folder?: WorkspaceFolder
): Promise<[string, string | undefined]> {
logger.info('Finding haskell-language-server');
if (workspace.getConfiguration('haskell').get('serverExecutablePath') as string) {
const exe = await findServerExecutable(logger, folder);
return [exe, undefined];
}
const storagePath: string = await getStoragePath(context);
if (!fs.existsSync(storagePath)) {
fs.mkdirSync(storagePath);
}
// first plugin initialization
if (manageHLS !== 'GHCup' && (!context.globalState.get('pluginInitialized') as boolean | null)) {
const promptMessage = 'How do you want the extension to manage/discover HLS and the relevant toolchain?';
const popup = window.showInformationMessage(
promptMessage,
{ modal: true },
'Automatically via GHCup',
'Manually via PATH'
);
const decision = (await popup) || null;
if (decision === 'Automatically via GHCup') {
manageHLS = 'GHCup';
} else if (decision === 'Manually via PATH') {
manageHLS = 'PATH';
} else {
window.showWarningMessage(
"Choosing default PATH method for HLS discovery. You can change this via 'haskell.manageHLS' in the settings."
);
manageHLS = 'PATH';
}
workspace.getConfiguration('haskell').update('manageHLS', manageHLS, ConfigurationTarget.Global);
context.globalState.update('pluginInitialized', true);
}
if (manageHLS === 'PATH') {
const exe = await findHLSinPATH(context, logger);
return [exe, undefined];
} else {
// we manage HLS, make sure ghcup is installed/available
await upgradeGHCup(context, logger);
// boring init
let latestHLS: string | undefined | null;
let latestCabal: string | undefined | null;
let latestStack: string | undefined | null;
let recGHC: string | undefined | null = 'recommended';
let projectHls: string | undefined | null;
let projectGhc: string | undefined | null;
// support explicit toolchain config
const toolchainConfig: ToolConfig = new Map(
Object.entries(workspace.getConfiguration('haskell').get('toolchain') as any)
) as ToolConfig;
if (toolchainConfig) {
latestHLS = toolchainConfig.get('hls');
latestCabal = toolchainConfig.get('cabal');
latestStack = toolchainConfig.get('stack');
recGHC = toolchainConfig.get('ghc');
projectHls = latestHLS;
projectGhc = recGHC;
}
// get a preliminary toolchain for finding the correct project GHC version
// (we need HLS and cabal/stack and ghc as fallback),
// later we may install a different toolchain that's more project-specific
if (latestHLS === undefined) {
latestHLS = await getLatestToolFromGHCup(context, logger, 'hls');
}
if (latestCabal === undefined) {
latestCabal = await getLatestToolFromGHCup(context, logger, 'cabal');
}
if (latestStack === undefined) {
latestStack = await getLatestToolFromGHCup(context, logger, 'stack');
}
if (recGHC === undefined) {
recGHC = !executableExists('ghc')
? await getLatestAvailableToolFromGHCup(context, logger, 'ghc', 'recommended')
: null;
}
// download popups
const promptBeforeDownloads = workspace.getConfiguration('haskell').get('promptBeforeDownloads') as boolean;
if (promptBeforeDownloads) {
const hlsInstalled = latestHLS ? await toolInstalled(context, logger, 'hls', latestHLS) : undefined;
const cabalInstalled = latestCabal ? await toolInstalled(context, logger, 'cabal', latestCabal) : undefined;
const stackInstalled = latestStack ? await toolInstalled(context, logger, 'stack', latestStack) : undefined;
const ghcInstalled = executableExists('ghc')
? new InstalledTool(
'ghc',
await callAsync(`ghc${exeExt}`, ['--numeric-version'], logger, undefined, undefined, false)
)
: // if recGHC is null, that means user disabled automatic handling,
recGHC !== null
? await toolInstalled(context, logger, 'ghc', recGHC)
: undefined;
const toInstall: InstalledTool[] = [hlsInstalled, cabalInstalled, stackInstalled, ghcInstalled].filter(
(tool) => tool && !tool.installed
) as InstalledTool[];
if (toInstall.length > 0) {
const decision = await window.showInformationMessage(
`Need to download ${toInstall.map((t) => t.nameWithVersion).join(', ')}, continue?`,
'Yes',
'No',
"Yes, don't ask again"
);
if (decision === 'Yes') {
logger.info(`User accepted download for ${toInstall.map((t) => t.nameWithVersion).join(', ')}.`);
} else if (decision === "Yes, don't ask again") {
logger.info(
`User accepted download for ${toInstall.map((t) => t.nameWithVersion).join(', ')} and won't be asked again.`
);
workspace.getConfiguration('haskell').update('promptBeforeDownloads', false);
} else {
toInstall.forEach((tool) => {
if (tool !== undefined && !tool.installed) {
if (tool.name === 'hls') {
throw new MissingToolError('hls');
} else if (tool.name === 'cabal') {
latestCabal = null;
} else if (tool.name === 'stack') {
latestStack = null;
} else if (tool.name === 'ghc') {
recGHC = null;
}
}
});
}
}
}
// our preliminary toolchain
const latestToolchainBindir = await callGHCup(
context,
logger,
[
'run',
...(latestHLS ? ['--hls', latestHLS] : []),
...(latestCabal ? ['--cabal', latestCabal] : []),
...(latestStack ? ['--stack', latestStack] : []),
...(recGHC ? ['--ghc', recGHC] : []),
'--install',
],
'Installing latest toolchain for bootstrap',
true,
(err, stdout, _stderr, resolve, reject) => {
err ? reject("Couldn't install latest toolchain") : resolve(stdout?.trim());
}
);
// now figure out the actual project GHC version and the latest supported HLS version
// we need for it (e.g. this might in fact be a downgrade for old GHCs)
if (projectHls === undefined || projectGhc === undefined) {
const res = await getLatestProjectHLS(context, logger, workingDir, latestToolchainBindir);
if (projectHls === undefined) {
projectHls = res[0];
}
if (projectGhc === undefined) {
projectGhc = res[1];
}
}
// more download popups
if (promptBeforeDownloads) {
const hlsInstalled = projectHls ? await toolInstalled(context, logger, 'hls', projectHls) : undefined;
const ghcInstalled = projectGhc ? await toolInstalled(context, logger, 'ghc', projectGhc) : undefined;
const toInstall: InstalledTool[] = [hlsInstalled, ghcInstalled].filter(
(tool) => tool && !tool.installed
) as InstalledTool[];
if (toInstall.length > 0) {
const decision = await window.showInformationMessage(
`Need to download ${toInstall.map((t) => t.nameWithVersion).join(', ')}, continue?`,
{ modal: true },
'Yes',
'No',
"Yes, don't ask again"
);
if (decision === 'Yes') {
logger.info(`User accepted download for ${toInstall.map((t) => t.nameWithVersion).join(', ')}.`);
} else if (decision === "Yes, don't ask again") {
logger.info(
`User accepted download for ${toInstall.map((t) => t.nameWithVersion).join(', ')} and won't be asked again.`
);
workspace.getConfiguration('haskell').update('promptBeforeDownloads', false);
} else {
toInstall.forEach((tool) => {
if (!tool.installed) {
if (tool.name === 'hls') {
throw new MissingToolError('hls');
} else if (tool.name === 'ghc') {
projectGhc = null;
}
}
});
}
}
}
// now install the proper versions
const hlsBinDir = await callGHCup(
context,
logger,
[
'run',
...(projectHls ? ['--hls', projectHls] : []),
...(latestCabal ? ['--cabal', latestCabal] : []),
...(latestStack ? ['--stack', latestStack] : []),
...(projectGhc ? ['--ghc', projectGhc] : []),
'--install',
],
`Installing project specific toolchain: ${[
['hls', projectHls],
['GHC', projectGhc],
['cabal', latestCabal],
['stack', latestStack],
]
.filter((t) => t[1])
.map((t) => `${t[0]}-${t[1]}`)
.join(', ')}`,
true
);
if (projectHls) {
return [path.join(hlsBinDir, `haskell-language-server-wrapper${exeExt}`), hlsBinDir];
} else {
const exe = await findHLSinPATH(context, logger);
return [exe, hlsBinDir];
}
}
}
async function callGHCup(
context: ExtensionContext,
logger: Logger,
args: string[],
title?: string,
cancellable?: boolean,
callback?: ProcessCallback
): Promise<string> {
const metadataUrl = workspace.getConfiguration('haskell').metadataURL;
if (manageHLS === 'GHCup') {
const ghcup = await findGHCup(context, logger);
return await callAsync(
ghcup,
['--no-verbose'].concat(metadataUrl ? ['-s', metadataUrl] : []).concat(args),
logger,
undefined,
title,
cancellable,
{
// omit colourful output because the logs are uglier
NO_COLOR: '1',
},
callback
);
} else {
throw new HlsError(`Internal error: tried to call ghcup while haskell.manageHLS is set to ${manageHLS}. Aborting!`);
}
}
async function getLatestProjectHLS(
context: ExtensionContext,
logger: Logger,
workingDir: string,
toolchainBindir: string
): Promise<[string, string]> {
// get project GHC version, but fallback to system ghc if necessary.
const projectGhc = toolchainBindir
? await getProjectGHCVersion(toolchainBindir, workingDir, logger).catch(async (e) => {
logger.error(`${e}`);
window.showWarningMessage(
`I had trouble figuring out the exact GHC version for the project. Falling back to using 'ghc${exeExt}'.`
);
return await callAsync(`ghc${exeExt}`, ['--numeric-version'], logger, undefined, undefined, false);
})
: await callAsync(`ghc${exeExt}`, ['--numeric-version'], logger, undefined, undefined, false);
// first we get supported GHC versions from available HLS bindists (whether installed or not)
const metadataMap = (await getHLSesfromMetadata(context, logger)) || new Map<string, string[]>();
// then we get supported GHC versions from currently installed HLS versions
const ghcupMap = (await getHLSesFromGHCup(context, logger)) || new Map<string, string[]>();
// since installed HLS versions may support a different set of GHC versions than the bindists
// (e.g. because the user ran 'ghcup compile hls'), we need to merge both maps, preferring
// values from already installed HLSes
const merged = new Map<string, string[]>([...metadataMap, ...ghcupMap]); // right-biased
// now sort and get the latest suitable version
const latest = [...merged]
.filter(([_k, v]) => v.some((x) => x === projectGhc))
.sort(([k1, _v1], [k2, _v2]) => comparePVP(k1, k2))
.pop();
if (!latest) {
throw new NoMatchingHls(projectGhc);
} else {
return [latest[0], projectGhc];
}
}
/**
* Obtain the project ghc version from the HLS - Wrapper (which must be in PATH now).
* Also, serves as a sanity check.
* @param toolchainBindir Path to the toolchainn bin directory (added to PATH)
* @param workingDir Directory to run the process, usually the root of the workspace.
* @param logger Logger for feedback.
* @returns The GHC version, or fail with an `Error`.
*/
export async function getProjectGHCVersion(
toolchainBindir: string,
workingDir: string,
logger: Logger
): Promise<string> {
const title = 'Working out the project GHC version. This might take a while...';
logger.info(title);
const args = ['--project-ghc-version'];
const newPath = await addPathToProcessPath(toolchainBindir);
const environmentNew: IEnvVars = {
PATH: newPath,
};
return callAsync(
'haskell-language-server-wrapper',
args,
logger,
workingDir,
title,
false,
environmentNew,
(err, stdout, stderr, resolve, reject) => {
if (err) {
// Error message emitted by HLS-wrapper
const regex =
/Cradle requires (.+) but couldn't find it|The program \'(.+)\' version .* is required but the version of.*could.*not be determined|Cannot find the program \'(.+)\'\. User-specified/;
const res = regex.exec(stderr);
if (res) {
for (let i = 1; i < res.length; i++) {
if (res[i]) {
reject(new MissingToolError(res[i]));
}
}
reject(new MissingToolError('unknown'));
}
reject(
Error(
`haskell-language-server --project-ghc-version exited with exit code ${err.code}:\n${stdout}\n${stderr}`
)
);
} else {
logger.info(`The GHC version for the project or file: ${stdout?.trim()}`);
resolve(stdout?.trim());
}
}
);
}
export async function upgradeGHCup(context: ExtensionContext, logger: Logger): Promise<void> {
if (manageHLS === 'GHCup') {
const upgrade = workspace.getConfiguration('haskell').get('upgradeGHCup') as boolean;
if (upgrade) {
await callGHCup(context, logger, ['upgrade'], 'Upgrading ghcup', true);
}
} else {
throw new Error(`Internal error: tried to call ghcup while haskell.manageHLS is set to ${manageHLS}. Aborting!`);
}
}
export async function findGHCup(_context: ExtensionContext, logger: Logger, folder?: WorkspaceFolder): Promise<string> {
logger.info('Checking for ghcup installation');
let exePath = workspace.getConfiguration('haskell').get('ghcupExecutablePath') as string;
if (exePath) {
logger.info(`Trying to find the ghcup executable in: ${exePath}`);
exePath = resolvePathPlaceHolders(exePath, folder);
logger.log(`Location after path variables substitution: ${exePath}`);
if (executableExists(exePath)) {
return exePath;
} else {
throw new Error(`Could not find a ghcup binary at ${exePath}!`);
}
} else {
const localGHCup = ['ghcup'].find(executableExists);
if (!localGHCup) {
throw new MissingToolError('ghcup');
} else {
logger.info(`found ghcup at ${localGHCup}`);
return localGHCup;
}
}
}
export async function getStoragePath(context: ExtensionContext): Promise<string> {
let storagePath: string | undefined = await workspace.getConfiguration('haskell').get('releasesDownloadStoragePath');
if (!storagePath) {
storagePath = context.globalStorageUri.fsPath;
} else {
storagePath = resolvePathPlaceHolders(storagePath);
}
return storagePath;
}
// the tool might be installed or not
async function getLatestToolFromGHCup(context: ExtensionContext, logger: Logger, tool: Tool): Promise<string> {
// these might be custom/stray/compiled, so we try first
const installedVersions = await callGHCup(
context,
logger,
['list', '-t', tool, '-c', 'installed', '-r'],
undefined,
false
);
const latestInstalled = installedVersions.split(/\r?\n/).pop();
if (latestInstalled) {
return latestInstalled.split(/\s+/)[1];
}
return getLatestAvailableToolFromGHCup(context, logger, tool);
}
async function getLatestAvailableToolFromGHCup(
context: ExtensionContext,
logger: Logger,
tool: Tool,
tag?: string,
criteria?: string
): Promise<string> {
// fall back to installable versions
const availableVersions = await callGHCup(
context,
logger,
['list', '-t', tool, '-c', criteria ? criteria : 'available', '-r'],
undefined,
false
).then((s) => s.split(/\r?\n/));
let latestAvailable: string | null = null;
availableVersions.forEach((ver) => {
if (
ver
.split(/\s+/)[2]
.split(',')
.includes(tag ? tag : 'latest')
) {
latestAvailable = ver.split(/\s+/)[1];
}
});
if (!latestAvailable) {
throw new Error(`Unable to find ${tag ? tag : 'latest'} tool ${tool}`);
} else {
return latestAvailable;
}
}
// complements getHLSesfromMetadata, by checking possibly locally compiled
// HLS in ghcup
// If 'targetGhc' is omitted, picks the latest 'haskell-language-server-wrapper',
// otherwise ensures the specified GHC is supported.
async function getHLSesFromGHCup(context: ExtensionContext, logger: Logger): Promise<Map<string, string[]> | null> {
const hlsVersions = await callGHCup(
context,
logger,
['list', '-t', 'hls', '-c', 'installed', '-r'],
undefined,
false
);
const bindir = await callGHCup(context, logger, ['whereis', 'bindir'], undefined, false);
const files = fs.readdirSync(bindir).filter(async (e) => {
return await stat(path.join(bindir, e))
.then((s) => s.isDirectory())
.catch(() => false);
});
const installed = hlsVersions.split(/\r?\n/).map((e) => e.split(/\s+/)[1]);
if (installed?.length) {
const myMap = new Map<string, string[]>();
installed.forEach((hls) => {
const ghcs = files
.filter((f) => f.endsWith(`~${hls}${exeExt}`) && f.startsWith('haskell-language-server-'))
.map((f) => {
const rmPrefix = f.substring('haskell-language-server-'.length);
return rmPrefix.substring(0, rmPrefix.length - `~${hls}${exeExt}`.length);
});
myMap.set(hls, ghcs);
});
return myMap;
} else {
return null;
}
}
async function toolInstalled(
context: ExtensionContext,
logger: Logger,
tool: Tool,
version: string
): Promise<InstalledTool> {
const b = await callGHCup(context, logger, ['whereis', tool, version], undefined, false)
.then((_x) => true)
.catch((_x) => false);
return new InstalledTool(tool, version, b);
}
/**
* Metadata of release information.
*
* Example of the expected format:
*
* ```
* {
* "1.6.1.0": {
* "A_64": {
* "Darwin": [
* "8.10.6",
* ],
* "Linux_Alpine": [
* "8.10.7",
* "8.8.4",
* ],
* },
* "A_ARM": {
* "Linux_UnknownLinux": [
* "8.10.7"
* ]
* },
* "A_ARM64": {
* "Darwin": [
* "8.10.7"
* ],
* "Linux_UnknownLinux": [
* "8.10.7"
* ]
* }
* }
* }
* ```
*
* consult [ghcup metadata repo](https://github.com/haskell/ghcup-metadata/) for details.
*/
export type ReleaseMetadata = Map<string, Map<string, Map<string, string[]>>>;
/**
* Compute Map of supported HLS versions for this platform.
* Fetches HLS metadata information.
*
* @param context Context of the extension, required for metadata.
* @param logger Logger for feedback
* @returns Map of supported HLS versions or null if metadata could not be fetched.
*/
async function getHLSesfromMetadata(context: ExtensionContext, logger: Logger): Promise<Map<string, string[]> | null> {
const storagePath: string = await getStoragePath(context);
const metadata = await getReleaseMetadata(context, storagePath, logger).catch((_e) => null);
if (!metadata) {
window.showErrorMessage('Could not get release metadata');
return null;
}
const plat: Platform | null = match(process.platform)
.with('darwin', (_) => 'Darwin' as Platform)
.with('linux', (_) => 'Linux_UnknownLinux' as Platform)
.with('win32', (_) => 'Windows' as Platform)
.with('freebsd', (_) => 'FreeBSD' as Platform)
.otherwise((_) => null);
if (plat === null) {
throw new Error(`Unknown platform ${process.platform}`);
}
const arch: Arch | null = match(process.arch)
.with('arm', (_) => 'A_ARM' as Arch)
.with('arm64', (_) => 'A_ARM64' as Arch)
.with('x32', (_) => 'A_32' as Arch)
.with('x64', (_) => 'A_64' as Arch)
.otherwise((_) => null);
if (arch === null) {
throw new Error(`Unknown architecture ${process.arch}`);
}
return findSupportedHlsPerGhc(plat, arch, metadata, logger);
}
export type Platform = 'Darwin' | 'Linux_UnknownLinux' | 'Windows' | 'FreeBSD';
export type Arch = 'A_ARM' | 'A_ARM64' | 'A_32' | 'A_64';
/**
* Find all supported GHC versions per HLS version supported on the given
* platform and architecture.
* @param platform Platform of the host.
* @param arch Arch of the host.
* @param metadata HLS Metadata information.
* @param logger Logger.
* @returns Map from HLS version to GHC versions that are supported.
*/
export function findSupportedHlsPerGhc(
platform: Platform,
arch: Arch,
metadata: ReleaseMetadata,
logger: Logger
): Map<string, string[]> {
logger.info(`Platform constants: ${platform}, ${arch}`);
const newMap = new Map<string, string[]>();
metadata.forEach((supportedArch, hlsVersion) => {
const supportedOs = supportedArch.get(arch);
if (supportedOs) {
const ghcSupportedOnOs = supportedOs.get(platform);
if (ghcSupportedOnOs) {
logger.log(`HLS ${hlsVersion} compatible with GHC Versions: ${ghcSupportedOnOs}`);
// copy supported ghc versions to avoid unintended modifications
newMap.set(hlsVersion, [...ghcSupportedOnOs]);
}
}
});
return newMap;
}
/**
* Download GHCUP metadata.
*
* @param _context Extension context.
* @param storagePath Path to put in binary files and caches.
* @param logger Logger for feedback.
* @returns Metadata of releases, or null if the cache can not be found.
*/
async function getReleaseMetadata(
_context: ExtensionContext,
storagePath: string,
logger: Logger
): Promise<ReleaseMetadata | null> {
const releasesUrl = workspace.getConfiguration('haskell').releasesURL
? new URL(workspace.getConfiguration('haskell').releasesURL)
: undefined;
const opts: https.RequestOptions = releasesUrl
? {
host: releasesUrl.host,
path: releasesUrl.pathname,
}
: {
host: 'raw.githubusercontent.com',
path: '/haskell/ghcup-metadata/master/hls-metadata-0.0.1.json',
};
const offlineCache = path.join(storagePath, 'ghcupReleases.cache.json');
/**
* Convert a json value to ReleaseMetadata.
* Assumes the json is well-formed and a valid Release-Metadata.
* @param obj Release Metadata without any typing information but well-formed.
* @returns Typed ReleaseMetadata.
*/
const objectToMetadata = (obj: any): ReleaseMetadata => {
const hlsMetaEntries = Object.entries(obj).map(([hlsVersion, archMap]) => {
const archMetaEntries = Object.entries(archMap as any).map(([arch, supportedGhcVersionsPerOs]) => {
return [arch, new Map(Object.entries(supportedGhcVersionsPerOs as any))] as [string, Map<string, string[]>];
});
return [hlsVersion, new Map(archMetaEntries)] as [string, Map<string, Map<string, string[]>>];
});
return new Map(hlsMetaEntries);
};
async function readCachedReleaseData(): Promise<ReleaseMetadata | null> {
try {
logger.info(`Reading cached release data at ${offlineCache}`);
const cachedInfo = await promisify(fs.readFile)(offlineCache, { encoding: 'utf-8' });
// export type ReleaseMetadata = Map<string, Map<string, Map<string, string[]>>>;
const value: any = JSON.parse(cachedInfo);
return objectToMetadata(value);
} catch (err: any) {
// If file doesn't exist, return null, otherwise consider it a failure
if (err.code === 'ENOENT') {
logger.warn(`No cached release data found at ${offlineCache}`);
return null;
}
throw err;
}
}
try {
const releaseInfo = await httpsGetSilently(opts);
const releaseInfoParsed = JSON.parse(releaseInfo);
// Cache the latest successfully fetched release information
await promisify(fs.writeFile)(offlineCache, JSON.stringify(releaseInfoParsed), { encoding: 'utf-8' });
return objectToMetadata(releaseInfoParsed);
} catch (githubError: any) {
// Attempt to read from the latest cached file
try {
const cachedInfoParsed = await readCachedReleaseData();
window.showWarningMessage(
"Couldn't get the latest haskell-language-server releases from GitHub, used local cache instead: " +
githubError.message
);
return cachedInfoParsed;
} catch (fileError) {
throw new Error("Couldn't get the latest haskell-language-server releases from GitHub: " + githubError.message);
}
}
}
/**
* Tracks the name, version and installation state of tools we need.
*/
class InstalledTool {
/**
* "\<name\>-\<version\>" of the installed Tool.
*/
readonly nameWithVersion: string = '';
/**
* Initialize an installed tool entry.
*
* If optional parameters are omitted, we assume the tool is installed.
*
* @param name Name of the tool.
* @param version Version of the tool, expected to be either SemVer or PVP versioned.
* @param installed Is this tool currently installed?
*/
public constructor(readonly name: string, readonly version: string, readonly installed: boolean = true) {
this.nameWithVersion = `${name}-${version}`;
}
} | the_stack |
import { pick } from 'ramda'
import { describe, Try } from 'riteway'
import {
loadConfigurationWithDefaults,
mergeConfigs,
applyExchangePrefix,
extractValue,
validatePoetVersion,
validatePoetNetwork,
} from './LoadConfiguration'
const defaultConfig = mergeConfigs()
describe('src/LoadConfiguration', async assert => {
assert({
given: 'no arguments',
should: 'return the default config',
actual: mergeConfigs(),
expected: defaultConfig,
})
{
const stringOverride = { MONGODB_HOST: 'one' }
assert({
given: 'a string override',
should: 'return a config containing the string value',
actual: mergeConfigs(stringOverride),
expected: {
...defaultConfig,
mongodbHost: 'one',
mongodbUrl: 'mongodb://one:27017/poet',
},
})
}
{
const numberOverride = { BATCH_CREATION_INTERVAL_IN_SECONDS: '10' }
assert({
given: 'a numerical value as a string override',
should: 'return a config containing the numeric value',
actual: mergeConfigs(numberOverride),
expected: { ...defaultConfig, batchCreationIntervalInSeconds: 10 },
})
}
// TODO: This is here to support using either MONGODB_URL or MONGO_HOST, MONGO_PORT, etc.
// Remove this once local-dev switches over to using the individual env vars.
{
{
const mongodbOverrides = {
MONGODB_USER: 'dylan',
MONGODB_PASSWORD: 'p1960s',
MONGODB_DATABASE: 'poet-test-integration',
}
assert({
given: 'a mongodb user override',
should: 'return a config containing a mongodbUrl with auth info',
actual: mergeConfigs(mongodbOverrides),
expected: {
...defaultConfig,
mongodbUser: 'dylan',
mongodbPassword: 'p1960s',
mongodbDatabase: 'poet-test-integration',
mongodbUrl: 'mongodb://dylan:p1960s@localhost:27017/poet-test-integration',
},
})
}
{
const mongodbOverrides = {
MONGODB_URL: 'foo/bar',
}
assert({
given: 'a mongodb url override',
should: 'return a config using the override',
actual: mergeConfigs(mongodbOverrides),
expected: {
...defaultConfig,
mongodbUrl: 'foo/bar',
},
})
}
}
})
describe('loadConfigurationWithDefaults', async assert => {
const mongodbOverrides = {
API_PORT: '4321',
ENABLE_ANCHORING: 'true',
RABBITMQ_URL: 'foo',
}
const withoutLocalOverrides = loadConfigurationWithDefaults()
assert({
given: 'a local configuration override',
should: 'return a config using the local override',
actual: loadConfigurationWithDefaults(mongodbOverrides),
expected: {
...withoutLocalOverrides,
apiPort: 4321,
enableAnchoring: true,
rabbitmqUrl: 'foo',
},
})
{
const overrideValues = {
EXCHANGE_PREFIX: 'myPrefix',
}
const expected = {
exchangeBatchReaderReadNextDirectoryRequest: 'myPrefix.BATCH_READER::READ_NEXT_DIRECTORY_REQUEST',
exchangeBatchReaderReadNextDirectorySuccess: 'myPrefix.BATCH_READER::READ_NEXT_DIRECTORY_SUCCESS',
exchangeBatchWriterCreateNextBatchRequest: 'myPrefix.BATCH_WRITER::CREATE_NEXT_BATCH_REQUEST',
exchangeBatchWriterCreateNextBatchSuccess: 'myPrefix.BATCH_WRITER::CREATE_NEXT_BATCH_SUCCESS',
exchangeNewClaim: 'myPrefix.NEW_CLAIM',
exchangeClaimIpfsHash: 'myPrefix.CLAIM_IPFS_HASH',
exchangeIpfsHashTxId: 'myPrefix.IPFS_HASH_TX_ID',
exchangePoetAnchorDownloaded: 'myPrefix.POET_ANCHOR_DOWNLOADED',
exchangeClaimsDownloaded: 'myPrefix.CLAIMS_DOWNLOADED',
exchangeClaimsNotDownloaded: 'myPrefix.CLAIMS_NOT_DOWNLOADED',
exchangeStorageWriterStoreNextClaim: 'myPrefix.STORAGE_WRITER::STORE_NEXT_CLAIM',
exchangeGetHealth: 'myPrefix.HEALTH::GET_HEALTH',
}
const keys = Object.keys(expected)
const actual = pick(keys, loadConfigurationWithDefaults(overrideValues))
assert({
given: 'override default values with an EXCHANGE_PREFIX',
should: 'return exchange names with the prefix prepended',
actual,
expected,
})
}
})
describe('src/LoadConfiguration RabbitmqExchangeMessages', async assert => {
{
const defaultValues = {
exchangeBatchReaderReadNextDirectoryRequest: 'BATCH_READER::READ_NEXT_DIRECTORY_REQUEST',
exchangeBatchReaderReadNextDirectorySuccess: 'BATCH_READER::READ_NEXT_DIRECTORY_SUCCESS',
exchangeBatchWriterCreateNextBatchRequest: 'BATCH_WRITER::CREATE_NEXT_BATCH_REQUEST',
exchangeBatchWriterCreateNextBatchSuccess: 'BATCH_WRITER::CREATE_NEXT_BATCH_SUCCESS',
exchangeNewClaim: 'NEW_CLAIM',
exchangeClaimIpfsHash: 'CLAIM_IPFS_HASH',
exchangeIpfsHashTxId: 'IPFS_HASH_TX_ID',
exchangePoetAnchorDownloaded: 'POET_ANCHOR_DOWNLOADED',
exchangeClaimsDownloaded: 'CLAIMS_DOWNLOADED',
exchangeClaimsNotDownloaded: 'CLAIMS_NOT_DOWNLOADED',
exchangeGetHealth: 'HEALTH::GET_HEALTH',
}
const keys = Object.keys(defaultValues)
const actual = pick(keys, defaultConfig)
const expected = defaultValues
assert({
given: 'no arguments',
should: 'return the default config',
actual,
expected,
})
}
{
const overrideValues = {
EXCHANGE_BATCH_READER_READ_NEXT_DIRECTORY_REQUEST: 'override',
EXCHANGE_BATCH_READER_READ_NEXT_DIRECTORY_SUCCESS: 'override',
EXCHANGE_BATCH_WRITER_CREATE_NEXT_BATCH_REQUEST: 'override',
EXCHANGE_BATCH_WRITER_CREATE_NEXT_BATCH_SUCCESS: 'override',
EXCHANGE_NEW_CLAIM: 'override',
EXCHANGE_CLAIM_IPFS_HASH: 'override',
EXCHANGE_IPFS_HASH_TX_ID: 'override',
EXCHANGE_POET_ANCHOR_DOWNLOADED: 'override',
EXCHANGE_CLAIMS_DOWNLOADED: 'override',
EXCHANGE_CLAIMS_NOT_DOWNLOADED: 'override',
EXCHANGE_GET_HEALTH: 'override',
}
const expected = {
exchangeBatchReaderReadNextDirectoryRequest: 'override',
exchangeBatchReaderReadNextDirectorySuccess: 'override',
exchangeBatchWriterCreateNextBatchRequest: 'override',
exchangeBatchWriterCreateNextBatchSuccess: 'override',
exchangeNewClaim: 'override',
exchangeClaimIpfsHash: 'override',
exchangeIpfsHashTxId: 'override',
exchangePoetAnchorDownloaded: 'override',
exchangeClaimsDownloaded: 'override',
exchangeClaimsNotDownloaded: 'override',
exchangeGetHealth: 'override',
}
const keys = Object.keys(expected)
const actual = pick(keys, mergeConfigs(overrideValues))
assert({
given: 'override default values',
should: 'return the new config',
actual,
expected,
})
}
})
describe('src/LoadConfiguration applyExchangePrefix', async assert => {
{
const actual = { exchangePrefix: '' }
const expected = applyExchangePrefix(actual)
assert({
given: 'configVars with the property exchangePrefix with empty string',
should: 'return the same object configVars',
actual,
expected,
})
}
{
const configVars = {
exchangePrefix: 'prefix',
exchangeAnchorNextHashRequest: 'exchangeAnchorNextHashRequest',
exchangeBatchReaderReadNextDirectoryRequest: 'exchangeBatchReaderReadNextDirectoryRequest',
exchangeBatchReaderReadNextDirectorySuccess: 'exchangeBatchReaderReadNextDirectorySuccess',
exchangeBatchWriterCreateNextBatchRequest: 'exchangeBatchWriterCreateNextBatchRequest',
exchangeBatchWriterCreateNextBatchSuccess: 'exchangeBatchWriterCreateNextBatchSuccess',
exchangeNewClaim: 'exchangeNewClaim',
exchangeClaimIpfsHash: 'exchangeClaimIpfsHash',
exchangeIpfsHashTxId: 'exchangeIpfsHashTxId',
exchangePoetAnchorDownloaded: 'exchangePoetAnchorDownloaded',
exchangeClaimsDownloaded: 'exchangeClaimsDownloaded',
exchangeClaimsNotDownloaded: 'exchangeClaimsNotDownloaded',
exchangeStorageWriterStoreNextClaim: 'exchangeStorageWriterStoreNextClaim',
exchangeGetHealth: 'exchangeGetHealth',
exchangePurgeStaleTransactions: 'exchangePurgeStaleTransactions',
exchangeForkDetected: 'exchangeForkDetected',
}
const actual = applyExchangePrefix(configVars)
const expected = {
exchangePrefix: 'prefix',
exchangeAnchorNextHashRequest: 'prefix.exchangeAnchorNextHashRequest',
exchangeBatchReaderReadNextDirectoryRequest: 'prefix.exchangeBatchReaderReadNextDirectoryRequest',
exchangeBatchReaderReadNextDirectorySuccess: 'prefix.exchangeBatchReaderReadNextDirectorySuccess',
exchangeBatchWriterCreateNextBatchRequest: 'prefix.exchangeBatchWriterCreateNextBatchRequest',
exchangeBatchWriterCreateNextBatchSuccess: 'prefix.exchangeBatchWriterCreateNextBatchSuccess',
exchangeNewClaim: 'prefix.exchangeNewClaim',
exchangeClaimIpfsHash: 'prefix.exchangeClaimIpfsHash',
exchangeIpfsHashTxId: 'prefix.exchangeIpfsHashTxId',
exchangePoetAnchorDownloaded: 'prefix.exchangePoetAnchorDownloaded',
exchangeClaimsDownloaded: 'prefix.exchangeClaimsDownloaded',
exchangeClaimsNotDownloaded: 'prefix.exchangeClaimsNotDownloaded',
exchangeStorageWriterStoreNextClaim: 'prefix.exchangeStorageWriterStoreNextClaim',
exchangeGetHealth: 'prefix.exchangeGetHealth',
exchangePurgeStaleTransactions: 'prefix.exchangePurgeStaleTransactions',
exchangeForkDetected: 'prefix.exchangeForkDetected',
}
assert({
given: 'configVars with the property exchangePrefix with a custom prefix',
should: 'return the same object configVars with the custom prefix over the name of exchanges',
actual,
expected,
})
}
})
describe('src/LoadConfiguration extractValue', async assert => {
{
const actual = extractValue('false')
const expected = false
assert({
given: 'false like as string',
should: 'return false as boolean',
actual,
expected,
})
}
{
const actual = extractValue('true')
const expected = true
assert({
given: 'true like as string',
should: 'return true as boolean',
actual,
expected,
})
}
})
describe('src/LoadConfiguration validatePoetVersion', async assert => {
{
assert({
given: 'an invalid Poet version -1',
should: `return the message 'poetVersion must be an integer between 0 and 65535'`,
actual: Try(validatePoetVersion, -1).message,
expected: 'poetVersion must be an integer between 0 and 65535',
})
}
{
assert({
given: 'an invalid Poet version 65536',
should: `return the message 'poetVersion must be an integer between 0 and 65535'`,
actual: Try(validatePoetVersion, 65536).message,
expected: 'poetVersion must be an integer between 0 and 65535',
})
}
})
describe('src/LoadConfiguration validatePoetNetwork', async assert => {
{
assert({
given: 'a string with more 4 letters as Poet Network',
should: `return the message 'Field poetNetwork must have a length of 4'`,
actual: Try(validatePoetNetwork, '12345').message,
expected: 'Field poetNetwork must have a length of 4',
})
}
}) | the_stack |
import React, { Component } from 'react';
import { TextInput, FileUploader, Accordion, AccordionItem, Link, FileUploaderItem, InlineNotification, NotificationKind } from 'carbon-components-react';
import IPackageRegistryEntry from '../../../../interfaces/IPackageRegistryEntry';
import './DeployStepTwo.scss';
interface IProps {
hasV1Capabilities: boolean;
selectedPackage: IPackageRegistryEntry;
onDefinitionNameChange: (name: string, nameInvalid: boolean) => void;
onDefinitionVersionChange: (name: string, versionInvalid: boolean) => void;
onCollectionChange: (file: File) => void;
onEndorsementPolicyChange: (policy: string) => void;
enableOrDisableNext: (value: boolean) => void;
currentDefinitionName: string;
currentDefinitionVersion: string;
currentCollectionFile: File | undefined;
committedDefinitions: string[];
endorsementPolicy: string | undefined;
}
interface DeployStepTwoState {
definitionNameValue: string;
definitionVersionValue: string;
collectionFile: File | undefined;
endorsementPolicy: string | undefined;
}
class DeployStepTwo extends Component<IProps, DeployStepTwoState> {
nameInvalid: boolean;
versionInvalid: boolean;
constructor(props: Readonly<IProps>) {
super(props);
this.state = {
definitionNameValue: this.props.currentDefinitionName ? this.props.currentDefinitionName : this.props.selectedPackage.name,
definitionVersionValue: this.props.currentDefinitionVersion ? this.props.currentDefinitionVersion : this.props.selectedPackage.version as string,
collectionFile: this.props.currentCollectionFile ? this.props.currentCollectionFile : undefined,
endorsementPolicy: this.props.endorsementPolicy ? this.props.endorsementPolicy : ''
};
this.handleDefinitionNameChange = this.handleDefinitionNameChange.bind(this);
this.handleDefinitionVersionChange = this.handleDefinitionVersionChange.bind(this);
this.isNameInvalid = this.isNameInvalid.bind(this);
this.isVersionInvalid = this.isVersionInvalid.bind(this);
this.nameInvalid = this.isNameInvalid(this.state.definitionNameValue);
this.versionInvalid = this.isVersionInvalid(this.state.definitionVersionValue);
this.handleCollectionChange = this.handleCollectionChange.bind(this);
this.handleEndorsementPolicyChange = this.handleEndorsementPolicyChange.bind(this);
}
componentWillReceiveProps(props: IProps): void {
if (props.currentDefinitionName !== this.state.definitionNameValue || props.currentDefinitionVersion !== this.state.definitionVersionValue) {
this.setState({ definitionNameValue: props.currentDefinitionName, definitionVersionValue: props.currentDefinitionVersion });
}
}
handleDefinitionNameChange(data: any): void {
const name: string = data.target.value.trim();
this.nameInvalid = this.isNameInvalid(name);
this.props.onDefinitionNameChange(name, this.nameInvalid);
}
handleDefinitionVersionChange(data: any): void {
const version: string = data.target.value.trim();
this.versionInvalid = this.isVersionInvalid(version);
this.props.onDefinitionVersionChange(version, this.versionInvalid);
}
handleEndorsementPolicyChange(data: any): void {
const policy: string = data.target.value.trim();
this.props.onEndorsementPolicyChange(policy);
}
isNameInvalid(name: string): boolean {
const regex: RegExp = /^[a-zA-Z0-9-_]+$/;
const validName: boolean = regex.test(name);
if (name.length === 0 || !validName) {
return true;
} else {
return false;
}
}
isVersionInvalid(version: string): boolean {
if (version.length === 0) {
return true;
} else {
return false;
}
}
handleCollectionChange(event: any): void {
const files: FileList = event.target.files;
if (files.length > 0) {
const file: File = files[0];
this.props.onCollectionChange(file);
}
}
renderInlineNotification(): JSX.Element | undefined {
let notificationJSX: JSX.Element | undefined;
let notificationKind: NotificationKind;
let notificationSubtitle: string;
if (this.props.committedDefinitions.indexOf(`${this.state.definitionNameValue}@${this.state.definitionVersionValue}`) > -1) {
if (this.props.hasV1Capabilities) {
notificationKind = 'error';
notificationSubtitle = 'Please select a different smart contract to deploy.';
this.props.enableOrDisableNext(true);
} else {
notificationKind = 'info';
notificationSubtitle = 'We recommend changing the definition version to update the existing smart contract. Alternatively, provide a new name to deploy as a new definition.';
}
notificationJSX = (
<div className='bx--row margin-bottom-05'>
<div className='bx--col-lg-10'>
<InlineNotification
hideCloseButton={true}
kind={notificationKind}
lowContrast={true}
notificationType='inline'
role='alert'
statusIconDescription='describes the status icon'
subtitle={<p>{notificationSubtitle}</p>}
title='Name matches an existing smart contract'
className='deploy-step-two-notification'
/>
</div>
</div>
);
} else if (this.props.committedDefinitions.find((entry: string) => entry.includes(`${this.state.definitionNameValue}@`))) {
// If there exists an entry with a different version
if (this.props.hasV1Capabilities) {
notificationSubtitle = 'This deployment will upgrade the existing smart contract.';
this.props.enableOrDisableNext(false);
} else {
notificationSubtitle = 'This deployment will update the existing smart contract. Alternatively, provide a new name to deploy as a new definition.';
}
notificationJSX = (
<div className='bx--row margin-bottom-05'>
<div className='bx--col-lg-10'>
<InlineNotification
hideCloseButton={true}
kind='info'
lowContrast={true}
notificationType='inline'
role='alert'
statusIconDescription='describes the status icon'
subtitle={<p>{notificationSubtitle}</p>}
title='Name matches an existing smart contract'
className='deploy-step-two-notification'
/>
</div>
</div>
);
}
return notificationJSX;
}
renderNameAndDefinitionInputs(): JSX.Element {
let inputsJSX: JSX.Element = <></>;
const contractExists: JSX.Element | undefined = this.renderInlineNotification();
if (this.props.hasV1Capabilities) {
inputsJSX = contractExists as JSX.Element;
} else {
inputsJSX = (
<>
<div className='bx--row margin-bottom-06'>
<div className='bx--col-lg-10'>
A smart contract definition describes how the selected package will be deployed in this channel.
The package's name and version (where available) are copied across to the definition as defaults.
You may optionally change them.
</div>
</div>
<div className={'bx--row' + (contractExists ? ' margin-bottom-03' : ' margin-bottom-06')}>
<div className='bx--col-lg-11'>
<h5>Smart contract definition</h5>
</div>
<div className='bx--col-lg-11'>
<div className='bx--row'>
<div className='bx--col-lg-7 bx--col-md-3 bx--col-sm-4'>
<TextInput invalidText={`Name can only contain alphanumeric, '_' and '-' characters.`} invalid={this.nameInvalid} id='nameInput' labelText='Definition name' defaultValue={this.state.definitionNameValue} onChange={this.handleDefinitionNameChange}></TextInput>
</div>
<div className='bx--col-lg-2 bx--col-md-1 bx--col-sm-0'></div>
<div className='bx--col-lg-7 bx--col-md-3 bx--col-sm-4'>
<TextInput invalidText={'Version cannot be empty'} invalid={this.versionInvalid} id='versionInput' labelText='Definition version' defaultValue={this.state.definitionVersionValue} onChange={this.handleDefinitionVersionChange}></TextInput>
</div>
</div>
</div>
</div>
{contractExists}
</>
);
}
return inputsJSX;
}
render(): JSX.Element {
const defaultCollectionValue: string[] = this.state.collectionFile ? [this.state.collectionFile.name] : [];
let uploadedItem: JSX.Element = <></>;
if (defaultCollectionValue.length > 0) {
uploadedItem = (
<FileUploaderItem iconDescription='Remove file' name={defaultCollectionValue[0]} status='edit'></FileUploaderItem>
);
}
const cliLink: string = this.props.hasV1Capabilities ? 'https://hyperledger-fabric.readthedocs.io/en/release-1.4/command_ref.html' : 'https://hyperledger-fabric.readthedocs.io/en/release-2.0/chaincode_lifecycle.html';
return (
<>
{this.renderNameAndDefinitionInputs()}
<div className='bx--row margin-bottom-06'>
<div className='bx--col-lg-11'>
<div className='bx--row'>
<div className='bx--col-lg-7 bx--col-md-3 bx--col-sm-4'>
<TextInput id='endorsementInput' labelText='Endorsement policy' helperText='Default (/Channel/Application/Endorsement) policy will be used unless you specify your own.' placeholder='e.g. OR("Org1MSP.member","Org2MSP.member")' defaultValue={this.state.endorsementPolicy} onChange={this.handleEndorsementPolicyChange}></TextInput>
</div>
</div>
</div>
</div>
<div className='bx--row margin-bottom-06'>
<div className='bx--col-lg-11'>
<div className='bx--row'>
<div className='bx--col-lg-7 bx--col-md-3 bx--col-sm-4'>
<div className='bx--file__container'>
<FileUploader
defaultValue={defaultCollectionValue}
accept={[
'.json'
]}
buttonKind='tertiary'
buttonLabel='Add file'
iconDescription='Remove file'
labelDescription='Default (implicit private data collections only) will be used unless you add your own.'
labelTitle='Collections configuration'
size='default'
filenameStatus='edit'
onChange={this.handleCollectionChange}
/>
{uploadedItem}
</div>
</div>
</div>
</div>
</div>
<div className='bx--row'>
<div className='bx--col-lg-10'>
<Accordion>
<AccordionItem title={`Learn about other smart contract ${this.props.hasV1Capabilities ? '' : 'definition'} parameters (advanced)`}>
<p>
These developer tools automatically handle other parameters for simplified deployment. Learn what values are used in our <Link href='https://github.com/IBM-Blockchain/blockchain-vscode-extension'>documentation</Link>.
</p>
<p className='margin-bottom-05'>
Find out more information about the endorsement policy syntax <Link href='https://hyperledger-fabric.readthedocs.io/en/release-2.2/endorsement-policies.html#endorsement-policy-syntax'>here</Link>.
</p>
<p className='margin-bottom-05'>
To deploy with full control of all parameters, please use the <Link href='https://cloud.ibm.com/catalog/services/blockchain-platform'>IBM Blockchain Platform Console</Link> or <Link href={cliLink}>Hyperledger Fabric CLIs</Link>.
</p>
</AccordionItem>
</Accordion>
</div>
</div>
</>
);
}
}
export default DeployStepTwo; | the_stack |
import { flatbuffers } from "flatbuffers";
import * as NS7624605610262437867 from "./Schema";
export declare namespace org.apache.arrow.flatbuf {
export import Schema = NS7624605610262437867.org.apache.arrow.flatbuf.Schema;
}
/**
* ----------------------------------------------------------------------
* The root Message type
* This union enables us to easily send different message types without
* redundant storage, and in the future we can easily add new message types.
*
* Arrow implementations do not need to implement all of the message types,
* which may include experimental metadata types. For maximum compatibility,
* it is best to send data using RecordBatch
*
* @enum {number}
*/
export declare namespace org.apache.arrow.flatbuf {
enum MessageHeader {
NONE = 0,
Schema = 1,
DictionaryBatch = 2,
RecordBatch = 3,
Tensor = 4,
SparseTensor = 5
}
}
/**
* ----------------------------------------------------------------------
* Data structures for describing a table row batch (a collection of
* equal-length Arrow arrays)
* Metadata about a field at some level of a nested type tree (but not
* its children).
*
* For example, a List<Int16> with values [[1, 2, 3], null, [4], [5, 6], null]
* would have {length: 5, null_count: 2} for its List node, and {length: 6,
* null_count: 0} for its Int16 node, as separate FieldNode structs
*
* @constructor
*/
export declare namespace org.apache.arrow.flatbuf {
class FieldNode {
bb: flatbuffers.ByteBuffer | null;
bb_pos: number;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns FieldNode
*/
__init(i: number, bb: flatbuffers.ByteBuffer): FieldNode;
/**
* The number of value slots in the Arrow array at this level of a nested
* tree
*
* @returns flatbuffers.Long
*/
length(): flatbuffers.Long;
/**
* The number of observed nulls. Fields with null_count == 0 may choose not
* to write their physical validity bitmap out as a materialized buffer,
* instead setting the length of the bitmap buffer to 0.
*
* @returns flatbuffers.Long
*/
nullCount(): flatbuffers.Long;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long length
* @param flatbuffers.Long null_count
* @returns flatbuffers.Offset
*/
static createFieldNode(
builder: flatbuffers.Builder,
length: flatbuffers.Long,
null_count: flatbuffers.Long
): flatbuffers.Offset;
}
}
/**
* A data header describing the shared memory layout of a "record" or "row"
* batch. Some systems call this a "row batch" internally and others a "record
* batch".
*
* @constructor
*/
export declare namespace org.apache.arrow.flatbuf {
class RecordBatch {
bb: flatbuffers.ByteBuffer | null;
bb_pos: number;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns RecordBatch
*/
__init(i: number, bb: flatbuffers.ByteBuffer): RecordBatch;
/**
* @param flatbuffers.ByteBuffer bb
* @param RecordBatch= obj
* @returns RecordBatch
*/
static getRootAsRecordBatch(
bb: flatbuffers.ByteBuffer,
obj?: RecordBatch
): RecordBatch;
/**
* number of records / rows. The arrays in the batch should all have this
* length
*
* @returns flatbuffers.Long
*/
length(): flatbuffers.Long;
/**
* Nodes correspond to the pre-ordered flattened logical schema
*
* @param number index
* @param org.apache.arrow.flatbuf.FieldNode= obj
* @returns org.apache.arrow.flatbuf.FieldNode
*/
nodes(
index: number,
obj?: org.apache.arrow.flatbuf.FieldNode
): org.apache.arrow.flatbuf.FieldNode | null;
/**
* @returns number
*/
nodesLength(): number;
/**
* Buffers correspond to the pre-ordered flattened buffer tree
*
* The number of buffers appended to this list depends on the schema. For
* example, most primitive arrays will have 2 buffers, 1 for the validity
* bitmap and 1 for the values. For struct arrays, there will only be a
* single buffer for the validity (nulls) bitmap
*
* @param number index
* @param org.apache.arrow.flatbuf.Buffer= obj
* @returns org.apache.arrow.flatbuf.Buffer
*/
buffers(
index: number,
obj?: NS7624605610262437867.org.apache.arrow.flatbuf.Buffer
): NS7624605610262437867.org.apache.arrow.flatbuf.Buffer | null;
/**
* @returns number
*/
buffersLength(): number;
/**
* @param flatbuffers.Builder builder
*/
static startRecordBatch(builder: flatbuffers.Builder): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long length
*/
static addLength(
builder: flatbuffers.Builder,
length: flatbuffers.Long
): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset nodesOffset
*/
static addNodes(
builder: flatbuffers.Builder,
nodesOffset: flatbuffers.Offset
): void;
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startNodesVector(
builder: flatbuffers.Builder,
numElems: number
): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset buffersOffset
*/
static addBuffers(
builder: flatbuffers.Builder,
buffersOffset: flatbuffers.Offset
): void;
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startBuffersVector(
builder: flatbuffers.Builder,
numElems: number
): void;
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endRecordBatch(builder: flatbuffers.Builder): flatbuffers.Offset;
static createRecordBatch(
builder: flatbuffers.Builder,
length: flatbuffers.Long,
nodesOffset: flatbuffers.Offset,
buffersOffset: flatbuffers.Offset
): flatbuffers.Offset;
}
}
/**
* For sending dictionary encoding information. Any Field can be
* dictionary-encoded, but in this case none of its children may be
* dictionary-encoded.
* There is one vector / column per dictionary, but that vector / column
* may be spread across multiple dictionary batches by using the isDelta
* flag
*
* @constructor
*/
export declare namespace org.apache.arrow.flatbuf {
class DictionaryBatch {
bb: flatbuffers.ByteBuffer | null;
bb_pos: number;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns DictionaryBatch
*/
__init(i: number, bb: flatbuffers.ByteBuffer): DictionaryBatch;
/**
* @param flatbuffers.ByteBuffer bb
* @param DictionaryBatch= obj
* @returns DictionaryBatch
*/
static getRootAsDictionaryBatch(
bb: flatbuffers.ByteBuffer,
obj?: DictionaryBatch
): DictionaryBatch;
/**
* @returns flatbuffers.Long
*/
id(): flatbuffers.Long;
/**
* @param org.apache.arrow.flatbuf.RecordBatch= obj
* @returns org.apache.arrow.flatbuf.RecordBatch|null
*/
data(
obj?: org.apache.arrow.flatbuf.RecordBatch
): org.apache.arrow.flatbuf.RecordBatch | null;
/**
* If isDelta is true the values in the dictionary are to be appended to a
* dictionary with the indicated id
*
* @returns boolean
*/
isDelta(): boolean;
/**
* @param flatbuffers.Builder builder
*/
static startDictionaryBatch(builder: flatbuffers.Builder): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long id
*/
static addId(builder: flatbuffers.Builder, id: flatbuffers.Long): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset dataOffset
*/
static addData(
builder: flatbuffers.Builder,
dataOffset: flatbuffers.Offset
): void;
/**
* @param flatbuffers.Builder builder
* @param boolean isDelta
*/
static addIsDelta(builder: flatbuffers.Builder, isDelta: boolean): void;
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endDictionaryBatch(
builder: flatbuffers.Builder
): flatbuffers.Offset;
static createDictionaryBatch(
builder: flatbuffers.Builder,
id: flatbuffers.Long,
dataOffset: flatbuffers.Offset,
isDelta: boolean
): flatbuffers.Offset;
}
}
/**
* @constructor
*/
export declare namespace org.apache.arrow.flatbuf {
class Message {
bb: flatbuffers.ByteBuffer | null;
bb_pos: number;
/**
* @param number i
* @param flatbuffers.ByteBuffer bb
* @returns Message
*/
__init(i: number, bb: flatbuffers.ByteBuffer): Message;
/**
* @param flatbuffers.ByteBuffer bb
* @param Message= obj
* @returns Message
*/
static getRootAsMessage(
bb: flatbuffers.ByteBuffer,
obj?: Message
): Message;
/**
* @returns org.apache.arrow.flatbuf.MetadataVersion
*/
version(): NS7624605610262437867.org.apache.arrow.flatbuf.MetadataVersion;
/**
* @returns org.apache.arrow.flatbuf.MessageHeader
*/
headerType(): org.apache.arrow.flatbuf.MessageHeader;
/**
* @param flatbuffers.Table obj
* @returns ?flatbuffers.Table
*/
header<T extends flatbuffers.Table>(obj: T): T | null;
/**
* @returns flatbuffers.Long
*/
bodyLength(): flatbuffers.Long;
/**
* @param number index
* @param org.apache.arrow.flatbuf.KeyValue= obj
* @returns org.apache.arrow.flatbuf.KeyValue
*/
customMetadata(
index: number,
obj?: NS7624605610262437867.org.apache.arrow.flatbuf.KeyValue
): NS7624605610262437867.org.apache.arrow.flatbuf.KeyValue | null;
/**
* @returns number
*/
customMetadataLength(): number;
/**
* @param flatbuffers.Builder builder
*/
static startMessage(builder: flatbuffers.Builder): void;
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.MetadataVersion version
*/
static addVersion(
builder: flatbuffers.Builder,
version: NS7624605610262437867.org.apache.arrow.flatbuf.MetadataVersion
): void;
/**
* @param flatbuffers.Builder builder
* @param org.apache.arrow.flatbuf.MessageHeader headerType
*/
static addHeaderType(
builder: flatbuffers.Builder,
headerType: org.apache.arrow.flatbuf.MessageHeader
): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset headerOffset
*/
static addHeader(
builder: flatbuffers.Builder,
headerOffset: flatbuffers.Offset
): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Long bodyLength
*/
static addBodyLength(
builder: flatbuffers.Builder,
bodyLength: flatbuffers.Long
): void;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset customMetadataOffset
*/
static addCustomMetadata(
builder: flatbuffers.Builder,
customMetadataOffset: flatbuffers.Offset
): void;
/**
* @param flatbuffers.Builder builder
* @param Array.<flatbuffers.Offset> data
* @returns flatbuffers.Offset
*/
static createCustomMetadataVector(
builder: flatbuffers.Builder,
data: flatbuffers.Offset[]
): flatbuffers.Offset;
/**
* @param flatbuffers.Builder builder
* @param number numElems
*/
static startCustomMetadataVector(
builder: flatbuffers.Builder,
numElems: number
): void;
/**
* @param flatbuffers.Builder builder
* @returns flatbuffers.Offset
*/
static endMessage(builder: flatbuffers.Builder): flatbuffers.Offset;
/**
* @param flatbuffers.Builder builder
* @param flatbuffers.Offset offset
*/
static finishMessageBuffer(
builder: flatbuffers.Builder,
offset: flatbuffers.Offset
): void;
static createMessage(
builder: flatbuffers.Builder,
version: NS7624605610262437867.org.apache.arrow.flatbuf.MetadataVersion,
headerType: org.apache.arrow.flatbuf.MessageHeader,
headerOffset: flatbuffers.Offset,
bodyLength: flatbuffers.Long,
customMetadataOffset: flatbuffers.Offset
): flatbuffers.Offset;
}
} | the_stack |
import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { GridOptions } from 'ag-grid';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';
import { DataCacheService } from '../../../../core/services/data-cache.service';
import { CommonResponseService } from '../../../../shared/services/common-response.service';
import { AssetGroupObservableService } from '../../../../core/services/asset-group-observable.service';
import { WorkflowService } from '../../../../core/services/workflow.service';
import { environment } from '../../../../../environments/environment';
import { RefactorFieldsService } from '../../../../shared/services/refactor-fields.service';
import { LoggerService } from '../../../../shared/services/logger.service';
import { UtilsService } from '../../../../shared/services/utils.service';
@Component({
selector: 'app-onprem-assets',
templateUrl: './onprem-assets.component.html',
styleUrls: ['./onprem-assets.component.css'],
providers: [ CommonResponseService]
})
export class OnpremAssetsComponent implements OnInit, OnDestroy {
@Input() pageLevel = 0;
private subscriptionToAssetGroup: Subscription;
private targetSubscription: Subscription;
private updateSubscription: Subscription;
private dataSubscription: Subscription;
private gridOptions: GridOptions;
public backButtonRequired;
pageTitle = 'Update Asset Data';
breadcrumbArray: any = ['Assets'];
breadcrumbLinks: any = ['asset-dashboard'];
breadcrumbPresent: any;
getContextMenuItems: any;
gridApi: any;
gridColumnApi: any;
selectedAssetGroup = '';
urlToRedirect = '';
targetTypeSelected = '';
savedTarget = '';
userName = 'Hi Guest';
showTargets = true;
showSidebar = false;
errorTabValue = -2;
errorValue = 0;
carouselState = 0;
updateState = 0;
paginatorSize = 3000;
bucketNumber = 0;
currentTotal = -1;
activeIndex = -1;
identifier: any = '';
rowSelectData: any = [];
ObjArr: any = [];
targetTiles: any = [];
editableFields: any = [];
cbModel: any = [];
ipModel: any = [];
updateColData: any = [];
currentData: any = [];
selectFields: any = [];
selObj: any = {};
updatePayload: any = {};
activeRadio = '';
filterValues: any = [{id: 1, text: '1'},
{id: 2, text: '2'},
{id: 3, text: '3'},
{id: 4, text: '4'},
{id: 5, text: '5'},
{id: 6, text: '6'},
{id: 7, text: '7'},
{id: 8, text: '8'},
{id: 9, text: '9'},
{id: 10, text: '10'},
{id: 11, text: '11'},
{id: 12, text: '12'},
{id: 13, text: '13'}
];
constructor(
private router: Router,
private assetGroupObservableService: AssetGroupObservableService,
private dataStore: DataCacheService,
private workflowService: WorkflowService,
private commonResponseService: CommonResponseService,
private logger: LoggerService,
private refactorFieldsService: RefactorFieldsService,
private utils: UtilsService) {
this.gridOptions = <GridOptions>{};
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel);
this.selectedAssetGroup = assetGroupName;
this.getTargetTypes();
});
this.gridOptions.columnDefs = [];
this.gridOptions.rowData = [];
this.getContextMenuItems = function getContextMenuItems(params) {
const result = [
'toolPanel',
'separator',
'copy',
'separator',
'csvExport',
'separator',
'autoSizeAll',
'resetColumns'
];
return result;
};
}
ngOnInit() {
this.breadcrumbPresent = 'Update Asset Data';
this.urlToRedirect = this.router.routerState.snapshot.url;
}
resetPage() {
this.showSidebar = false;
this.gridOptions.columnDefs = [];
this.gridOptions.rowData = [];
this.rowSelectData = [];
this.errorTabValue = -2;
this.identifier = '';
this.editableFields = [];
this.activeRadio = '';
this.ObjArr = [];
this.cbModel = [];
this.ipModel = [];
this.updateColData = [];
this.currentTotal = 0;
this.currentData = [];
this.bucketNumber = 0;
this.carouselState = 0;
this.updateState = 0;
this.updatePayload = {};
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
if (this.gridOptions.api) {
this.gridOptions.api.setColumnDefs(this.gridOptions.columnDefs);
this.gridOptions.api.setRowData(this.gridOptions.rowData);
}
}
onRowSelected() {
this.rowSelectData = this.gridOptions.api.getSelectedRows();
if (this.rowSelectData.length === 0) {
this.showSidebar = false;
}
}
onFilterChanged() {
// Remove selected row on filter change so user will have to select rows which he wants to update again.
this.gridOptions.api.deselectAll();
}
downloadCsv() {
this.gridApi.exportDataAsCsv();
}
getTargetTypes() {
if (this.targetSubscription) {
this.targetSubscription.unsubscribe();
}
const payload = {};
const queryParam = {
'ag': this.selectedAssetGroup
};
this.targetTypeSelected = '';
this.savedTarget = '';
this.errorValue = 0;
this.targetTiles = [];
this.showTargets = true;
this.resetPage();
const url = environment.resourceCount.url;
const method = environment.resourceCount.method;
this.targetSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
this.errorValue = 1;
if (response.assetcount.length === 0 ) {
this.errorValue = -1;
}
this.targetTiles = response.assetcount;
} catch (e) {
this.errorValue = -1;
this.logger.log('error', e);
}
},
error => {
this.errorValue = -1;
});
}
getTableData() {
this.resetPage();
if (this.targetTypeSelected) {
this.showTargets = false;
this.savedTarget = this.targetTypeSelected;
}
this.getData();
}
getData() {
if (this.savedTarget) {
const payload = {
'ag': this.selectedAssetGroup,
'filter': {'resourceType': this.savedTarget},
'targetType': this.savedTarget,
'from': this.bucketNumber * this.paginatorSize,
'searchtext': '',
'size': this.paginatorSize
};
const queryParam = {};
this.errorTabValue = 0;
const url = environment.onpremData.url;
const method = environment.onpremData.method;
this.dataSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
if ( response.data.response.length === 0 && this.currentData.length === 0 ) {
this.errorTabValue = -3;
} else {
this.identifier = response.data.identifier.key;
this.editableFields = [];
const editableKeys = Object.keys(response.data.editableFields);
for (let x = 0; x < editableKeys.length; x++) {
const pushObj = {
key: editableKeys[x],
displayName: this.refactorFieldsService.getDisplayNameForAKey(editableKeys[x].toLowerCase()) || editableKeys[x],
type: response.data.editableFields[editableKeys[x]]
};
this.editableFields.push(pushObj);
}
this.currentTotal = response.data.total;
const dataResponse = response.data.response;
for (let i = 0; i < dataResponse.length; i++) {
this.currentData.push(dataResponse[i]);
}
if (this.paginatorSize === 0 && this.bucketNumber === 0) {
this.errorTabValue = 1;
this.processData(this.currentData);
} else {
this.bucketNumber++;
if ( (this.bucketNumber * this.paginatorSize) < this.currentTotal ) {
this.getData();
} else {
this.errorTabValue = 1;
this.processData(this.currentData);
}
}
}
} catch (e) {
this.errorTabValue = -1;
this.logger.log('error', e);
}
},
error => {
if (this.currentData.length === 0) {
this.errorTabValue = -1;
} else {
this.errorTabValue = 1;
this.processData(this.currentData);
}
this.logger.log('error', error);
});
}
}
openTargets() {
if (this.savedTarget) {
this.targetTypeSelected = this.savedTarget;
}
this.showTargets = true;
}
updateCols() {
try {
if (this.rowSelectData.length > 0) {
this.showSidebar = true;
}
this.selectFields = [];
for (let x = 0; x < this.editableFields.length; x++) {
if (this.editableFields[x].key.toLowerCase() === 'u_projection_week') {
this.selObj = {
type: 'weekDropdown',
values: this.filterValues,
placeholder: 'Select Projection Week'
};
} else if (this.editableFields[x].type.toLowerCase() === 'boolean') {
this.selObj = {
type: 'radio',
values: ['true', 'false'],
placeholder: ''
};
} else {
this.selObj = {
type: 'textField',
values: [],
placeholder: ''
};
}
this.selectFields.push(this.selObj);
}
} catch (e) {
this.logger.log('error', e);
}
}
processData(data) {
try {
this.gridOptions.rowData = data;
let currentObj = {};
for (let x = 0 ; x < data.length ; x++ ) {
currentObj = Object.assign(currentObj, data[x]);
}
const ObjArr = Object.keys(currentObj);
this.ObjArr = ObjArr;
const extraFeatures = {
checkboxSelection: true,
pinned: 'left',
lockPosition: true,
headerCheckboxSelection: true,
headerCheckboxSelectionFilteredOnly: true,
maxWidth: 400,
minWidth: 210
};
for (let i = 0; i < ObjArr.length; i++) {
let eachObj = {
field: ObjArr[i],
headerName: this.refactorFieldsService.getDisplayNameForAKey(ObjArr[i]),
minWidth: 160,
maxWidth: 800,
filterParams: { selectAllOnMiniFilter: true }
};
if (ObjArr[i] === this.identifier) {
eachObj = Object.assign(eachObj, extraFeatures);
}
this.gridOptions.columnDefs.push(eachObj);
}
this.gridOptions.api.setColumnDefs(this.gridOptions.columnDefs);
this.gridOptions.api.setRowData(data);
this.onresize();
} catch (e) {
this.logger.log('error', e);
}
}
updateColSave() {
try {
this.updateColData = [];
for (let k = 0; k < this.editableFields.length; k++ ) {
if (this.cbModel[k]) {
if (this.ipModel[k] === undefined ) {
this.ipModel[k] = '';
}
const obj = {
'key': this.editableFields[k].key,
'value': this.ipModel[k]
};
this.updateColData.push(obj);
}
}
let userId;
if (this.updateColData.length > 0) {
if (this.dataStore.get('currentUserLoginDetails')) {
userId = (this.dataStore.getUserDetailsValue().getUserId());
}
const rawPayload = {
'ag': this.selectedAssetGroup,
'targettype': this.savedTarget,
'update_by': userId,
'resources': {
'key': '',
'values': []
},
'updates': []
};
for (let i = 0; i < this.rowSelectData.length; i++) {
const identifier = this.identifier;
const value = this.rowSelectData[i][this.identifier];
rawPayload.resources.key = identifier;
rawPayload.resources.values.push(value);
}
for (let j = 0; j < this.updateColData.length; j++) {
const keyValObj = {
'key': this.updateColData[j].key,
'value': this.updateColData[j].value
};
rawPayload.updates.push(keyValObj);
}
this.carouselState++;
this.updatePayload = rawPayload;
}
} catch (e) {
this.logger.log('error', e);
}
}
updateTable() {
if (this.updateSubscription) {
this.updateSubscription.unsubscribe();
}
this.carouselState++;
this.updateState = 0;
const url = environment.onpremDataUpdate.url;
const method = environment.onpremDataUpdate.method;
const payload = this.updatePayload;
this.updateSubscription = this.commonResponseService.getData(url, method, payload, {}).subscribe(
response => {
try {
this.updateState = 1;
this.cbModel = [];
this.ipModel = [];
this.errorTabValue = 0;
this.bucketNumber = 0;
this.updateColData = [];
this.currentTotal = 0;
this.gridOptions.columnDefs = [];
this.gridOptions.rowData = [];
this.currentData = [];
this.updatePayload = {};
this.utils.clickClearDropdown();
setTimeout(() => {
this.showSidebar = false;
this.onFilterChanged();
this.rowSelectData = [];
this.carouselState = 0;
}, 2000);
this.getData();
} catch (e) {
this.updateState = -1;
this.logger.log('error', e);
}
},
error => {
this.updateState = -1;
});
}
closeUpdateSidebar() {
if (this.updateState === 1 ) {
this.onFilterChanged();
}
}
changeFilterTags(data, i) {
this.ipModel[i] = parseInt(data.text, 10);
if (data.text === undefined) {
this.ipModel[i] = '';
}
}
verifyIfChecked() {
let flag = false;
for (let i = 0; i < this.cbModel.length; i++ ) {
if (this.cbModel[i]) {
flag = true;
break;
}
}
if (flag) {
return false;
} else {
return true;
}
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
}
autoSizeAll() {
const allColumnIds = [];
this.gridColumnApi.getAllColumns().forEach(function(column) {
allColumnIds.push(column.colId);
});
this.gridColumnApi.autoSizeColumns(allColumnIds);
}
onresize() {
if (this.ObjArr.length < 6 && this.ObjArr.length > 0) {
this.gridApi.sizeColumnsToFit();
} else {
this.autoSizeAll();
}
}
setRadioInput(val, index) {
if (val === 'true') {
this.ipModel[index] = true;
} else if (val === 'false') {
this.ipModel[index] = false;
} else if (val === undefined) {
this.ipModel[index] = '';
} else {
this.ipModel[index] = val;
}
}
typeof(val) {
return typeof(val);
}
checkboxClicked(obj, i) {
if (obj.type === 'boolean' && this.activeRadio === '') {
this.activeRadio = 'true';
this.ipModel[i] = true;
}
}
ngOnDestroy() {
if (this.subscriptionToAssetGroup) {
this.subscriptionToAssetGroup.unsubscribe();
}
if (this.targetSubscription) {
this.targetSubscription.unsubscribe();
}
if (this.updateSubscription) {
this.updateSubscription.unsubscribe();
}
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
}
} | the_stack |
import * as child_process from 'child_process';
import { expect } from 'chai';
import * as Databench from '.';
import * as https from 'https';
import * as request from 'request';
describe('Standalone Process', () => {
let databench_process_return_code = -42;
const databench_process = child_process.spawn('python', [
'databench/tests/standalone/test_standalone.py',
'--log', 'WARNING',
'--coverage', '.coverage.js.standalone',
'--port', '5002',
'--ssl-port', '5003',
'--some-test-flag',
]);
databench_process.stdout.on('data', data => console.log('databench stdout: ' + data));
databench_process.stderr.on('data', data => console.log('databench stderr: ' + data));
databench_process.on('exit', code => {
databench_process_return_code = code;
console.log('databench process exited with code ' + code);
});
before(done => {
setTimeout(() => {
expect(databench_process_return_code).to.equal(-42);
done();
}, 2000);
});
after(done => {
setTimeout(() => {
databench_process.kill('SIGINT');
done();
}, 2000);
});
describe('App test', () => {
it('has a working page', done => {
request.get('http://localhost:5002', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('can serve a custom static location', done => {
request.get('http://localhost:5002/special/analysis.js', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('serves all files from the same directory', done => {
request.get('http://localhost:5002/analysis.js', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
});
});
describe('Server Process', () => {
let databench_process_return_code = -42;
const databench_process = child_process.spawn('databench', [
'--log', 'WARNING',
'--analyses', 'databench.tests.analyses',
'--coverage', '.coverage.js',
'--ssl-port', '5001',
'--some-test-flag',
]);
databench_process.stdout.on('data', data => console.log('databench stdout: ' + data));
databench_process.stderr.on('data', data => console.log('databench stderr: ' + data));
databench_process.on('exit', code => {
databench_process_return_code = code;
console.log('databench process exited with code ' + code);
});
before(done => {
setTimeout(() => {
expect(databench_process_return_code).to.equal(-42);
done();
}, 2000);
});
after(done => {
setTimeout(() => {
databench_process.kill('SIGINT');
done();
}, 2000);
});
describe('App test', () => {
it('has a working index page', done => {
request.get('http://localhost:5000', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('responds to HEAD requests for index page', done => {
request.head('http://localhost:5000', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('has a working analysis page', done => {
request.get('http://localhost:5000/parameters/', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('responds to HEAD requests for an analysis page', done => {
request.head('http://localhost:5000/parameters/', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('has a working index page with SSL', done => {
request.get({url: 'https://localhost:5001', rejectUnauthorized: false}, (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('has an invalid SSL certificate', done => {
request.get('https://localhost:5001', (error, response, body) => {
expect(error.code).to.equal('DEPTH_ZERO_SELF_SIGNED_CERT');
done();
});
});
it('can access the static folder', done => {
request.get('http://localhost:5000/static/test_file.txt', (error, response, body) => {
expect(response.statusCode).to.equal(200);
expect(body).to.contain('placeholder');
done();
});
});
it('can access the node_modules folder', done => {
request.get('http://localhost:5000/node_modules/test_file.txt', (error, response, body) => {
expect(response.statusCode).to.equal(200);
expect(body).to.contain('placeholder');
done();
});
});
});
describe('Routes Tests', () => {
it('creates good routes for GET', done => {
request.get('http://localhost:5000/simple2/get', (error, response, body) => {
expect(response.statusCode).to.equal(200);
done();
});
});
it('creates good routes for POST', done => {
request.post({url: 'http://localhost:5000/simple2/post', form: {data: 'test data'}}, (error, response, body) => {
expect(response.statusCode).to.equal(200);
expect(body).to.equal('test data');
done();
});
});
});
describe('Echo Tests', () => {
let c = new Databench.Connection();
beforeEach(() => { c.disconnect(); c = Databench.connect('ws://localhost:5000/parameters/ws'); });
after(() => c.disconnect());
it('creates a WebSocket connection', () => {
expect(typeof c).to.equal('object');
});
it('sends an action without message', (done) => {
c.on('test_action_ack', () => done());
c.emit('test_action');
});
it('echos an object', done => {
c.on('test_fn', data => {
expect(data).to.deep.equal([1, 2]);
done();
});
c.emit('test_fn', [1, 2]);
});
it('echos an empty string', done => {
c.on('test_fn', dataEmpty => {
expect(dataEmpty).to.deep.equal(['', 100]);
done();
});
c.emit('test_fn', '');
});
it('echos a null parameter', done => {
c.on('test_fn', dataNull => {
expect(dataNull).to.deep.equal([null, 100]);
done();
});
c.emit('test_fn', null);
});
});
describe('Command Line and Request Arguments', () => {
describe('empty request args', () => {
const c = new Databench.Connection('ws://localhost:5000/requestargs/ws');
after(() => c.disconnect());
it('valid empty request args', done => {
c.on('echo_request_args', request_args => {
expect(request_args).to.deep.equal({});
done();
});
c.connect();
});
});
describe('simple request args', () => {
const c = new Databench.Connection('ws://localhost:5000/requestargs/ws', '?data=requestargtest');
after(() => c.disconnect());
it('can access request args', done => {
c.on('echo_request_args', request_args => {
expect(request_args).to.deep.equal({ data: ['requestargtest'] });
done();
});
c.connect();
});
});
describe('simple cli args', () => {
const c = new Databench.Connection('ws://localhost:5000/cliargs/ws');
after(() => c.disconnect());
it('can access cli args', done => {
c.on({ data: 'cli_args' }, args => {
expect(args).to.deep.equal(['--some-test-flag']);
done();
});
c.connect();
});
});
});
describe('Cycle Connection', () => {
let c = new Databench.Connection();
before(() => { c = Databench.connect('ws://localhost:5000/requestargs/ws'); });
after(() => c.disconnect());
it('reconnects after disconnect', done => {
c.disconnect();
c.on('echo_request_args', () => done());
c.connect();
});
});
describe('Connection Interruption', () => {
it('keeps analysis id', async () => {
const client1 = await Databench.attach('ws://localhost:5000/connection_interruption/ws');
const id1 = client1.analysisId;
client1.disconnect();
expect(id1).to.have.length(8);
const client2 = await Databench.attach('ws://localhost:5000/connection_interruption/ws', undefined, id1);
const id2 = client2.analysisId;
client2.disconnect();
expect(id2).to.equal(id1);
});
});
describe('Analysis Test', () => {
let c: Databench.Connection = new Databench.Connection();
beforeEach(() => { c.disconnect(); c = new Databench.Connection(); });
after(() => c.disconnect());
it('can open a connection without connecting', done => {
c.preEmit('test', message => done());
c.emit('test');
});
it('can emulate an empty backend response', done => {
c.on('received', message => done());
c.preEmit('test', message => c.trigger('received'));
c.emit('test');
});
it('can emulate a string backend response', () => {
c.on('received', message => {
expect(message).to.equal('test message');
});
c.preEmit('test', message => c.trigger('received', 'test message'));
c.emit('test');
});
});
['parameters', 'parameters_py'].forEach(analysis => {
describe(`Parameter Tests for ${analysis}`, () => {
let databench = new Databench.Connection();
beforeEach(() => { databench.disconnect(); databench = Databench.connect(`ws://localhost:5000/${analysis}/ws`); });
after(() => databench.disconnect());
it('calls an action without parameter', done => {
databench.on('test_action_ack', () => done());
databench.emit('test_action');
});
it('calls an action with an empty string', done => {
databench.on('test_fn', data => {
expect(data).to.deep.equal(['', 100]);
done();
});
databench.emit('test_fn', '');
});
it('calls an action with a single int', done => {
databench.on('test_fn', data => {
expect(data).to.deep.equal([1, 100]);
done();
});
databench.emit('test_fn', 1);
});
it('calls an action with a list', done => {
databench.on('test_fn', data => {
expect(data).to.deep.equal([1, 2]);
done();
});
databench.emit('test_fn', [1, 2]);
});
it('calls an action with a dictionary', done => {
databench.on('test_fn', data => {
expect(data).to.deep.equal([1, 2]);
done();
});
databench.emit('test_fn', {first_param: 1, second_param: 2});
});
it('calls an action that sets state', done => {
databench.on({data: 'light'}, data => {
expect(data).to.equal('red');
done();
});
databench.emit('test_state', ['light', 'red']);
});
it('calls an action that sets state', done => {
databench.on({data: 'light'}, data => {
expect(data).to.equal('red');
done();
});
databench.emit('test_set_data', ['light', 'red']);
});
it('calls an action that sets class data', done => {
databench.on({class_data: 'light'}, data => {
expect(data).to.equal('red');
done();
});
databench.emit('test_class_data', ['light', 'red']);
});
it('calls an action that well emit process states', done => {
databench.on('test_fn', data => expect(data).to.deep.equal([1, 100]));
databench.onProcess(123, data => {
expect(data).to.be.oneOf(['start', 'end']);
if (data === 'end') done();
});
databench.emit('test_fn', {first_param: 1, __process_id: 123});
});
it('creates multiple connections', async () => {
const connections = await Promise.all([1, 2, 3, 4].map(
() => Databench.attach(`ws://localhost:5000/${analysis}/ws`)));
// connection established, now check analysis id
connections.forEach(connection => expect(connection.analysisId).to.have.length(8));
// listen for responses
const responses = connections.map(connection => connection.once('test_action_ack'));
// execute an actions that will trigger a responses
connections.forEach(connection => connection.emit('test_action'));
await Promise.all(responses);
connections.forEach(connection => connection.disconnect());
});
});
});
}); | the_stack |
import { expect, test } from '@jest/globals';
import { pack } from '../src/reflection/processor';
import { copyAndSetParent, ParentLessType, ReflectionKind, ReflectionVisibility, TypeObjectLiteral, TypePropertySignature, TypeUnion } from '../src/reflection/type';
import { MappedModifier, ReflectionOp } from '@deepkit/type-spec';
import { isExtendable } from '../src/reflection/extends';
import { assertValidParent, expectEqualType, expectType } from './utils';
Error.stackTraceLimit = 200;
test('assertEqualType 1', () => {
expectEqualType({ kind: ReflectionKind.string }, { kind: ReflectionKind.string });
expectEqualType({ kind: ReflectionKind.number }, { kind: ReflectionKind.number });
expectEqualType({ kind: ReflectionKind.literal, literal: 'asd' }, { kind: ReflectionKind.literal, literal: 'asd' });
expect(() => expectEqualType({ kind: ReflectionKind.literal, literal: 'asd' }, {
kind: ReflectionKind.literal,
literal: 'asd2'
})).toThrow('Invalid type .literal: asd !== asd2');
const a: ParentLessType = { kind: ReflectionKind.tuple, types: [{ kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.string } }] };
expectEqualType(a, a);
expect(() => expectEqualType(a, {
kind: ReflectionKind.tuple,
types: [{ kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.number } }]
})).toThrow('Invalid type .types.0.type.kind: 5 !== 6');
const b: ParentLessType = {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'b', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.never }
};
expectEqualType(b, b);
expect(() => expectEqualType(b, {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'c', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.never }
})).toThrow('Invalid type .parameters.0.name');
expect(() => expectEqualType(b, {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'b', type: { kind: ReflectionKind.number } }],
return: { kind: ReflectionKind.never }
})).toThrow('Invalid type .parameters.0.type.kind');
expect(() => expectEqualType(b, {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'b', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.number }
})).toThrow('Invalid type .return.kind');
});
test('assertEqualType 2', () => {
assertValidParent({ kind: ReflectionKind.string });
assertValidParent({ kind: ReflectionKind.literal, literal: 'asd' });
assertValidParent(copyAndSetParent({ kind: ReflectionKind.literal, literal: 'asd' }));
expect(() => assertValidParent({ kind: ReflectionKind.literal, literal: 'asd', parent: Object as any })).toThrow('Parent was set, but not expected at');
});
enum MyEnum {
first, second, third
}
test('simple', () => {
expectType([ReflectionOp.string], { kind: ReflectionKind.string });
expectType([ReflectionOp.string, ReflectionOp.number], { kind: ReflectionKind.number });
});
test('query', () => {
expectType({ ops: [ReflectionOp.number, ReflectionOp.propertySignature, 0, ReflectionOp.objectLiteral, ReflectionOp.literal, 0, ReflectionOp.indexAccess], stack: ['a'] }, {
kind: ReflectionKind.number
});
});
test('inline', () => {
const external = pack([ReflectionOp.string]);
expectType({ ops: [ReflectionOp.inline, 0], stack: [external] }, { kind: ReflectionKind.string });
});
test('extends primitive', () => {
expectType({ ops: [ReflectionOp.number, ReflectionOp.number, ReflectionOp.extends], stack: [] }, { kind: ReflectionKind.literal, literal: true });
// expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.number, ReflectionOp.extends], stack: [1] }, true);
// expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.number, ReflectionOp.extends], stack: ['asd'] }, false);
expectType({ ops: [ReflectionOp.string, ReflectionOp.number, ReflectionOp.extends], stack: [] }, { kind: ReflectionKind.literal, literal: false });
expectType({ ops: [ReflectionOp.string, ReflectionOp.string, ReflectionOp.extends], stack: [] }, { kind: ReflectionKind.literal, literal: true });
// expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.string, ReflectionOp.extends], stack: ['asd'] }, true);
expect(isExtendable({ kind: ReflectionKind.boolean }, { kind: ReflectionKind.boolean })).toBe(true);
expect(isExtendable({ kind: ReflectionKind.literal, literal: true }, { kind: ReflectionKind.boolean })).toBe(true);
});
test('extends fn', () => {
expect(isExtendable(
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.boolean }, parameters: [] },
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.boolean }, parameters: [] }
)).toBe(true);
expect(isExtendable(
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.string }, parameters: [] },
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.boolean }, parameters: [] }
)).toBe(false);
expect(isExtendable(
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.literal, literal: true }, parameters: [] },
{ kind: ReflectionKind.function, return: { kind: ReflectionKind.boolean }, parameters: [] }
)).toBe(true);
});
test('arg', () => {
//after initial stack, an implicit frame is created. arg references always relative to the current frame.
expectType({ ops: [ReflectionOp.arg, 0], stack: [{ kind: ReflectionKind.literal, literal: 'a' }] }, { kind: ReflectionKind.literal, literal: 'a' });
// expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.arg, 0], stack: ['a'] }, 'a');
//frame is started automatically when a sub routine is called, but we do it here manually to make sure arg works correctly
// expectType({ ops: [ReflectionOp.arg, 1, ReflectionOp.arg, 0, ReflectionOp.frame, ReflectionOp.arg, 0], stack: ['a', 'b'] }, 'a');
// expectType({ ops: [ReflectionOp.arg, 1, ReflectionOp.arg, 0, ReflectionOp.frame, ReflectionOp.arg, 1], stack: ['a', 'b'] }, 'b');
// expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.arg, 0, ReflectionOp.frame, ReflectionOp.arg, 1], stack: ['a', 'b'] }, 'a');
});
test('call sub routine', () => {
expectType({ ops: [ReflectionOp.jump, 4, ReflectionOp.string, ReflectionOp.return, ReflectionOp.call, 2], stack: [] }, { kind: ReflectionKind.string });
expectType({ ops: [ReflectionOp.jump, 5, ReflectionOp.string, ReflectionOp.number, ReflectionOp.return, ReflectionOp.call, 2], stack: [] }, { kind: ReflectionKind.number });
expectType({
ops: [ReflectionOp.jump, 5, ReflectionOp.string, ReflectionOp.number, ReflectionOp.return, ReflectionOp.boolean, ReflectionOp.call, 2, ReflectionOp.union],
stack: []
}, {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.boolean }, { kind: ReflectionKind.number }], //not string, since `return` returns only latest stack entry, not all
});
expectType({
ops: [ReflectionOp.jump, 5, ReflectionOp.string, ReflectionOp.number, ReflectionOp.return, ReflectionOp.call, 2, ReflectionOp.undefined, ReflectionOp.union],
stack: []
}, {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }],
});
expectType({
ops: [ReflectionOp.string, ReflectionOp.jump, 6, ReflectionOp.string, ReflectionOp.number, ReflectionOp.return, ReflectionOp.call, 2, ReflectionOp.undefined, ReflectionOp.union],
stack: []
}, {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }],
});
});
test('type argument', () => {
//type A<T> = T extends string;
expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.arg, 0, ReflectionOp.string, ReflectionOp.extends], stack: ['a'] }, { kind: ReflectionKind.literal, literal: true });
});
test('conditional', () => {
//1 ? string : number
expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.string, ReflectionOp.number, ReflectionOp.condition], stack: [1] }, {
kind: ReflectionKind.string
});
//0 ? string : number
expectType({ ops: [ReflectionOp.arg, 0, ReflectionOp.string, ReflectionOp.number, ReflectionOp.condition], stack: [0] }, {
kind: ReflectionKind.number
});
});
test('jump conditional', () => {
//1 ? string : number
expectType({
ops: [ReflectionOp.jump, 6, ReflectionOp.string, ReflectionOp.return, ReflectionOp.number, ReflectionOp.return, ReflectionOp.arg, 0, ReflectionOp.jumpCondition, 2, 4],
stack: [1]
}, {
kind: ReflectionKind.string
});
//0 ? string : number
expectType({
ops: [ReflectionOp.jump, 6, ReflectionOp.string, ReflectionOp.return, ReflectionOp.number, ReflectionOp.return, ReflectionOp.arg, 0, ReflectionOp.jumpCondition, 2, 4],
stack: [0]
}, {
kind: ReflectionKind.number
});
//(0 ? string : number) | undefined
expectType({
ops: [ReflectionOp.jump, 6, ReflectionOp.string, ReflectionOp.return, ReflectionOp.number, ReflectionOp.return, ReflectionOp.arg, 0, ReflectionOp.jumpCondition, 2, 4, ReflectionOp.undefined, ReflectionOp.union],
stack: [0]
}, {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }]
});
});
test('object literal', () => {
expectType({
ops: [ReflectionOp.number, ReflectionOp.propertySignature, 0, ReflectionOp.string, ReflectionOp.propertySignature, 1, ReflectionOp.objectLiteral],
stack: ['a', 'b']
}, {
kind: ReflectionKind.objectLiteral,
types: [
{ kind: ReflectionKind.propertySignature, type: { kind: ReflectionKind.number }, name: 'a' },
{ kind: ReflectionKind.propertySignature, type: { kind: ReflectionKind.string }, name: 'b' },
]
});
expectType([ReflectionOp.string, ReflectionOp.number, ReflectionOp.indexSignature, ReflectionOp.objectLiteral], copyAndSetParent({
kind: ReflectionKind.objectLiteral,
types: [
{ kind: ReflectionKind.indexSignature, index: { kind: ReflectionKind.string }, type: { kind: ReflectionKind.number } }
]
}));
expectType({
ops: [ReflectionOp.number, ReflectionOp.propertySignature, 0, ReflectionOp.string, ReflectionOp.number, ReflectionOp.indexSignature, ReflectionOp.objectLiteral],
stack: ['a']
}, {
kind: ReflectionKind.objectLiteral,
types: [
{ kind: ReflectionKind.propertySignature, type: { kind: ReflectionKind.number }, name: 'a' },
{ kind: ReflectionKind.indexSignature, index: { kind: ReflectionKind.string }, type: { kind: ReflectionKind.number } }
]
});
expectType([ReflectionOp.string, ReflectionOp.frame, ReflectionOp.number, ReflectionOp.undefined, ReflectionOp.union, ReflectionOp.indexSignature, ReflectionOp.objectLiteral], {
kind: ReflectionKind.objectLiteral,
types: [
{
kind: ReflectionKind.indexSignature,
index: { kind: ReflectionKind.string },
type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }] }
}
]
});
});
test('method', () => {
expectType({ ops: [ReflectionOp.string, ReflectionOp.method, 0], stack: ['name'] }, {
kind: ReflectionKind.method,
name: 'name',
visibility: ReflectionVisibility.public,
parameters: [],
return: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.parameter, 0, ReflectionOp.string, ReflectionOp.method, 1], stack: ['param', 'name'] }, {
kind: ReflectionKind.method,
name: 'name',
visibility: ReflectionVisibility.public,
parameters: [{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.parameter, 0, ReflectionOp.number, ReflectionOp.method, 1, ReflectionOp.protected], stack: ['param', 'name'] }, {
kind: ReflectionKind.method,
name: 'name',
visibility: ReflectionVisibility.protected,
parameters: [{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.number }
});
expectType({
ops: [ReflectionOp.string, ReflectionOp.parameter, 0, ReflectionOp.number, ReflectionOp.method, 1, ReflectionOp.protected, ReflectionOp.abstract],
stack: ['param', 'name']
}, {
kind: ReflectionKind.method,
name: 'name',
visibility: ReflectionVisibility.protected,
abstract: true,
parameters: [{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.number }
});
});
test('property', () => {
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.optional], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
optional: true,
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.protected], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
visibility: ReflectionVisibility.protected,
type: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.optional, ReflectionOp.protected], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
optional: true,
visibility: ReflectionVisibility.protected,
type: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.optional, ReflectionOp.private], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
optional: true,
visibility: ReflectionVisibility.private,
type: { kind: ReflectionKind.string }
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.optional, ReflectionOp.abstract, ReflectionOp.private], stack: ['name'] }, {
kind: ReflectionKind.property,
name: 'name',
optional: true,
abstract: true,
visibility: ReflectionVisibility.private,
type: { kind: ReflectionKind.string }
});
});
test('class', () => {
expectType({
ops: [ReflectionOp.string, ReflectionOp.property, 0, ReflectionOp.number, ReflectionOp.property, 1, ReflectionOp.class],
stack: ['name', 'id']
}, {
kind: ReflectionKind.class,
classType: Object,
types: [{
kind: ReflectionKind.property,
name: 'name',
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.string }
}, {
kind: ReflectionKind.property,
name: 'id',
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.number }
}]
});
});
test('mapped type simple', () => {
type A<T extends string> = { [P in T]: boolean };
type B = { [P in 'a' | 'b']: boolean };
type B1 = A<'a' | 'b'>;
expectType({
ops: [
ReflectionOp.jump, 4,
ReflectionOp.boolean, ReflectionOp.return,
ReflectionOp.typeParameter, 0, ReflectionOp.frame, ReflectionOp.var, ReflectionOp.loads, 1, 0, ReflectionOp.mappedType, 2, 0
],
stack: ['T'],
inputs: [{ kind: ReflectionKind.union, types: [{ kind: ReflectionKind.literal, literal: 'a' }, { kind: ReflectionKind.literal, literal: 'b' }] } as TypeUnion]
}, {
kind: ReflectionKind.objectLiteral,
types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.boolean }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.boolean }
}]
});
});
test('mapped type optional simple', () => {
type A<T extends string> = { [P in T]: boolean };
type B = { [P in 'a' | 'b']: boolean };
type B1 = A<'a' | 'b'>;
expectType({
ops: [
ReflectionOp.jump, 4,
ReflectionOp.boolean, ReflectionOp.return,
ReflectionOp.typeParameter, 0, ReflectionOp.var, ReflectionOp.loads, 0, 0, ReflectionOp.mappedType, 2, 0 | MappedModifier.optional
],
stack: ['T'],
inputs: [{ kind: ReflectionKind.union, types: [{ kind: ReflectionKind.literal, literal: 'a' }, { kind: ReflectionKind.literal, literal: 'b' }] } as TypeUnion]
}, {
kind: ReflectionKind.objectLiteral,
types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.boolean },
optional: true,
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.boolean },
optional: true,
}]
});
});
test('mapped type keyof and query', () => {
type A<T> = { [P in keyof T]: T[P] };
type B1 = A<{ a: number, b: string }>;
expectType({
ops: [
ReflectionOp.typeParameter, 0,
ReflectionOp.jump, 12,
ReflectionOp.loads, 2, 0, ReflectionOp.loads, 1, 0, ReflectionOp.indexAccess, ReflectionOp.return,
ReflectionOp.frame, ReflectionOp.var, ReflectionOp.loads, 1, 0, ReflectionOp.keyof, ReflectionOp.mappedType, 4, 0
],
stack: ['T'],
inputs: [{
kind: ReflectionKind.objectLiteral, types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.number }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.string }
}]
} as TypeObjectLiteral]
}, {
kind: ReflectionKind.objectLiteral,
types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.number }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.string }
}]
});
});
test('mapped type keyof and fixed', () => {
type A<T> = { [P in keyof T]: boolean };
type B1 = A<{ a: number, b: string }>;
expectType({
ops: [
ReflectionOp.typeParameter, 0,
ReflectionOp.jump, 6,
ReflectionOp.boolean, ReflectionOp.return,
ReflectionOp.frame, ReflectionOp.var, ReflectionOp.loads, 1, 0, ReflectionOp.keyof, ReflectionOp.mappedType, 4, 0
],
stack: ['T'],
inputs: [{
kind: ReflectionKind.objectLiteral, types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.number }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.string }
}]
} as TypeObjectLiteral]
}, {
kind: ReflectionKind.objectLiteral,
types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.boolean }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.boolean }
}]
});
});
test('mapped type keyof and conditional', () => {
type A<T> = { [P in keyof T]: T[P] extends number ? boolean : never };
type B1 = A<{ a: number, b: string }>;
expectType({
ops: [
ReflectionOp.typeParameter, 0,
ReflectionOp.jump, 18,
ReflectionOp.frame, ReflectionOp.loads, 3, 0, ReflectionOp.loads, 2, 0, ReflectionOp.indexAccess, ReflectionOp.number, ReflectionOp.extends, ReflectionOp.boolean, ReflectionOp.never, ReflectionOp.condition, ReflectionOp.return,
ReflectionOp.frame, ReflectionOp.var, ReflectionOp.loads, 1, 0, ReflectionOp.keyof, ReflectionOp.mappedType, 4, 0
],
stack: ['T'],
inputs: [{
kind: ReflectionKind.objectLiteral, types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.number }
}, {
kind: ReflectionKind.propertySignature,
name: 'b',
type: { kind: ReflectionKind.string }
}]
} as TypeObjectLiteral]
}, {
kind: ReflectionKind.objectLiteral,
types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.boolean }
}]
});
});
test('infer property signature', () => {
type A<T> = T extends { a: infer K } ? K : never;
type B1 = A<{ a: number }>;
expectType({
ops: [
ReflectionOp.typeParameter, 0,
ReflectionOp.frame, ReflectionOp.var, ReflectionOp.loads, 1, 0, ReflectionOp.frame, ReflectionOp.infer, 1, 0, ReflectionOp.propertySignature, 1, ReflectionOp.objectLiteral, ReflectionOp.extends,
ReflectionOp.loads, 0, 0, ReflectionOp.never, ReflectionOp.condition,
],
stack: ['T', 'a'],
inputs: [{
kind: ReflectionKind.objectLiteral, types: [{
kind: ReflectionKind.propertySignature,
name: 'a',
type: { kind: ReflectionKind.number }
}]
} as TypeObjectLiteral]
}, { kind: ReflectionKind.number });
});
// test('infer function parameters', () => {
// type A<T> = T extends (...args: infer K) => any ? K : never;
// type B1 = A<(a: string, b: number) => void>;
//
// expectType({
// ops: [],
// stack: ['T'],
// inputs: []
// }, {});
// });
//
// test('infer index signature', () => {
// type A<T> = T extends { [name: string]: infer K } ? K : never;
// type B1 = A<{ a: number, b: string }>;
//
// expectType({
// ops: [],
// stack: ['T'],
// inputs: []
// }, {});
// });
test('generic class', () => {
class MyClass<T> {
name!: T;
}
expectType({
ops: [ReflectionOp.typeParameter, 0, ReflectionOp.loads, 0, 0, ReflectionOp.property, 1, ReflectionOp.class],
stack: ['T', 'name'],
inputs: [{ kind: ReflectionKind.string }]
}, {
kind: ReflectionKind.class,
classType: Object,
types: [{
kind: ReflectionKind.property,
name: 'name',
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.string }
}]
});
expectType({
ops: [ReflectionOp.typeParameter, 0, ReflectionOp.loads, 0, 0, ReflectionOp.property, 1, ReflectionOp.class],
stack: ['T', 'name']
}, {
kind: ReflectionKind.class,
classType: Object,
types: [{
kind: ReflectionKind.property,
name: 'name',
visibility: ReflectionVisibility.public,
type: { kind: ReflectionKind.typeParameter, name: 'T' }
}]
});
});
test('basic types', () => {
expectType([ReflectionOp.string], { kind: ReflectionKind.string });
expectType([ReflectionOp.number], { kind: ReflectionKind.number });
expectType([ReflectionOp.boolean], { kind: ReflectionKind.boolean });
expectType([ReflectionOp.void], { kind: ReflectionKind.void });
expectType([ReflectionOp.undefined], { kind: ReflectionKind.undefined });
expectType([ReflectionOp.bigint], { kind: ReflectionKind.bigint });
expectType([ReflectionOp.null], { kind: ReflectionKind.null });
expectType({ ops: [ReflectionOp.literal, 0], stack: ['a'] }, { kind: ReflectionKind.literal, literal: 'a' });
});
test('more advances types', () => {
class Entity {
}
expectType([ReflectionOp.undefined, ReflectionOp.string, ReflectionOp.union], {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.undefined }, { kind: ReflectionKind.string }]
});
expectType([ReflectionOp.number, ReflectionOp.undefined, ReflectionOp.string, ReflectionOp.union], {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }, { kind: ReflectionKind.string }]
});
expectType([ReflectionOp.date], { kind: ReflectionKind.class, classType: Date, types: [] });
expectType([ReflectionOp.uint8Array], { kind: ReflectionKind.class, classType: Uint8Array, types: [] });
expectType([ReflectionOp.int8Array], { kind: ReflectionKind.class, classType: Int8Array, types: [] });
expectType([ReflectionOp.uint8ClampedArray], { kind: ReflectionKind.class, classType: Uint8ClampedArray, types: [] });
expectType([ReflectionOp.uint16Array], { kind: ReflectionKind.class, classType: Uint16Array, types: [] });
expectType([ReflectionOp.int16Array], { kind: ReflectionKind.class, classType: Int16Array, types: [] });
expectType([ReflectionOp.uint32Array], { kind: ReflectionKind.class, classType: Uint32Array, types: [] });
expectType([ReflectionOp.int32Array], { kind: ReflectionKind.class, classType: Int32Array, types: [] });
expectType([ReflectionOp.float32Array], { kind: ReflectionKind.class, classType: Float32Array, types: [] });
expectType([ReflectionOp.float64Array], { kind: ReflectionKind.class, classType: Float64Array, types: [] });
expectType([ReflectionOp.bigInt64Array], { kind: ReflectionKind.class, classType: BigInt64Array, types: [] });
expectType([ReflectionOp.arrayBuffer], { kind: ReflectionKind.class, classType: ArrayBuffer, types: [] });
expectType([ReflectionOp.string, ReflectionOp.promise], { kind: ReflectionKind.promise, type: { kind: ReflectionKind.string } });
// expectType({ ops: [ReflectionOp.enum, 0], stack: [() => MyEnum] }, { kind: ReflectionKind.enum, enum: MyEnum, values: Object.keys(MyEnum) });
expectType([ReflectionOp.string, ReflectionOp.set], { kind: ReflectionKind.class, classType: Set, types: [], arguments: [{ kind: ReflectionKind.string }] });
expectType([ReflectionOp.string, ReflectionOp.number, ReflectionOp.map], {
kind: ReflectionKind.class, classType: Map, types: [], arguments: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.number }]
});
expectType([ReflectionOp.string, ReflectionOp.undefined, ReflectionOp.union], {
kind: ReflectionKind.union,
types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.undefined }]
});
expectType({ ops: [ReflectionOp.frame, ReflectionOp.string, ReflectionOp.parameter, 0, ReflectionOp.void, ReflectionOp.function], stack: ['param'] }, {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.void },
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.parameter, 0, ReflectionOp.void, ReflectionOp.function], stack: ['param'] }, {
kind: ReflectionKind.function,
parameters: [{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.string } }],
return: { kind: ReflectionKind.void },
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.undefined, ReflectionOp.union, ReflectionOp.parameter, 0, ReflectionOp.void, ReflectionOp.function], stack: ['param'] }, {
kind: ReflectionKind.function,
parameters: [{
kind: ReflectionKind.parameter,
name: 'param',
type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.undefined }] }
}],
return: { kind: ReflectionKind.void },
});
expectType({
ops: [
ReflectionOp.string, ReflectionOp.undefined, ReflectionOp.union, ReflectionOp.parameter, 0,
ReflectionOp.frame, ReflectionOp.number, ReflectionOp.undefined, ReflectionOp.union, ReflectionOp.parameter, 1,
ReflectionOp.void, ReflectionOp.function
], stack: ['param', 'param2']
}, {
kind: ReflectionKind.function,
parameters: [
{
kind: ReflectionKind.parameter,
name: 'param',
type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.undefined }] }
},
{
kind: ReflectionKind.parameter,
name: 'param2',
type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.number }, { kind: ReflectionKind.undefined }] }
},
],
return: { kind: ReflectionKind.void },
});
expectType([ReflectionOp.string, ReflectionOp.array], { kind: ReflectionKind.array, type: { kind: ReflectionKind.string } });
expectType([ReflectionOp.string, ReflectionOp.undefined, ReflectionOp.union, ReflectionOp.array], {
kind: ReflectionKind.array, type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.undefined }] },
});
expectType({ ops: [ReflectionOp.string, ReflectionOp.array, ReflectionOp.parameter, 0, ReflectionOp.void, ReflectionOp.function], stack: ['param'] }, {
kind: ReflectionKind.function,
parameters: [
{ kind: ReflectionKind.parameter, name: 'param', type: { kind: ReflectionKind.array, type: { kind: ReflectionKind.string } } },
],
return: { kind: ReflectionKind.void },
});
});
test('inline class', () => {
const external = pack({ ops: [ReflectionOp.string, ReflectionOp.propertySignature, 0, ReflectionOp.objectLiteral], stack: ['a'] });
expectType({ ops: [ReflectionOp.inline, 0], stack: [external] }, {
kind: ReflectionKind.objectLiteral,
types: [{ kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } }]
});
});
test('inline class circular', () => {
const external = pack({ ops: [ReflectionOp.inline, 0, ReflectionOp.propertySignature, 1, ReflectionOp.objectLiteral], stack: ['a'] });
external.unshift(external);
const expected: TypeObjectLiteral = {
kind: ReflectionKind.objectLiteral,
types: [{ kind: ReflectionKind.propertySignature, parent: undefined as any, name: 'a', type: { kind: ReflectionKind.string } }]
};
(expected.types[0] as TypePropertySignature).parent = expected;
(expected.types[0] as TypePropertySignature).type = expected;
expectType({ ops: [ReflectionOp.inline, 0], stack: [external] }, expected);
}); | the_stack |
import {RootState} from '../../data/reducers';
import {ProviderSourceConfig, runTimeType} from '../../types';
import {containerActionCreators} from '../Container/action';
import {isEqual, isPlainObject, isEmpty, get, has} from 'lodash';
import {ContainerProps} from '../Container/Container';
import {RunTimeContextCollection} from '../context';
import {getRuntimeContext, isPromise} from '../util/util';
import {compileExpressionString, isExpression, parseExpressionString} from '../util/vm';
import {SyncAdaptor} from './adaptors/sync';
import {AsyncAdaptor} from './adaptors/async';
import {SocketAdaptor} from './adaptors/socket';
import {AjaxAdaptor} from './applications/ajax';
import {CookieAdaptor} from './applications/cookie';
import {LocalStorageAdaptor} from './applications/localstorage';
export * from './adaptors/async';
export * from './adaptors/sync';
// TODO autoInterval
export interface ProviderActions {
/**
* 异步加载中
*/
asyncLoadDataProgress: typeof containerActionCreators.asyncLoadDataProgress;
/**
* 异步加载成功
*/
asyncLoadDataSuccess: typeof containerActionCreators.asyncLoadDataSuccess;
/**
* 异步加载失败
*/
asyncLoadDataFail: typeof containerActionCreators.asyncLoadDataFail;
}
/**
* DataProvider 是一个数据源控制器
* 它通过为Container组件提供一个单一, 简单的API调用. 来对各种各样的数据获取操作进行封装
* 它支持控制同步的数据和异步的数据操作. 获取到目标数据之后,
* DataProvider会触发action来写入数据到redux store
*
* 流程图可参考
* src/doc/graphic/dataFlow.png
*
* 同步的操作会触发一个action, 并进行同步写入
* 异步的操作会有3个运行状态:
*
* 1. before(异步运行前)
* 2. progress(异步运行中)
* 3.1 success(异步运行成功)
* 3.2 fail(异步运行失败)
*/
export class DataProvider {
static providerInstance: {
[mode: string]: {
type: 'sync',
instance: SyncAdaptor
} | {
type: 'async',
instance: AsyncAdaptor
} | {
type: 'socket',
instance: SocketAdaptor
};
};
public providerCache: {
[namespace: string]: any;
};
public isUnmount: boolean;
public dependencies: {
[namespace: string]: {
dep: string[];
beDep: string[];
}
};
public buildInProvider: {
[namespace: string]: ProviderSourceConfig
};
public taskQueue: string[][];
static registerSyncProvider(mode: string, adaptor: SyncAdaptor) {
DataProvider.providerInstance[mode] = {
type: 'sync',
instance: adaptor
};
}
static registerAsyncProvider(mode: string, adaptor: AsyncAdaptor) {
DataProvider.providerInstance[mode] = {
type: 'async',
instance: adaptor
};
}
static registerSocketProvider(mode: string, adaptor: SocketAdaptor) {
DataProvider.providerInstance[mode] = {
type: 'socket',
instance: adaptor
};
}
static getProvider(mode: string) {
if (!DataProvider.providerInstance[mode]) {
console.error('can not find exact data provider of mode: ' + mode);
return null;
}
return DataProvider.providerInstance[mode];
}
constructor(providerList: ProviderSourceConfig[]) {
this.providerCache = {};
this.dependencies = {};
this.buildInProvider = {};
this.isUnmount = false;
providerList.forEach(provider => {
if (provider.namespace) {
if (this.buildInProvider[provider.namespace]) {
console.warn('DataProvider: 检测到重复的namespace: ' + provider.namespace);
return;
}
this.buildInProvider[provider.namespace] = provider;
}
});
this.buildDependencies(providerList);
this.computeRequestGroup(providerList);
}
public depose() {
delete this.providerCache;
delete this.dependencies;
delete this.buildInProvider;
this.isUnmount = true;
}
public buildDependencies(providerList: ProviderSourceConfig[]) {
for (let i = 0; i < providerList.length; i++) {
let provider = providerList[i];
let namespace = provider.namespace;
if (!namespace) {
console.error('DataProvider: mode: ' + provider.mode + ' 缺少namespace');
continue;
}
if (!this.dependencies[namespace]) {
this.dependencies[namespace] = {
dep: [],
beDep: []
};
}
if (!provider.requiredParams) {
continue;
}
let requiredParams = provider.requiredParams;
if (!Array.isArray(requiredParams)) {
continue;
}
for (let requiredKey of provider.requiredParams) {
if (!this.dependencies[requiredKey]) {
this.dependencies[requiredKey] = {
dep: [],
beDep: []
};
}
if (this.buildInProvider[requiredKey]) {
this.dependencies[namespace].dep.push(requiredKey);
this.dependencies[requiredKey].beDep.push(namespace);
}
}
}
}
public computeRequestGroup(providerList: ProviderSourceConfig[]) {
let roads: string[] = [];
let taskQueue: string[][] = [];
for (let i = 0; i < providerList.length; i++) {
let provider = providerList[i];
let requiredParams = provider.requiredParams || [];
if (!Array.isArray(requiredParams)) {
continue;
}
requiredParams = requiredParams.filter(params => {
return this.buildInProvider[params];
});
if (requiredParams.length === 0 && provider.namespace) {
let key = provider.namespace;
let paths = {};
this.getRequestTaskQueue(key, this.dependencies[key].beDep, key, paths, roads);
}
}
roads.sort((prev, next) => {
return next.split('->').length - prev.split('->').length;
});
let activeStep = {};
for (let road of roads) {
let step = road.split('->');
for (let i = 0; i < step.length; i ++) {
if (!taskQueue[i]) {
taskQueue[i] = [];
}
if (!taskQueue[i].includes(step[i]) && !activeStep[step[i]]) {
activeStep[step[i]] = true;
taskQueue[i].push(step[i]);
}
}
}
this.taskQueue = taskQueue;
}
public getRequestTaskQueue(key: string, deps: string[], road: string, paths: { [key: string]: boolean }, roads: string[]) {
if (deps.length === 0) {
roads.push(road);
return;
}
for (let nextProvider of deps) {
let existPaths = road.split('->');
if (existPaths.includes(nextProvider)) {
throw new Error(`DataProvider: 发现循环依赖的dataProvider. ${road + '->' + nextProvider}`);
}
let nextRoad = road + '->' + nextProvider;
this.getRequestTaskQueue(nextProvider, this.dependencies[nextProvider].beDep, nextRoad, paths, roads);
}
}
public shouldRequestData(
provider: ProviderSourceConfig,
runTime: runTimeType,
model: string,
props: ContainerProps,
context: RunTimeContextCollection
) {
let mode = provider.mode;
let adaptor = DataProvider.getProvider(mode);
let namespace = provider.namespace;
if (!adaptor) {
return false;
}
if (!namespace) {
return false;
}
if (runTime.$data && runTime.$data[namespace] && runTime.$data[namespace].$loading === true) {
return false;
}
if (!provider || !provider.config) {
return false;
}
let previousConfig = this.providerCache[namespace];
let config = compileExpressionString(provider.config, runTime, [], true);
let forceUpdate = runTime.$data && runTime.$data['$update'];
if (forceUpdate) {
context.rcre.store.dispatch(containerActionCreators.setData({
name: '$update',
value: false
}, model, context));
}
// if (providerConfig.autoInterval && !providerConfig._timer && !$data['$clearTimeout']) {
// providerConfig._timer = setInterval(() => {
// console.log('tick');
// store.dispatch(actionCreators.setMultiData([{
// name: '$update',
// value: true
// }, {
// name: '$clearTimeout',
// value: false
// }], props.info.model, context));
// }, providerConfig.autoInterval);
// }
//
// if (providerConfig._timer && $data['$clearTimeout']) {
// clearTimeout(providerConfig._timer);
// providerConfig._timer = 0;
// }
// 如果$data中存在字段没有满足要求,则return false
let requiredParams = provider.requiredParams;
if (isExpression(requiredParams)) {
requiredParams = parseExpressionString(requiredParams, runTime);
}
if (requiredParams instanceof Array) {
let flag = requiredParams.every(param => {
if (isExpression(param)) {
param = parseExpressionString(param, runTime);
}
if (param === null) {
console.warn('DataProvider: 动态requiredParams计算结果为null');
return false;
}
let paramData = get(runTime.$data, param);
if (this.buildInProvider[param] && paramData) {
return !paramData.$loading;
}
let strictRequired = provider.strictRequired;
if (isExpression(strictRequired)) {
strictRequired = parseExpressionString(strictRequired, runTime);
}
if (strictRequired === true) {
return !!get(runTime.$data, param);
}
return has(runTime.$data, param);
});
if (!flag) {
return false;
}
}
if (provider.hasOwnProperty('condition')) {
let condition = provider.condition;
if (isExpression(condition)) {
condition = parseExpressionString(condition, runTime);
}
if (condition === false) {
return false;
}
}
// 如果provider数据配置和上次相同, 就必须阻止以后的操作.
// 不然就会死循环
// 参考流程图: src/doc/graphic/dataFlow.png
if (previousConfig && !forceUpdate && isEqual(previousConfig, config)) {
return false;
}
// 防止adaptor中出现代码改动了provider的值
Object.freeze(config);
this.providerCache[namespace] = config;
return provider;
}
public async execProvider(config: any, provider: ProviderSourceConfig, runTime: runTimeType, actions: ProviderActions, model: string) {
let mode = provider.mode;
let adaptor = DataProvider.getProvider(mode);
if (!adaptor) {
return;
}
switch (adaptor.type) {
default:
case 'sync': {
let sync = await this.execSyncAdaptor(config, provider, adaptor.instance, runTime, actions, model);
return sync;
}
case 'async': {
return await this.execAsyncAdaptor(config, provider, adaptor.instance, runTime, actions, model);
}
case 'socket': {
// await this.execSocketAdaptor(provider, adaptor.instance, runTime, actions, model);
break;
}
}
}
private async handleAdaptorResult(provider: ProviderSourceConfig, data: any, runTime: runTimeType) {
data = this.applyRetMapping(provider, data, runTime);
if (provider.responseRewrite) {
data = await this.applyResponseRewrite(provider, data, runTime);
} else if (provider.namespace) {
data = {
[provider.namespace]: data
};
}
return data;
}
private async execSyncAdaptor(config: any, provider: ProviderSourceConfig, instance: SyncAdaptor, runTime: runTimeType, actions: ProviderActions, model: string) {
try {
let data = instance.exec(config, provider, runTime);
return this.handleAdaptorResult(provider, data, runTime);
} catch (e) {
this.handleError(actions, model, e, e.message);
return null;
}
}
private async execAsyncAdaptor(config: any, provider: ProviderSourceConfig, instance: AsyncAdaptor, runTime: runTimeType, actions: ProviderActions, model: string) {
try {
let instanceResult = await instance.exec(config, provider, runTime);
if (instanceResult.success && instanceResult.data) {
let data = instanceResult.data;
return this.handleAdaptorResult(provider, data, runTime);
} else if (instanceResult.errmsg) {
this.handleError(actions, model, new Error(instanceResult.errmsg), instanceResult.errmsg);
}
} catch (e) {
this.handleError(actions, model, e, e.message);
}
}
private applyRetMapping(provider: ProviderSourceConfig, data: any, runTime: runTimeType) {
let retMapping = provider.retMapping;
if (!retMapping || !isPlainObject(retMapping)) {
return data;
}
return compileExpressionString(retMapping, {
...runTime,
$output: data
});
}
private async applyResponseRewrite(provider: ProviderSourceConfig, data: any, runTime: runTimeType) {
let response;
if (isPlainObject(provider.responseRewrite)) {
response = compileExpressionString(provider.responseRewrite, {
...runTime,
$output: data
}, [], true);
}
if (provider.responseRewrite && isExpression(provider.responseRewrite)) {
response = parseExpressionString(provider.responseRewrite, {
...runTime,
$output: data
});
}
if (isPromise(response)) {
response = await response;
} else if (isPlainObject(response)) {
for (let key in response) {
if (response.hasOwnProperty(key) && isPromise(response[key])) {
response[key] = await response[key];
}
}
}
if (typeof provider.namespace === 'string' && response) {
response[provider.namespace] = data;
}
return response;
}
private handleError(actions: ProviderActions, model: string, error: Error, errmsg: string) {
actions.asyncLoadDataFail({
model: model,
error: errmsg
});
console.error('DataProvider exec error: ' + errmsg);
}
// private async execSocketAdaptor(provider: ProviderSourceConfig, instance: SocketAdaptor, runTime: runTimeType, actions: ProviderActions, model: string) {
// }
public getRunTime(model: string, props: ContainerProps, context: RunTimeContextCollection) {
let runTime = getRuntimeContext(context.container, context.rcre, {
iteratorContext: context.iterator
});
let state: RootState = context.rcre.store.getState();
runTime.$data = state.$rcre.container[model];
runTime.$trigger = state.$rcre.trigger[model];
return runTime;
}
public async requestForData(
model: string,
providerConfig: ProviderSourceConfig[],
actions: ProviderActions,
props: ContainerProps,
context: RunTimeContextCollection
) {
let runTime = this.getRunTime(model, props, context);
let retCache = {};
let execTask = this.taskQueue;
let isProgress = false;
// 并发发送请求
for (let i = 0; i < execTask.length; i++) {
let state: RootState = context.rcre.store.getState();
let container = state.$rcre.container[model];
let parallel = execTask[i].map(namespace => {
let provider = this.buildInProvider[namespace];
runTime.$data = {
...container,
...retCache
};
let verifyProvider = this.shouldRequestData(provider, runTime, model, props, context);
if (typeof verifyProvider === 'boolean') {
return null;
}
if (!isProgress) {
actions.asyncLoadDataProgress({
model: model
});
}
isProgress = true;
context.rcre.dataProviderEvent.addToList(verifyProvider.namespace);
return this.execProvider(this.providerCache[namespace], verifyProvider, runTime, actions, model);
});
let resultList = await Promise.all(parallel);
resultList.forEach((result, index) => {
if (!result) {
return;
}
process.nextTick(() => {
context.rcre.dataProviderEvent.setToDone(execTask[i][index]);
});
Object.assign(retCache, result);
});
}
if (!isEmpty(retCache) &&
!this.isUnmount &&
// 如果测试代码中没有正确处理,会导致jest已经回收了DOM,而接口这时候才调用完毕
(window && !!window.document)) {
actions.asyncLoadDataSuccess({
model: model,
data: retCache,
context: context
});
return retCache;
}
return null;
}
}
DataProvider.providerInstance = {};
DataProvider.registerAsyncProvider('ajax', new AjaxAdaptor());
DataProvider.registerSyncProvider('localStorage', new LocalStorageAdaptor());
DataProvider.registerSyncProvider('cookie', new CookieAdaptor()); | the_stack |
import { EventEmitter } from 'events';
import { Kind, ActionType, Region, ModeInfoSet } from './actions';
import log from '../log';
import ScreenDrag from './screen-drag';
import ScreenWheel from './screen-wheel';
import { DOM } from '../neovim';
import { Dispatcher } from 'flux';
// TODO:
// Debug log should be implemented as the subscriber of store
// and be controlled by registering it or not, watching NODE_ENV variable.
export interface Size {
lines: number;
cols: number;
width: number;
height: number;
}
export interface Cursor {
line: number;
col: number;
}
export interface FontAttributes {
fg: string;
bg: string;
sp: string;
bold: boolean;
italic: boolean;
underline: boolean;
undercurl: boolean;
draw_width: number;
draw_height: number;
width: number;
height: number;
face: string;
specified_px: number;
}
export type DispatcherType = Dispatcher<ActionType>;
// Note: 0x001203 -> '#001203'
function colorString(new_color: number, fallback: string) {
if (typeof new_color !== 'number' || new_color < 0) {
return fallback;
}
return (
'#' +
[16, 8, 0]
.map(shift => {
const mask = 0xff << shift;
const hex = ((new_color & mask) >> shift).toString(16);
return hex.length < 2 ? '0' + hex : hex;
})
.join('')
);
}
export default class NeovimStore extends EventEmitter {
dispatch_token: string;
size: Size;
font_attr: FontAttributes;
fg_color: string;
bg_color: string;
sp_color: string;
cursor: Cursor;
modeInfo: ModeInfoSet;
mode: string;
busy: boolean;
mouse_enabled: boolean;
dragging: ScreenDrag;
title: string;
icon_path: string;
wheel_scrolling: ScreenWheel;
scroll_region: Region;
dispatcher: Dispatcher<ActionType>;
focused: boolean;
line_height: number;
alt_key_disabled: boolean;
meta_key_disabled: boolean;
cursor_draw_delay: number;
blink_cursor: boolean;
cursor_blink_interval: number;
constructor(public dom: DOM) {
super();
this.dispatcher = new Dispatcher<ActionType>();
this.size = {
lines: 0,
cols: 0,
width: 0,
height: 0,
};
this.font_attr = {
fg: 'white',
bg: 'black',
sp: null,
bold: false,
italic: false,
underline: false,
undercurl: false,
draw_width: 1,
draw_height: 1,
width: 1,
height: 1,
specified_px: 1,
face: 'monospace',
};
this.cursor = {
line: 0,
col: 0,
};
this.modeInfo = {};
this.mode = 'normal';
this.busy = false;
this.mouse_enabled = true;
this.dragging = null;
this.title = '';
this.icon_path = '';
this.wheel_scrolling = new ScreenWheel(this);
this.scroll_region = {
left: 0,
right: 0,
top: 0,
bottom: 0,
};
this.focused = true;
this.line_height = 1.2;
this.alt_key_disabled = false;
this.meta_key_disabled = false;
this.cursor_draw_delay = 10;
this.blink_cursor = false;
this.cursor_blink_interval = 1000;
this.dispatch_token = this.dispatcher.register(this.receiveAction.bind(this));
}
private receiveAction(action: ActionType) {
switch (action.type) {
case Kind.Input: {
this.emit('input', action.input);
break;
}
case Kind.PutText: {
this.emit('put', action.text);
this.cursor.col = this.cursor.col + action.text.length;
this.emit('cursor');
break;
}
case Kind.Cursor: {
this.cursor = {
line: action.line,
col: action.col,
};
this.emit('cursor');
break;
}
case Kind.Highlight: {
const hl = action.highlight;
this.font_attr.bold = hl.bold;
this.font_attr.italic = hl.italic;
this.font_attr.underline = hl.underline;
this.font_attr.undercurl = hl.undercurl;
if (hl.reverse === true) {
this.font_attr.fg = colorString(hl.background, this.bg_color);
this.font_attr.bg = colorString(hl.foreground, this.fg_color);
} else {
this.font_attr.fg = colorString(hl.foreground, this.fg_color);
this.font_attr.bg = colorString(hl.background, this.bg_color);
}
this.font_attr.sp = colorString(hl.special, this.sp_color || this.fg_color);
log.debug('Highlight is updated: ', this.font_attr);
break;
}
case Kind.FocusChanged: {
this.focused = action.focused;
this.emit('focus-changed');
log.debug('Focus changed: ', this.focused);
break;
}
case Kind.ClearEOL: {
this.emit('clear-eol');
break;
}
case Kind.ClearAll: {
this.emit('clear-all');
this.cursor = {
line: 0,
col: 0,
};
this.emit('cursor');
break;
}
case Kind.ScrollScreen: {
this.emit('screen-scrolled', action.cols);
break;
}
case Kind.SetScrollRegion: {
this.scroll_region = action.region;
log.debug('Region is set: ', this.scroll_region);
this.emit('scroll-region-updated');
break;
}
case Kind.Resize: {
if (this.resize(action.lines, action.cols)) {
this.emit('resize');
}
break;
}
case Kind.UpdateFG: {
this.fg_color = colorString(action.color, this.font_attr.fg);
this.emit('update-fg');
log.debug('Foreground color is updated: ', this.fg_color);
break;
}
case Kind.UpdateBG: {
this.bg_color = colorString(action.color, this.font_attr.bg);
this.emit('update-bg');
log.debug('Background color is updated: ', this.bg_color);
break;
}
case Kind.UpdateSP: {
this.sp_color = colorString(action.color, this.fg_color);
this.emit('update-sp-color');
log.debug('Special color is updated: ', this.sp_color);
break;
}
case Kind.ModeInfo: {
this.modeInfo = action.modeInfo;
this.emit('mode-info', this.modeInfo);
break;
}
case Kind.Mode: {
this.mode = action.mode;
this.emit('mode', this.mode);
break;
}
case Kind.BusyStart: {
this.busy = true;
this.emit('busy');
break;
}
case Kind.BusyStop: {
this.busy = false;
this.emit('busy');
break;
}
case Kind.UpdateFontSize: {
this.font_attr.draw_width = action.draw_width;
this.font_attr.draw_height = action.draw_height;
this.font_attr.width = action.width;
this.font_attr.height = action.height;
log.debug('Actual font size is updated: ', action.width, action.height);
this.emit('font-size-changed');
break;
}
case Kind.UpdateFontPx: {
this.font_attr.specified_px = action.font_px;
this.emit('font-px-specified');
break;
}
case Kind.UpdateFontFace: {
this.font_attr.face = action.font_face;
this.emit('font-face-specified');
break;
}
case Kind.UpdateScreenSize: {
if (this.size.width === action.width && this.size.height === action.height) {
break;
}
this.size.width = action.width;
this.size.height = action.height;
this.emit('update-screen-size');
log.debug('Screen size is updated: ', action.width, action.height);
break;
}
case Kind.UpdateScreenBounds: {
if (this.resize(action.lines, action.cols)) {
this.emit('update-screen-bounds');
}
break;
}
case Kind.EnableMouse: {
if (!this.mouse_enabled) {
this.mouse_enabled = true;
this.emit('mouse-enabled');
log.info('Mouse enabled.');
}
break;
}
case Kind.DisableMouse: {
if (this.mouse_enabled) {
this.mouse_enabled = false;
this.emit('mouse-disabled');
log.info('Mouse disabled.');
}
break;
}
case Kind.DragStart: {
if (this.mouse_enabled) {
this.dragging = new ScreenDrag(this);
this.emit('input', this.dragging.start(action.event));
this.emit('drag-started');
} else {
log.debug('Click ignored because mouse is disabled.');
}
break;
}
case Kind.DragUpdate: {
if (this.mouse_enabled && this.dragging !== null) {
const input = this.dragging.drag(action.event);
if (input) {
this.emit('input', input);
this.emit('drag-updated');
}
}
break;
}
case Kind.DragEnd: {
if (this.mouse_enabled && this.dragging !== null) {
this.emit('input', this.dragging.end(action.event));
this.emit('drag-ended');
this.dragging = null;
}
break;
}
case Kind.WheelScroll: {
if (this.mouse_enabled) {
const input = this.wheel_scrolling.handleEvent(action.event as WheelEvent);
if (input) {
this.emit('input', input);
this.emit('wheel-scrolled');
}
}
break;
}
case Kind.Bell: {
this.emit(action.visual ? 'visual-bell' : 'beep');
break;
}
case Kind.SetTitle: {
this.title = action.title;
this.emit('title-changed');
log.info('Title is set to ', this.title);
break;
}
case Kind.SetIcon: {
this.icon_path = action.icon_path;
this.emit('icon-changed');
log.info('Icon is set to ', this.icon_path);
break;
}
case Kind.UpdateLineHeight: {
if (this.line_height !== action.line_height) {
this.line_height = action.line_height;
this.emit('line-height-changed');
log.info('Line height is changed to ', this.line_height);
}
break;
}
case Kind.DisableAltKey: {
this.alt_key_disabled = action.disabled;
this.emit('alt-key-disabled');
log.info('Alt key disabled: ', action.disabled);
break;
}
case Kind.DisableMetaKey: {
this.meta_key_disabled = action.disabled;
this.emit('meta-key-disabled');
log.info('Meta key disabled: ', action.disabled);
break;
}
case Kind.ChangeCursorDrawDelay: {
this.cursor_draw_delay = action.delay;
this.emit('cursor-draw-delay-changed');
log.info(`Drawing cursor is delayed by ${action.delay}ms`);
break;
}
case Kind.StartBlinkCursor: {
const changed = this.blink_cursor === false;
this.blink_cursor = true;
if (changed) {
this.emit('blink-cursor-started');
}
break;
}
case Kind.StopBlinkCursor: {
const changed = this.blink_cursor === true;
this.blink_cursor = false;
if (changed) {
this.emit('blink-cursor-stopped');
}
break;
}
case Kind.CompositionStart: {
this.emit('composition-started');
break;
}
case Kind.CompositionEnd: {
this.emit('composition-ended');
break;
}
default: {
log.warn('Unhandled action: ', action);
break;
}
}
}
private resize(lines: number, cols: number) {
if (this.size.lines === lines && this.size.cols === cols) {
return false;
}
this.size.lines = lines;
this.size.cols = cols;
this.scroll_region = {
top: 0,
left: 0,
right: cols - 1,
bottom: lines - 1,
};
log.debug(`Screen is resized: (${lines} lines, ${cols} cols)`);
return true;
}
} | the_stack |
import * as path from 'path'
import * as fs from 'fs'
export type AssetType = 'html' | 'typescript' | 'javascript' | 'css' | 'file'
export type Asset = Html | JavaScript | TypeScript | Css | File
export type Html = { type: 'html', timestamp: number, sourcePath: string, targetPath: string, content: string }
export type JavaScript = { type: 'javascript', timestamp: number, sourcePath: string, targetPath: string, esm: boolean }
export type TypeScript = { type: 'typescript', timestamp: number, sourcePath: string, targetPath: string, esm: boolean }
export type Css = { type: 'css', timestamp: number, sourcePath: string, targetPath: string }
export type File = { type: 'file', timestamp: number, sourcePath: string, targetPath: string }
export class Resolver {
private readonly sourcePaths = new Set<string>()
// -------------------------------------------------------------------------------------
// Attributes
// -------------------------------------------------------------------------------------
private getTimestamp(sourcePath: string): number {
return fs.statSync(sourcePath).mtimeMs
}
private getSourcePathType(sourcePath: string) {
const stat = fs.statSync(sourcePath)
if (stat.isDirectory()) return 'directory'
if (stat.isFile()) {
const extension = path.extname(sourcePath)
if (extension === '.ts' || extension === '.tsx') return 'typescript'
if (extension === '.js' || extension === '.jsx') return 'javascript'
if (extension === '.css') return 'css'
if (extension === '.html') return 'html'
return 'file'
}
return 'unknown'
}
// -------------------------------------------------------------------------------------
// Pathing
// -------------------------------------------------------------------------------------
private changeExtension(sourcePath: string, ext: string): string {
const extension = path.extname(sourcePath)
const filename = path.basename(sourcePath, extension)
const directory = path.dirname(sourcePath)
return path.join(directory, `${filename}${ext}`)
}
private getSourceDirectory(sourcePath: string): string {
return path.dirname(sourcePath)
}
private getSourcePathFromAbsolute(sourcePath: string): string {
return sourcePath
}
private getSourcePathFromRelative(partialPath: string, basePath: string): string {
return path.join(basePath, partialPath)
}
private getTargetPathFromAbsolute(absolutePath: string, basePath: string, targetDirectory: string): string {
return path.join(targetDirectory, path.relative(basePath, absolutePath))
}
private getTargetPathFromRelative(relativePath: string, targetDirectory: string): string {
return path.join(targetDirectory, relativePath)
}
// -------------------------------------------------------------------------------------
// Directory
// -------------------------------------------------------------------------------------
private * resolveDirectory(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
for (const partialPath of fs.readdirSync(sourcePath)) {
yield * this.resolveAny(path.join(sourcePath, partialPath), basePath, targetDirectory)
}
}
// -------------------------------------------------------------------------------------
// Html
// -------------------------------------------------------------------------------------
private * getHtmlTags(content: string, basePath: string, targetDirectory: string): Generator<{sourceContent: string, sourcePath: string, targetPath: string}> {
const regex = /<.*(src|href)\s*=\s*['"]([a-zA-Z0-9\._-]*)['"].*>/gi
while (true) {
const match = regex.exec(content)
if (match === null) break
const sourceContent = match[0]
const sourcePath = this.getSourcePathFromRelative(match[2], basePath)
const targetPath = this.getTargetPathFromRelative(match[2], targetDirectory)
yield { sourceContent, sourcePath, targetPath }
}
}
private getHtmlContent(content: string, tags: Array<{sourceContent: string, sourcePath: string, targetPath: string}>): string {
return tags.reduce((html, tag) => {
const extension = path.extname(tag.sourcePath)
const filename = path.basename(tag.sourcePath, extension)
const sourceName = `${filename}${extension}`
const targetName = (extension === '.tsx' || extension === '.ts') ? `${filename}.js` : `${filename}${extension}`
const targetTag = tag.sourceContent.replace(sourceName, targetName)
return html.replace(tag.sourceContent, targetTag)
}, content)
}
private * resolveHtml(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
const content = fs.readFileSync(sourcePath, 'utf-8')
const sourceDirectory = this.getSourceDirectory(sourcePath)
const htmlTags = [...this.getHtmlTags(content, sourceDirectory, targetDirectory)]
for(const htmlTag of htmlTags) {
// -----------------------------------------------------------------------------------------
// Note: Hammer will ignore any path it can't resolve that are referenced from the html
// file. Users will observe that their output bundle will not contain the reference file
// asset. Can consider emitting a warning to the user in later revisions.
// -----------------------------------------------------------------------------------------
if (!fs.existsSync(htmlTag.sourcePath)) continue
// -----------------------------------------------------------------------------------------
// Note: ESM modules can be inferred from HTML files. However because the getHtmlTags(...)
// function resolves agnostically for any tag that contains a 'src' or 'href' attribute,
// we need to explicitly check that the tag is both a <script> and contains a 'module'
// type specifier. In these cases, we call to the functions resolveTypeScript(...) and
// resolveJavaScript(...) respectively passing the 'esm' flag as 'true'.
// -----------------------------------------------------------------------------------------
const match = /<script.*type\s*=\s*['"]module['"].*>/gi.exec(htmlTag.sourceContent)
const type = this.getSourcePathType(htmlTag.sourcePath)
if (match && type === 'typescript') yield * this.resolveTypeScript(htmlTag.sourcePath, sourceDirectory, targetDirectory, true)
else if(match && type === 'javascript') yield * this.resolveJavaScript(htmlTag.sourcePath, sourceDirectory, targetDirectory, true)
else yield * this.resolveAny(htmlTag.sourcePath, basePath, targetDirectory)
}
yield {
type: 'html',
timestamp: this.getTimestamp(sourcePath),
sourcePath: this.getSourcePathFromAbsolute(sourcePath),
targetPath: this.getTargetPathFromAbsolute(sourcePath, basePath, targetDirectory),
content: this.getHtmlContent(content, htmlTags)
}
}
// -------------------------------------------------------------------------------------
// File
// -------------------------------------------------------------------------------------
private * resolveFile(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
const targetPath = this.getTargetPathFromAbsolute(sourcePath, basePath, targetDirectory)
const timestamp = this.getTimestamp(sourcePath)
yield { type: 'file', timestamp, sourcePath, targetPath }
}
// -------------------------------------------------------------------------------------
// TypeScript
// -------------------------------------------------------------------------------------
private * resolveTypeScript(sourcePath: string, basePath: string, targetDirectory: string, esm: boolean): Generator<Asset> {
const outputPath = this.getTargetPathFromAbsolute(sourcePath, basePath, targetDirectory)
const timestamp = this.getTimestamp(sourcePath)
const targetPath = this.changeExtension(outputPath, '.js')
yield { type: 'typescript', timestamp, sourcePath, targetPath, esm }
}
// -------------------------------------------------------------------------------------
// JavaScript
// -------------------------------------------------------------------------------------
private * resolveJavaScript(sourcePath: string, basePath: string, targetDirectory: string, esm: boolean): Generator<Asset> {
const targetPath = this.getTargetPathFromAbsolute(sourcePath, basePath, targetDirectory)
const timestamp = this.getTimestamp(sourcePath)
yield { type: 'javascript', timestamp, sourcePath, targetPath, esm }
}
// -------------------------------------------------------------------------------------
// Css
// -------------------------------------------------------------------------------------
private * resolveCss(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
const targetPath = this.getTargetPathFromAbsolute(sourcePath, basePath, targetDirectory)
const timestamp = this.getTimestamp(sourcePath)
yield { type: 'css', timestamp, sourcePath, targetPath }
}
// -------------------------------------------------------------------------------------
// Unknown
// -------------------------------------------------------------------------------------
private * resolveUnknown(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
}
private * resolveAny(sourcePath: string, basePath: string, targetDirectory: string): Generator<Asset> {
if(this.sourcePaths.has(sourcePath)) return
this.sourcePaths.add(sourcePath)
if (!fs.existsSync(sourcePath)) return
const type = this.getSourcePathType(sourcePath)
switch (type) {
case 'directory': yield* this.resolveDirectory(sourcePath, basePath, targetDirectory); break;
case 'typescript': yield* this.resolveTypeScript(sourcePath, basePath, targetDirectory, false); break;
case 'javascript': yield* this.resolveJavaScript(sourcePath, basePath, targetDirectory, false); break;
case 'html': yield* this.resolveHtml(sourcePath, basePath, targetDirectory); break;
case 'file': yield* this.resolveFile(sourcePath, basePath, targetDirectory); break;
case 'css': yield* this.resolveCss(sourcePath, basePath, targetDirectory); break;
case 'unknown': yield* this.resolveUnknown(sourcePath, basePath, targetDirectory); break;
}
}
public * resolve(sourcePaths: string[], targetDirectory: string): Generator<Asset> {
for (const sourcePath of sourcePaths) {
const basePath = path.dirname(sourcePath)
yield * this.resolveAny(sourcePath, basePath, targetDirectory)
}
}
}
export function resolve(sourcePaths: string[], targetDirectory: string): Generator<Asset> {
return new Resolver().resolve(sourcePaths, targetDirectory)
} | the_stack |
export const alertTypes = ["error", "info", "success", "warn", "default"];
export const messageType = ["", "warning", "success", "error"];
export const numInputTypes = ["integer", "decimal"];
export const badgeColor = ["default", "blue", "red", "yellow", "green", "mint"];
export const BarFormat = ["none", "fraction", "percentage"];
export const BarType = ["determinate", "indeterminate"];
export const coachPlacement = ["auto", "left", "right", "top", "bottom"];
export const TooltipDirection = ["top", "left", "right", "bottom"];
export const iconColorSample = [
"md-blue-70",
"md-green-60",
"md-yellow-70",
"md-red-60",
"md-blue-90",
"md-gray-80",
"md-orange-50",
"md-gold-70"
];
export const iconSamples = [
"3d-object_16",
"accessibility_16",
"accessories_16",
"accessories_18",
"accessories_36",
"accessories-active_12",
"accessories-active_16",
"application_12",
"application_16",
"application_36",
"application_48",
"application-panel_16",
"applications_16",
"arrow-down_16",
"arrow-down_18",
"arrow-down_28",
"arrow-down_32",
"arrow-down-optical_10",
"arrow-down-optical_12",
"arrow-down-optical_14",
"arrow-left_18",
"arrow-left_28",
"arrow-left_32",
"arrow-left-optical_10",
"arrow-left-optical_12",
"arrow-left-optical_14",
"arrow-left-optical_16",
"arrow-left-optical_18",
"arrow-left-optical_28",
"arrow-left-optical_32",
"arrow-right_12",
"arrow-right_16",
"arrow-right_18",
"arrow-right_28",
"arrow-right_32",
"arrow-right-optical_10",
"arrow-right-optical_12",
"arrow-right-optical_14",
"arrow-right-optical_16",
"arrow-right-optical_18",
"arrow-right-optical_28",
"arrow-right-optical_32",
"arrow-tail-down_10",
"arrow-tail-down_12",
"arrow-tail-down_14",
"arrow-tail-down_16",
"arrow-tail-down_28",
"arrow-tail-down_36",
"arrow-tail-up_10",
"arrow-tail-up_12",
"arrow-tail-up_14",
"arrow-tail-up_16",
"arrow-tail-up_28",
"arrow-tail-up_36",
"arrow-up_12",
"arrow-up_16",
"arrow-up_18",
"arrow-up_28",
"arrow-up_32",
"arrow-up-optical_12",
"arrow-up-optical_14",
"arrow-up-optical_16",
"arrow-up-optical_18",
"arrow-up-optical_28",
"arrow-up-optical_32",
"ask-for-help_12",
"ask-for-help_16",
"assign-host_12",
"assign-host_16",
"assign-privilege_12",
"assign-privilege_16",
"asterisk_10",
"asterisk_16",
"asterisk_32",
"asterisk_36",
"attachment_12",
"attachment_16",
"audio-and-video-connection_12",
"audio-broadcast_14",
"audio-broadcast_16",
"audio-call_14",
"audio-call_16",
"audio-input_16",
"audio-options_28",
"audio-options_32",
"audio-options_40",
"audio-video_12",
"audio-video_16",
"audio-video_28",
"back_10",
"back_12",
"back_16",
"back_28",
"back_36",
"back-to-fullscreen_12",
"back-to-fullscreen_14",
"back-to-fullscreen_16",
"back-to-fullscreen_22",
"back-to-fullscreen-adr_12",
"back-to-fullscreen-adr_14",
"back-to-fullscreen-adr_16",
"back-to-fullscreen-adr_22",
"back-to-fullscreen-adr_26",
"back-to-fullscreen-adr_28",
"backspace_16",
"backup-data_16",
"blocked_12",
"blocked_14",
"blocked_16",
"blocked_18",
"blocked_28",
"blocked_32",
"blocked_36",
"blocked_40",
"blocked_48",
"blocked_80",
"blog_16",
"bloomberg_16",
"bloomberg-circle_16",
"bluetooth_16",
"bluetooth-container-muted_16",
"blur_12",
"bookmark_16",
"bot_12",
"bot_14",
"bot_16",
"bot_18",
"bot_36",
"bot_40",
"bot-customer-assistant_16",
"bot-customer-assistant_36",
"bot-expert-assistant_16",
"bot-expert-assistant_36",
"breakout-session_16",
"brightness_16",
"broken-file_16",
"browser_12",
"browser_16",
"browser_28",
"bug_16",
"calendar-add_12",
"calendar-add_14",
"calendar-add_16",
"calendar-add_32",
"calendar-add_36",
"calendar-empty_16",
"calendar-empty_18",
"calendar-empty_32",
"calendar-empty-active_16",
"calendar-empty-active_18",
"calendar-empty-active_32",
"calendar-external_12",
"calendar-external_16",
"calendar-external_18",
"calendar-month_10",
"calendar-month_12",
"calendar-month_16",
"calendar-month_28",
"calendar-month_36",
"calendar-week_16",
"call-activities_16",
"call-forward_16",
"call-forward_28",
"call-forward-divert_14",
"call-forward-divert_16",
"call-forward-settings_12",
"call-forward-settings_14",
"call-handling_14",
"call-handling_16",
"call-hold_14",
"call-hold_16",
"call-incoming_12",
"call-incoming_16",
"call-log_12",
"call-log_14",
"call-log_16",
"call-merge_12",
"call-merge_16",
"call-outgoing_12",
"call-outgoing_16",
"call-pickup_14",
"call-pickup_16",
"call-pickup_18",
"call-private_12",
"call-private_14",
"call-request_12",
"call-request_14",
"call-room_28",
"call-swap_16",
"call-swap_28",
"call-voicemail_12",
"call-voicemail_16",
"call-voicemail_18",
"camera_10",
"camera_12",
"camera_120",
"camera_124",
"camera_14",
"camera_16",
"camera_18",
"camera_26",
"camera_28",
"camera_32",
"camera_36",
"camera_40",
"camera_48",
"camera_64",
"camera-active_14",
"camera-aux_16",
"camera-group_16",
"camera-muted_12",
"camera-muted_16",
"camera-muted_28",
"camera-muted_32",
"camera-muted_36",
"camera-photo_12",
"camera-photo_16",
"camera-photo_32",
"camera-photo_48",
"camera-photo-swap_16",
"camera-presence_12",
"camera-presence_14",
"camera-presence_28",
"camera-presence-stroke_10",
"camera-presence-stroke_14",
"camera-presence-stroke_16",
"camera-presence-stroke_26",
"camera-presence-stroke_30",
"camera-swap_16",
"cancel_10",
"cancel_12",
"cancel_14",
"cancel_16",
"cancel_18",
"cancel_28",
"cancel_36",
"capture-rewind_12",
"capture-rewind_16",
"cellular_16",
"certified_16",
"ch-p-search_14",
"chat_10",
"chat_12",
"chat_14",
"chat_16",
"chat_18",
"chat_26",
"chat_28",
"chat_32",
"chat_36",
"chat_40",
"chat-active_10",
"chat-active_12",
"chat-active_14",
"chat-active_16",
"chat-active_18",
"chat-active_26",
"chat-active_28",
"chat-active_32",
"chat-active_36",
"chat-group_12",
"chat-group_16",
"chat-group_32",
"chat-muted_12",
"chat-muted_16",
"chat-persistent_16",
"check_10",
"check_12",
"check_14",
"check_16",
"check_18",
"check_28",
"check_32",
"check_36",
"check_40",
"check_64",
"check_80",
"check-circle_100",
"check-circle_12",
"check-circle_14",
"check-circle_16",
"check-circle_18",
"check-circle_36",
"check-circle_40",
"check-circle_44",
"check-circle_72",
"check-circle-active_16",
"check-refresh_16",
"cisco-logo",
"clear_12",
"clear_14",
"clear_140",
"clear_16",
"clear_18",
"clear_32",
"clear_44",
"clear_80",
"clear-active_12",
"clear-active_14",
"clear-active_16",
"clear-active_18",
"clear-active_32",
"close-space_12",
"close-space_18",
"closed-caption_12",
"closed-caption_16",
"closed-caption-badge_12",
"closed-caption-badge_16",
"cloud_16",
"cloud_32",
"cloud-upload_16",
"commenting_16",
"company_16",
"company_32",
"computer_16",
"condition_16",
"contact-card_10",
"contact-card_12",
"contact-card_16",
"contact-card_22",
"contact-card_28",
"contact-card_36",
"contact-card-active_22",
"contact-group_16",
"content-download_12",
"content-download_14",
"content-share_10",
"content-share_12",
"content-share_120",
"content-share_124",
"content-share_14",
"content-share_16",
"content-share_18",
"content-share_32",
"content-share_36",
"content-share_40",
"content-share_48",
"copy_10",
"copy_12",
"copy_14",
"copy_16",
"cpu_16",
"cpu_32",
"crop_16",
"crunchbase-circle_16",
"dashboard_32",
"data-usage_16",
"data-usage_18",
"default-app_16",
"delete_10",
"delete_12",
"delete_14",
"delete_16",
"delete_18",
"deskphone_12",
"deskphone_14",
"deskphone_16",
"deskphone_32",
"deskphone_48",
"deskphone-warning_16",
"device-connection_12",
"device-connection_14",
"device-connection_16",
"device-connection_18",
"device-connection_36",
"device-connection_48",
"device-connection-active_14",
"device-connection-active_16",
"device-connection-active_36",
"device-connection-active_40",
"device-in-room_100",
"device-in-room_12",
"device-in-room_14",
"device-in-room_16",
"device-in-room_18",
"device-in-room_32",
"device-in-room_48",
"device-in-room-end_16",
"diagnostics_16",
"diagnostics_32",
"diagnostics-circle_100",
"dialpad_12",
"dialpad_16",
"directory_16",
"dislike_16",
"display_14",
"display_16",
"display_36",
"display_72",
"display-input_16",
"display-warning_16",
"dnd_12",
"dnd_120",
"dnd_124",
"dnd_14",
"dnd_16",
"dnd_18",
"dnd_26",
"dnd_28",
"dnd_32",
"dnd_36",
"dnd_40",
"dnd_48",
"dnd-active_14",
"dnd-presence_12",
"dnd-presence_14",
"dnd-presence_28",
"dnd-presence-stroke_14",
"dnd-presence-stroke_16",
"dnd-presence-stroke_26",
"dnd-presence-stroke_30",
"dock-in_12",
"dock-in_16",
"dock-out_12",
"dock-out_16",
"document_12",
"document_14",
"document_16",
"document_18",
"document_28",
"document_32",
"document_36",
"document_40",
"document_44",
"document_72",
"document-create_16",
"document-move_16",
"document-share_16",
"document-share_36",
"document-share_48",
"download_10",
"download_12",
"download_130",
"download_14",
"download_16",
"download_18",
"download_28",
"download_32",
"download-circle_100",
"drag_14",
"drag_16",
"dx70_16",
"dx80_16",
"edit_10",
"edit_12",
"edit_14",
"edit_16",
"edit_18",
"email_12",
"email_14",
"email_16",
"email-active_12",
"email-active_16",
"email-circle_32",
"email-invite_100",
"email-invite_16",
"email-read_16",
"emoji-food_16",
"emoji-heart_16",
"emoji-nature_16",
"emoji-people_16",
"emoticons_12",
"emoticons_16",
"emoticons_18",
"encryption_16",
"end-remote-desktop-control_10",
"endpoint_10",
"endpoint_12",
"endpoint_14",
"endpoint_16",
"endpoint_28",
"endpoint_32",
"endpoint_48",
"endpoint_64",
"tasks_14",
"tasks_16",
"tasks_18",
"tasks_26",
"tasks_28",
"tasks_32",
"tasks_36",
"team_12",
"team_14",
"team_16",
"team_18",
"team_32",
"team-active_12",
"team-active_14",
"team-active_16",
"team-active_18",
"team-active_32",
"telepresence_12",
"telepresence_14",
"telepresence_16",
"telepresence_18",
"telepresence_64",
"telepresence-alert_12",
"telepresence-muted_64",
"telepresence-muted-alert_12",
"telepresence-private_12",
"text_10",
"text_12",
"text_16",
"text-align-left_16",
"text-align-right_16",
"text-blockquote_12",
"text-blockquote_16",
"text-blockquote_18",
"text-bold_12",
"text-bold_16",
"text-code-block_12",
"text-code-block_16",
"text-code-inline_12",
"text-code-inline_16",
"text-color_12",
"text-color_16",
"text-format_10",
"text-format_12",
"text-format_16",
"text-heading-1_12",
"text-heading-1_16",
"text-heading-2_12",
"text-heading-2_16",
"text-heading-3_12",
"text-heading-3_16",
"text-highlight_12",
"text-highlight_16",
"text-indent-decrease_12",
"text-indent-increase_12",
"text-italic_12",
"text-italic_16",
"text-list-bulleted_10",
"text-list-bulleted_12",
"text-list-bulleted_16",
"text-list-numbered_12",
"text-list-numbered_16",
"text-list-numbered_36",
"text-list-numbered_40",
"text-strikethrough_12",
"text-strikethrough_16",
"text-table_12",
"text-table_16",
"text-underline_12",
"text-underline_16",
"too-fast_12",
"too-fast_16",
"too-slow_12",
"too-slow_16",
"tools_16",
"tools_28",
"tools_32",
"touch_16",
"transcript_16",
"twitter_16",
"twitter-circle_32",
"twitter-circle_40",
"ucm-cloud_10",
"ucm-cloud_16",
"ucm-cloud_32",
"undo_12",
"undo_14",
"undo_16",
"unread-badge_10",
"unread-badge_12",
"unread-badge_16",
"unsecure_12",
"unsecure_14",
"unsecure_16",
"unsecure_28",
"upload_12",
"upload_130",
"upload_14",
"upload_16",
"upload_18",
"upload_28",
"upload_32",
"upload_36",
"usb_16",
"user_16",
"video-effect_12",
"video-effect_16",
"video-layout_12",
"video-layout_16",
"video-layout-auto_12",
"video-layout-auto_16",
"video-layout-equal_14",
"video-layout-equal_16",
"video-layout-overlay_12",
"video-layout-overlay_16",
"video-layout-prominent_12",
"video-layout-prominent_16",
"video-layout-share-dominant_12",
"video-layout-share-dominant_16",
"video-layout-single_16",
"video-layout-video-dominant_12",
"video-layout-video-dominant_16",
"view-all_12",
"view-all_14",
"view-feed-multiple_16",
"view-feed-panel_16",
"view-feed-single_16",
"view-list_10",
"view-list_12",
"view-list_14",
"view-list_16",
"view-list_28",
"view-list-circle_100",
"view-mixed_12",
"view-stack_12",
"view-stack_14",
"view-thumbnail_12",
"view-thumbnail_14",
"view-thumbnail_16",
"voicemail_10",
"voicemail_14",
"voicemail_16",
"voicemail_18",
"voicemail_22",
"voicemail_28",
"voicemail-active_12",
"voicemail-active_14",
"voicemail-active_16",
"voicemail-active_18",
"voicemail-active_22",
"voicemail-active_28",
"wallpaper_16",
"wallpaper_28",
"wallpaper_32",
"warning_100",
"warning_12",
"warning_14",
"warning_16",
"warning_28",
"warning_32",
"warning_40",
"warning_44",
"warning_64",
"warning_72",
"web-sharing_16",
"webex_10",
"webex_16",
"webex_48",
"webex-board_14",
"webex-board_16",
"webex-board_28",
"webex-board_32",
"webex-board_48",
"webex-calling_10",
"webex-calling_12",
"webex-calling_16",
"webex-calling_18",
"webex-codec-plus_16",
"webex-instant-meeting_12",
"webex-instant-meeting_14",
"webex-instant-meeting_16",
"webex-meetings_10",
"webex-meetings_12",
"webex-meetings_14",
"webex-meetings_16",
"webex-meetings_48",
"webex-quad-camera_16",
"webex-room-kit_16",
"webex-room-kit-plus_16",
"webex-share_12",
"webex-teams_18",
"webex-voice_16",
"webpop_12",
"webpop_16",
"whatsApp_12",
"whatsApp_16",
"whiteboard_10",
"whiteboard_36",
"whiteboard-content_16",
"wifi_12",
"wifi_16",
"wifi-error_12",
"wifi-error_16",
"wikipedia_16",
"window-corner-scrub_16",
"window-vertical-scrub_16",
"youtube-circle_32",
"youtube-circle_40",
"zoom-in_12",
"zoom-in_14",
"zoom-in_16",
"zoom-out_12",
"zoom-out_14",
"zoom-out_16",
"zoom-out_20"
]; | the_stack |
import { SemanticTokensLegend, TokenMetadata, FontStyle, MetadataConsts, SemanticTokens } from 'vs/editor/common/modes';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ILogService, LogLevel } from 'vs/platform/log/common/log';
import { MultilineTokens2, SparseEncodedTokens } from 'vs/editor/common/model/tokensStore';
import { IModeService } from 'vs/editor/common/services/modeService';
export const enum SemanticTokensProviderStylingConstants {
NO_STYLING = 0b01111111111111111111111111111111
}
export class SemanticTokensProviderStyling {
private readonly _hashTable: HashTable;
private _hasWarnedOverlappingTokens: boolean;
constructor(
private readonly _legend: SemanticTokensLegend,
private readonly _themeService: IThemeService,
private readonly _modeService: IModeService,
private readonly _logService: ILogService
) {
this._hashTable = new HashTable();
this._hasWarnedOverlappingTokens = false;
}
public getMetadata(tokenTypeIndex: number, tokenModifierSet: number, languageId: string): number {
const encodedLanguageId = this._modeService.languageIdCodec.encodeLanguageId(languageId);
const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
let metadata: number;
if (entry) {
metadata = entry.metadata;
if (this._logService.getLevel() === LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
}
} else {
let tokenType = this._legend.tokenTypes[tokenTypeIndex];
const tokenModifiers: string[] = [];
if (tokenType) {
let modifierSet = tokenModifierSet;
for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
if (modifierSet & 1) {
tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
}
modifierSet = modifierSet >> 1;
}
if (modifierSet > 0 && this._logService.getLevel() === LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`);
tokenModifiers.push('not-in-legend');
}
const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
if (typeof tokenStyle === 'undefined') {
metadata = SemanticTokensProviderStylingConstants.NO_STYLING;
} else {
metadata = 0;
if (typeof tokenStyle.italic !== 'undefined') {
const italicBit = (tokenStyle.italic ? FontStyle.Italic : 0) << MetadataConsts.FONT_STYLE_OFFSET;
metadata |= italicBit | MetadataConsts.SEMANTIC_USE_ITALIC;
}
if (typeof tokenStyle.bold !== 'undefined') {
const boldBit = (tokenStyle.bold ? FontStyle.Bold : 0) << MetadataConsts.FONT_STYLE_OFFSET;
metadata |= boldBit | MetadataConsts.SEMANTIC_USE_BOLD;
}
if (typeof tokenStyle.underline !== 'undefined') {
const underlineBit = (tokenStyle.underline ? FontStyle.Underline : 0) << MetadataConsts.FONT_STYLE_OFFSET;
metadata |= underlineBit | MetadataConsts.SEMANTIC_USE_UNDERLINE;
}
if (tokenStyle.foreground) {
const foregroundBits = (tokenStyle.foreground) << MetadataConsts.FOREGROUND_OFFSET;
metadata |= foregroundBits | MetadataConsts.SEMANTIC_USE_FOREGROUND;
}
if (metadata === 0) {
// Nothing!
metadata = SemanticTokensProviderStylingConstants.NO_STYLING;
}
}
} else {
if (this._logService.getLevel() === LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`);
}
metadata = SemanticTokensProviderStylingConstants.NO_STYLING;
tokenType = 'not-in-legend';
}
this._hashTable.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
if (this._logService.getLevel() === LogLevel.Trace) {
this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(' ')}): foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
}
}
return metadata;
}
public warnOverlappingSemanticTokens(lineNumber: number, startColumn: number): void {
if (!this._hasWarnedOverlappingTokens) {
this._hasWarnedOverlappingTokens = true;
console.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
}
}
}
const enum SemanticColoringConstants {
/**
* Let's aim at having 8KB buffers if possible...
* So that would be 8192 / (5 * 4) = 409.6 tokens per area
*/
DesiredTokensPerArea = 400,
/**
* Try to keep the total number of areas under 1024 if possible,
* simply compensate by having more tokens per area...
*/
DesiredMaxAreas = 1024,
}
export function toMultilineTokens2(tokens: SemanticTokens, styling: SemanticTokensProviderStyling, languageId: string): MultilineTokens2[] {
const srcData = tokens.data;
const tokenCount = (tokens.data.length / 5) | 0;
const tokensPerArea = Math.max(Math.ceil(tokenCount / SemanticColoringConstants.DesiredMaxAreas), SemanticColoringConstants.DesiredTokensPerArea);
const result: MultilineTokens2[] = [];
let tokenIndex = 0;
let lastLineNumber = 1;
let lastStartCharacter = 0;
while (tokenIndex < tokenCount) {
const tokenStartIndex = tokenIndex;
let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
// Keep tokens on the same line in the same area...
if (tokenEndIndex < tokenCount) {
let smallTokenEndIndex = tokenEndIndex;
while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
smallTokenEndIndex--;
}
if (smallTokenEndIndex - 1 === tokenStartIndex) {
// there are so many tokens on this line that our area would be empty, we must now go right
let bigTokenEndIndex = tokenEndIndex;
while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
bigTokenEndIndex++;
}
tokenEndIndex = bigTokenEndIndex;
} else {
tokenEndIndex = smallTokenEndIndex;
}
}
let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
let destOffset = 0;
let areaLine = 0;
let prevLineNumber = 0;
let prevStartCharacter = 0;
let prevEndCharacter = 0;
while (tokenIndex < tokenEndIndex) {
const srcOffset = 5 * tokenIndex;
const deltaLine = srcData[srcOffset];
const deltaCharacter = srcData[srcOffset + 1];
const lineNumber = lastLineNumber + deltaLine;
const startCharacter = (deltaLine === 0 ? lastStartCharacter + deltaCharacter : deltaCharacter);
const length = srcData[srcOffset + 2];
const tokenTypeIndex = srcData[srcOffset + 3];
const tokenModifierSet = srcData[srcOffset + 4];
const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
if (metadata !== SemanticTokensProviderStylingConstants.NO_STYLING) {
if (areaLine === 0) {
areaLine = lineNumber;
}
if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
if (prevStartCharacter < startCharacter) {
// the previous token survives after the overlapping one
destData[destOffset - 4 + 2] = startCharacter;
} else {
// the previous token is entirely covered by the overlapping one
destOffset -= 4;
}
}
destData[destOffset] = lineNumber - areaLine;
destData[destOffset + 1] = startCharacter;
destData[destOffset + 2] = startCharacter + length;
destData[destOffset + 3] = metadata;
destOffset += 4;
prevLineNumber = lineNumber;
prevStartCharacter = startCharacter;
prevEndCharacter = startCharacter + length;
}
lastLineNumber = lineNumber;
lastStartCharacter = startCharacter;
tokenIndex++;
}
if (destOffset !== destData.length) {
destData = destData.subarray(0, destOffset);
}
const tokens = new MultilineTokens2(areaLine, new SparseEncodedTokens(destData));
result.push(tokens);
}
return result;
}
class HashTableEntry {
public readonly tokenTypeIndex: number;
public readonly tokenModifierSet: number;
public readonly languageId: number;
public readonly metadata: number;
public next: HashTableEntry | null;
constructor(tokenTypeIndex: number, tokenModifierSet: number, languageId: number, metadata: number) {
this.tokenTypeIndex = tokenTypeIndex;
this.tokenModifierSet = tokenModifierSet;
this.languageId = languageId;
this.metadata = metadata;
this.next = null;
}
}
class HashTable {
private static _SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
private _elementsCount: number;
private _currentLengthIndex: number;
private _currentLength: number;
private _growCount: number;
private _elements: (HashTableEntry | null)[];
constructor() {
this._elementsCount = 0;
this._currentLengthIndex = 0;
this._currentLength = HashTable._SIZES[this._currentLengthIndex];
this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
this._elements = [];
HashTable._nullOutEntries(this._elements, this._currentLength);
}
private static _nullOutEntries(entries: (HashTableEntry | null)[], length: number): void {
for (let i = 0; i < length; i++) {
entries[i] = null;
}
}
private _hash2(n1: number, n2: number): number {
return (((n1 << 5) - n1) + n2) | 0; // n1 * 31 + n2, keep as int32
}
private _hashFunc(tokenTypeIndex: number, tokenModifierSet: number, languageId: number): number {
return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
}
public get(tokenTypeIndex: number, tokenModifierSet: number, languageId: number): HashTableEntry | null {
const hash = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
let p = this._elements[hash];
while (p) {
if (p.tokenTypeIndex === tokenTypeIndex && p.tokenModifierSet === tokenModifierSet && p.languageId === languageId) {
return p;
}
p = p.next;
}
return null;
}
public add(tokenTypeIndex: number, tokenModifierSet: number, languageId: number, metadata: number): void {
this._elementsCount++;
if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
// expand!
const oldElements = this._elements;
this._currentLengthIndex++;
this._currentLength = HashTable._SIZES[this._currentLengthIndex];
this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
this._elements = [];
HashTable._nullOutEntries(this._elements, this._currentLength);
for (const first of oldElements) {
let p = first;
while (p) {
const oldNext = p.next;
p.next = null;
this._add(p);
p = oldNext;
}
}
}
this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
}
private _add(element: HashTableEntry): void {
const hash = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
element.next = this._elements[hash];
this._elements[hash] = element;
}
} | the_stack |
import Button from "antd/lib/button";
import Row from "antd/lib/row";
import { Languages } from "iotex-react-language-dropdown";
import { LanguageSwitcher } from "iotex-react-language-dropdown/lib/language-switcher";
import isBrowser from "is-browser";
import { t } from "onefx/lib/iso-i18n";
import { styled, StyleObject } from "onefx/lib/styletron-react";
import React, { Component, useState } from "react";
import OutsideClickHandler from "react-outside-click-handler";
import { connect, DispatchProp } from "react-redux";
import { Link } from "react-router-dom";
// @ts-ignore
import JsonGlobal from "safe-json-globals/get";
import { setSwitchAddress } from "../../client/javascripts/base-actions";
import { assetURL } from "./asset-url";
import { CommonMargin } from "./common-margin";
import { Logo as Icon } from "./icon";
import { Cross } from "./icons/cross.svg";
import { Hamburger } from "./icons/hamburger.svg";
import { transition } from "./styles/style-animation";
import { colors } from "./styles/style-color";
import { media, PALM_WIDTH } from "./styles/style-media";
import { contentPadding } from "./styles/style-padding";
import { TopbarExtMenu } from "./topbar-ext-menu";
const globalState = isBrowser && JsonGlobal("state");
const LanguageSwitcherMenu = () => {
return (
<Row className="language-switcher" style={{ marginLeft: "1em" }}>
<LanguageSwitcher
supportedLanguages={[
Languages.EN,
Languages.ZH_CN,
Languages.IT,
Languages.DE
]}
/>
</Row>
);
};
const AddressConverterSwitcher = (props: {
onSwitch(s: boolean): void;
toEthAddress: boolean;
}) => {
const [toEthAddress, setShowIoAddress] = useState(props.toEthAddress);
// @ts-ignore
const convertAddress = e => {
setShowIoAddress(!toEthAddress);
props.onSwitch(!toEthAddress);
e.stopPropagation();
};
return (
<AddressSwitcherContainer onClick={convertAddress}>
{/* tslint:disable-next-line:use-simple-attributes */}
<AddressSwitcherItem
style={{ background: toEthAddress ? "" : "#50B1A0" }}
>
io
</AddressSwitcherItem>
{/* tslint:disable-next-line:use-simple-attributes */}
<AddressSwitcherItem
style={{ background: toEthAddress ? "#89A8F2" : "" }}
>
0x
</AddressSwitcherItem>
</AddressSwitcherContainer>
);
};
const AddressSwitcherContainer = styled("div", {
display: "inline-block",
width: "4rem",
height: "1.3rem",
lineHeight: "1.3rem",
background: colors.black85,
borderRadius: "0.125rem",
cursor: "pointer"
});
const AddressSwitcherItem = styled("div", {
display: "inline-block",
width: "2rem",
height: "1.3rem",
lineHeight: "1.3rem",
color: "white",
textAlign: "center",
cursor: "pointer"
});
const V2Entry = styled("a", {
background: "rgba(217, 217, 217, 0.1)",
borderRadius: "5px",
width: "69px",
textAlign: "center",
fontWeight: 500,
fontSize: "14px",
lineHeight: "24px",
height: "24px",
display: "inline-block",
color: "#44FFB2"
});
const multiChain: {
current: string;
chains: Array<{
name: string;
url: string;
}>;
} = {
current: (isBrowser && globalState.base.multiChain.current) || "MAINNET",
chains: [
{
name: "MAINNET",
url: "https://iotexscan.io/"
},
{
name: "TESTNET",
url: "https://testnet.iotexscan.io/"
}
]
};
const CHAIN_MENU_ITEM = {
label: multiChain.current,
items: multiChain.chains.map(({ name, url }) => ({
name: t(name),
path: url
}))
};
export const TOP_BAR_HEIGHT = 60;
type State = {
displayMobileMenu: boolean;
};
type Props = {
loggedIn: boolean;
locale: string;
grafanaLink: string;
toEthAddress: boolean;
// tslint:disable:no-any
location: any;
} & DispatchProp;
export const TopBar = connect(
(state: {
base: {
userId?: string;
locale: string;
grafanaLink: string;
toEthAddress: boolean;
};
}) => ({
loggedIn: Boolean(state.base.userId),
locale: state.base.locale,
grafanaLink: state.base.grafanaLink,
toEthAddress: state.base.toEthAddress
})
)(
class TopBarInner extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
displayMobileMenu: false
};
}
public componentDidMount(): void {
window.addEventListener("resize", () => {
if (
document.documentElement &&
document.documentElement.clientWidth > PALM_WIDTH
) {
this.setState({
displayMobileMenu: false
});
}
});
}
public displayMobileMenu = () => {
this.setState({
displayMobileMenu: true
});
};
public hideMobileMenu = () => {
this.setState({
displayMobileMenu: false
});
};
public renderTools = (hasShadow: boolean) => {
return (
<TopbarExtMenu
hasShadow={hasShadow}
name={t("topbar.tools")}
routes={[
{
name: t("topbar.explorer_playground"),
path: "/explorer-playground/"
},
{
name: t("topbar.analytics_playground"),
path: "https://analytics.iotexscan.io/"
},
{
name: t("topbar.submit_a_bug_report"),
path: "https://github.com/iotexproject/iotex-explorer/issues/new"
},
{
name: t("topbar.address_converter"),
path: "https://member.iotex.io/tools/address-convert"
}
]}
onClick={this.hideMobileMenu}
/>
);
};
public renderWallets = (hasShadow: boolean) => {
return (
<TopbarExtMenu
hasShadow={hasShadow}
name={t("topbar.wallet")}
routes={[
{
name: t("topbar.wallet.ioPayMobile"),
path: "https://iopay.iotex.io"
},
{
name: t("topbar.wallet.ioPayDesktop"),
path: "https://iopay.iotex.io/desktop"
},
{
name: t("topbar.wallet.web"),
path: "https://iotexscan.io/wallet"
}
]}
onClick={this.hideMobileMenu}
/>
);
};
public renderBlockchain = (hasShadow: boolean) => {
return (
<TopbarExtMenu
hasShadow={hasShadow}
name={t("topbar.dashboard")}
routes={[
{ name: t("topbar.dashboard"), path: "/" },
{ name: t("topbar.actions"), path: "/action" },
{ name: t("topbar.blocks"), path: "/block" },
{ name: t("topbar.accounts"), path: "/account" }
]}
onClick={this.hideMobileMenu}
/>
);
};
public renderToken = (hasShadow: boolean) => {
return (
<TopbarExtMenu
hasShadow={hasShadow}
name={t("topbar.tokensMenu")}
routes={[
{ name: t("topbar.tokens"), path: "/tokens" },
{ name: t("topbar.xrc20Transfer"), path: "/tokentxns" },
{ name: t("topbar.xrc721Tokens"), path: "/xrc721-tokens" },
{ name: t("topbar.xrc721Transfer"), path: "/xrc721-tokentxns" }
]}
onClick={this.hideMobileMenu}
/>
);
};
public renderNetSelector = (hasShadow: boolean) => {
return (
<TopbarExtMenu
hasShadow={hasShadow}
name={t(CHAIN_MENU_ITEM.label)}
routes={CHAIN_MENU_ITEM.items}
onClick={this.hideMobileMenu}
/>
);
};
public renderMobileMenu = () => {
if (!this.state.displayMobileMenu) {
return null;
}
const { location } = this.props;
return (
<OutsideClickHandler onOutsideClick={this.hideMobileMenu}>
<Dropdown>
{this.renderBlockchain(true)}
{this.renderToken(true)}
{this.renderTools(true)}
<StyledExternalLink
href="https://member.iotex.io"
target="_blank"
onClick={this.hideMobileMenu}
>
{t("topbar.voting")}
</StyledExternalLink>
<StyledLink to="/wallet/transfer" onClick={this.hideMobileMenu}>
{t("topbar.wallet")}
</StyledLink>
{this.renderNetSelector(true)}
<div
style={{
display: "flex",
alignItems: "center",
width: "100%",
marginTop: "12px"
}}
>
<V2Entry
href={`https://v2.iotexscan.io${location.pathname}${location.search}`}
>
v2 beta
</V2Entry>
</div>
</Dropdown>
</OutsideClickHandler>
);
};
public render(): JSX.Element {
const { locale, location } = this.props;
const displayMobileMenu = this.state.displayMobileMenu;
return (
<div
style={{
position: "relative",
height: `${TOP_BAR_HEIGHT}px`
}}
>
<Bar>
<Flex>
<LinkLogoWrapper to={`/`}>
<Icon
height="38px"
width="auto"
margin="11px 0"
url={assetURL(
locale === "en"
? "/logo_explorer.png"
: "/logo_explorer.png"
)}
/>
</LinkLogoWrapper>
<HiddenOnMobile>
<CommonMargin />
<CommonMargin />
{this.renderBlockchain(true)}
{this.renderToken(true)}
{this.renderTools(true)}
<BrandLinkExternalUrl
href="https://member.iotex.io"
target="_blank"
onClick={this.hideMobileMenu}
>
{t("topbar.voting")}
</BrandLinkExternalUrl>
{this.renderWallets(true)}
<CommonMargin />
{this.renderNetSelector(true)}
<div
style={{
display: "flex",
alignItems: "center",
marginLeft: "24px"
}}
>
<V2Entry
href={`https://v2.iotexscan.io${location.pathname}${location.search}`}
>
v2 beta
</V2Entry>
</div>
</HiddenOnMobile>
</Flex>
<Flex>
<HamburgerBtn
onClick={this.displayMobileMenu}
displayMobileMenu={displayMobileMenu}
>
<Hamburger />
</HamburgerBtn>
<CrossBtn displayMobileMenu={displayMobileMenu}>
<Cross />
</CrossBtn>
<Flex style={{ alignItems: "center", justifyContent: "center" }}>
<AddressConverterSwitcher
toEthAddress={this.props.toEthAddress}
onSwitch={s => {
this.props.dispatch(setSwitchAddress(s));
}}
/>
<LanguageSwitcherMenu />
</Flex>
</Flex>
</Bar>
{this.renderMobileMenu()}
</div>
);
}
}
);
const Bar = styled("div", {
display: "flex",
position: "inherit",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
lineHeight: `${TOP_BAR_HEIGHT}px`,
height: `${TOP_BAR_HEIGHT}px`,
backgroundColor: colors.nav01,
top: "0px",
left: "0px",
width: "100%",
"z-index": "70",
...contentPadding,
boxSizing: "border-box",
boxShadow: "0",
[media.mediaHeaderWide]: {
position: "fixed"
},
[media.mediaHeaderDeskTopMin]: {
position: "fixed"
}
});
function HamburgerBtn({
displayMobileMenu,
children,
onClick
}: {
displayMobileMenu: boolean;
children: Array<JSX.Element> | JSX.Element;
onClick: Function;
}): JSX.Element {
const Styled = styled("div", {
":hover": {
color: colors.primary
},
color: colors.white,
display: "none!important",
[media.mediaHeaderWide]: {
display: "flex!important",
...(displayMobileMenu ? { display: "none!important" } : {})
},
[media.mediaHeaderDeskTopMin]: {
display: "flex!important",
...(displayMobileMenu ? { display: "none!important" } : {})
},
cursor: "pointer",
justifyContent: "center",
alignItems: "center"
});
return (
<Styled
// @ts-ignore
onClick={onClick}
>
{children}
</Styled>
);
}
function CrossBtn({
displayMobileMenu,
children
}: {
displayMobileMenu: boolean;
children: Array<JSX.Element> | JSX.Element;
}): JSX.Element {
const Styled = styled("div", {
":hover": {
color: colors.primary
},
color: colors.white,
display: "none!important",
[media.mediaHeaderWide]: {
display: "none!important",
...(displayMobileMenu ? { display: "flex!important" } : {})
},
[media.mediaHeaderDeskTopMin]: {
display: "none!important",
...(displayMobileMenu ? { display: "flex!important" } : {})
},
cursor: "pointer",
justifyContent: "center",
alignItems: "center",
padding: "5px"
});
return <Styled>{children}</Styled>;
}
const LinkLogoWrapper = styled(Link, {
width: `${TOP_BAR_HEIGHT * 3}px`,
height: `${TOP_BAR_HEIGHT}px`
});
const menuItem: StyleObject = {
color: colors.topbarColor,
textDecoration: "none",
":hover": {
color: colors.primary
},
transition,
padding: "0 20px",
[media.mediaHeaderWide]: {
boxSizing: "border-box",
width: "100%",
padding: "16px 0 16px 0"
},
[media.mediaHeaderDeskTopMin]: {
boxSizing: "border-box",
width: "100%",
padding: "16px 0 16px 0"
}
};
const BrandLinkExternalUrl = styled("a", {
...menuItem,
[media.mediaHeaderWide]: {},
[media.mediaHeaderDeskTopMin]: {}
});
// @ts-ignore
const StyledLink = styled(Link, menuItem);
const StyledExternalLink = styled("a", menuItem);
const Flex = styled("div", (_: React.CSSProperties) => ({
flexDirection: "row",
display: "flex",
boxSizing: "border-box"
}));
const Dropdown = styled("div", {
backgroundColor: colors.nav01,
display: "flex",
flexDirection: "column",
...contentPadding,
position: "fixed",
top: `${TOP_BAR_HEIGHT}px`,
"z-index": "999",
width: "100vw",
height: "100vh",
alignItems: "flex-end!important",
boxSizing: "border-box"
});
const HiddenOnMobile = styled("div", {
display: "flex!important",
flex: 1,
[media.mediaHeaderWide]: {
display: "none!important"
},
[media.mediaHeaderDeskTopMin]: {
display: "none!important"
}
}); | the_stack |
import { Palette } from "../interface";
export function getItalicSyntax(palette: Palette, italicComments: boolean) {
const syntax = [
// Syntax{{{
{
name: "Regular",
scope: "storage.type.function.arrow, keyword.other.arrow",
settings: {
fontStyle: "regular",
},
},
{
name: "Keyword",
scope:
"keyword, storage.type.function, storage.type.class, storage.type.enum, storage.type.interface, storage.type.property, keyword.operator.new, keyword.operator.expression, keyword.operator.new, keyword.operator.delete, storage.type.extends",
settings: {
foreground: palette.red,
},
},
{
name: "Keyword Italic",
scope:
"keyword.control, storage.type.function, storage.type.class, storage.type.enum, storage.type.interface, storage.type.property, keyword.operator.new, keyword.operator.expression, keyword.operator.new, keyword.operator.delete, storage.type.extends",
settings: {
fontStyle: "italic",
},
},
{
name: "Debug",
scope: "keyword.other.debugger",
settings: {
foreground: palette.red,
},
},
{
name: "Storage",
scope:
"storage, modifier, keyword.var, entity.name.tag, keyword.control.case, keyword.control.switch",
settings: {
foreground: palette.orange,
},
},
{
name: "Operator",
scope: "keyword.operator",
settings: {
foreground: palette.orange,
},
},
{
name: "String",
scope:
"string, punctuation.definition.string.end, punctuation.definition.string.begin, punctuation.definition.string.template.begin, punctuation.definition.string.template.end",
settings: {
foreground: palette.yellow,
},
},
{
name: "Attribute",
scope: "entity.other.attribute-name",
settings: {
foreground: palette.yellow,
},
},
{
name: "String Escape",
scope:
"constant.character.escape, punctuation.quasi.element, punctuation.definition.template-expression, punctuation.section.embedded, storage.type.format, constant.other.placeholder, constant.other.placeholder, variable.interpolation",
settings: {
foreground: palette.green,
},
},
{
name: "Function",
scope:
"entity.name.function, support.function, meta.function, meta.function-call, meta.definition.method",
settings: {
foreground: palette.green,
},
},
{
name: "Preproc",
scope:
"keyword.control.at-rule, keyword.control.import, keyword.control.export, storage.type.namespace, punctuation.decorator, keyword.control.directive, keyword.preprocessor, punctuation.definition.preprocessor, punctuation.definition.directive, keyword.other.import, keyword.other.package, entity.name.type.namespace, entity.name.scope-resolution, keyword.other.using, keyword.package, keyword.import, keyword.map",
settings: {
foreground: palette.aqua,
},
},
{
name: "Preproc Italic",
scope:
"keyword.control.at-rule, keyword.control.import, keyword.control.export, storage.type.namespace, keyword.control.directive, keyword.preprocessor, keyword.other.import, keyword.other.package, entity.name.type.namespace, entity.name.scope-resolution, keyword.other.using, keyword.package, keyword.import, keyword.map",
settings: {
fontStyle: "italic",
},
},
{
name: "Annotation",
scope: "storage.type.annotation",
settings: {
foreground: palette.aqua,
},
},
{
name: "Label",
scope: "entity.name.label, constant.other.label",
settings: {
foreground: palette.aqua,
},
},
{
name: "Modules",
scope:
"support.module, support.node, support.other.module, support.type.object.module, entity.name.type.module, entity.name.type.class.module, keyword.control.module",
settings: {
foreground: palette.aqua,
fontStyle: "italic",
},
},
{
name: "Type",
scope: "storage.type, support.type, entity.name.type, keyword.type",
settings: {
foreground: palette.blue,
},
},
{
name: "Class",
scope:
"entity.name.type.class, support.class, entity.name.class, entity.other.inherited-class, storage.class",
settings: {
foreground: palette.blue,
},
},
{
name: "Number",
scope: "constant.numeric",
settings: {
foreground: palette.purple,
},
},
{
name: "Boolean",
scope: "constant.language.boolean",
settings: {
foreground: palette.purple,
},
},
{
name: "Macro",
scope: "entity.name.function.preprocessor",
settings: {
foreground: palette.purple,
},
},
{
name: "Special identifier",
scope:
"variable.language.this, variable.language.self, variable.language.super, keyword.other.this, variable.language.special, constant.language.null, constant.language.undefined, constant.language.nan",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
{
name: "Constant",
scope: "constant.language, support.constant",
settings: {
foreground: palette.purple,
},
},
{
name: "Identifier",
scope: "variable, support.variable, meta.definition.variable",
settings: {
foreground: palette.fg,
},
},
{
name: "Property",
scope:
"variable.object.property, support.variable.property, variable.other.property, variable.other.object.property, variable.other.enummember, variable.other.member, meta.object-literal.key",
settings: {
foreground: palette.fg,
},
},
{
name: "Delimiter",
scope: "punctuation, meta.brace, meta.delimiter, meta.bracket",
settings: {
foreground: palette.fg,
},
},
// }}}
// Markdown{{{
{
name: "Markdown heading1",
scope: "heading.1.markdown, markup.heading.setext.1.markdown",
settings: {
foreground: palette.red,
fontStyle: "bold",
},
},
{
name: "Markdown heading2",
scope: "heading.2.markdown, markup.heading.setext.2.markdown",
settings: {
foreground: palette.orange,
fontStyle: "bold",
},
},
{
name: "Markdown heading3",
scope: "heading.3.markdown",
settings: {
foreground: palette.yellow,
fontStyle: "bold",
},
},
{
name: "Markdown heading4",
scope: "heading.4.markdown",
settings: {
foreground: palette.green,
fontStyle: "bold",
},
},
{
name: "Markdown heading5",
scope: "heading.5.markdown",
settings: {
foreground: palette.blue,
fontStyle: "bold",
},
},
{
name: "Markdown heading6",
scope: "heading.6.markdown",
settings: {
foreground: palette.purple,
fontStyle: "bold",
},
},
{
name: "Markdown heading delimiter",
scope: "punctuation.definition.heading.markdown",
settings: {
foreground: palette.grey1,
fontStyle: "regular",
},
},
{
name: "Markdown link",
scope:
"string.other.link.title.markdown, constant.other.reference.link.markdown, string.other.link.description.markdown",
settings: {
foreground: palette.purple,
fontStyle: "regular",
},
},
{
name: "Markdown link text",
scope:
"markup.underline.link.image.markdown, markup.underline.link.markdown",
settings: {
foreground: palette.green,
fontStyle: "underline",
},
},
{
name: "Markdown delimiter",
scope:
"punctuation.definition.string.begin.markdown, punctuation.definition.string.end.markdown, punctuation.definition.italic.markdown, punctuation.definition.quote.begin.markdown, punctuation.definition.metadata.markdown, punctuation.separator.key-value.markdown, punctuation.definition.constant.markdown",
settings: {
foreground: palette.grey1,
},
},
{
name: "Markdown bold delimiter",
scope: "punctuation.definition.bold.markdown",
settings: {
foreground: palette.grey1,
fontStyle: "regular",
},
},
{
name: "Markdown separator delimiter",
scope:
"meta.separator.markdown, punctuation.definition.constant.begin.markdown, punctuation.definition.constant.end.markdown",
settings: {
foreground: palette.grey1,
fontStyle: "bold",
},
},
{
name: "Markdown italic",
scope: "markup.italic",
settings: {
fontStyle: "italic",
},
},
{
name: "Markdown bold",
scope: "markup.bold",
settings: {
fontStyle: "bold",
},
},
{
name: "Markdown bold italic",
scope: "markup.bold markup.italic, markup.italic markup.bold",
settings: {
fontStyle: "italic bold",
},
},
{
name: "Markdown code delimiter",
scope:
"punctuation.definition.markdown, punctuation.definition.raw.markdown",
settings: {
foreground: palette.yellow,
},
},
{
name: "Markdown code type",
scope: "fenced_code.block.language",
settings: {
foreground: palette.yellow,
},
},
{
name: "Markdown code block",
scope:
"markup.fenced_code.block.markdown, markup.inline.raw.string.markdown",
settings: {
foreground: palette.green,
},
},
{
name: "Markdown list mark",
scope: "punctuation.definition.list.begin.markdown",
settings: {
foreground: palette.red,
},
},
// }}}
// reStructuredText{{{
{
name: "reStructuredText heading",
scope: "punctuation.definition.heading.restructuredtext",
settings: {
foreground: palette.orange,
fontStyle: "bold",
},
},
{
name: "reStructuredText delimiter",
scope:
"punctuation.definition.field.restructuredtext, punctuation.separator.key-value.restructuredtext, punctuation.definition.directive.restructuredtext, punctuation.definition.constant.restructuredtext, punctuation.definition.italic.restructuredtext, punctuation.definition.table.restructuredtext",
settings: {
foreground: palette.grey1,
},
},
{
name: "reStructuredText delimiter bold",
scope: "punctuation.definition.bold.restructuredtext",
settings: {
foreground: palette.grey1,
fontStyle: "regular",
},
},
{
name: "reStructuredText aqua",
scope:
"entity.name.tag.restructuredtext, punctuation.definition.link.restructuredtext, punctuation.definition.raw.restructuredtext, punctuation.section.raw.restructuredtext",
settings: {
foreground: palette.aqua,
},
},
{
name: "reStructuredText purple",
scope: "constant.other.footnote.link.restructuredtext",
settings: {
foreground: palette.purple,
},
},
{
name: "reStructuredText red",
scope: "support.directive.restructuredtext",
settings: {
foreground: palette.red,
},
},
{
name: "reStructuredText green",
scope:
"entity.name.directive.restructuredtext, markup.raw.restructuredtext, markup.raw.inner.restructuredtext, string.other.link.title.restructuredtext",
settings: {
foreground: palette.green,
},
},
// }}}
// LaTex{{{
{
name: "LaTex delimiter",
scope:
"punctuation.definition.function.latex, punctuation.definition.function.tex, punctuation.definition.keyword.latex, constant.character.newline.tex, punctuation.definition.keyword.tex",
settings: {
foreground: palette.grey1,
},
},
{
name: "LaTex red",
scope: "support.function.be.latex",
settings: {
foreground: palette.red,
},
},
{
name: "LaTex orange",
scope:
"support.function.section.latex, keyword.control.table.cell.latex, keyword.control.table.newline.latex",
settings: {
foreground: palette.orange,
},
},
{
name: "LaTex yellow",
scope:
"support.class.latex, variable.parameter.latex, variable.parameter.function.latex, variable.parameter.definition.label.latex, constant.other.reference.label.latex",
settings: {
foreground: palette.yellow,
},
},
{
name: "LaTex purple",
scope: "keyword.control.preamble.latex",
settings: {
foreground: palette.purple,
},
},
// }}}
// Html/Xml{{{
{
name: "Html grey",
scope: "punctuation.separator.namespace.xml",
settings: {
foreground: palette.grey1,
},
},
{
name: "Html orange",
scope:
"entity.name.tag.html, entity.name.tag.xml, entity.name.tag.localname.xml",
settings: {
foreground: palette.orange,
fontStyle: "italic",
},
},
{
name: "Html yellow",
scope:
"entity.other.attribute-name.html, entity.other.attribute-name.xml, entity.other.attribute-name.localname.xml",
settings: {
foreground: palette.yellow,
},
},
{
name: "Html green",
scope:
"string.quoted.double.html, string.quoted.single.html, punctuation.definition.string.begin.html, punctuation.definition.string.end.html, punctuation.separator.key-value.html, punctuation.definition.string.begin.xml, punctuation.definition.string.end.xml, string.quoted.double.xml, string.quoted.single.xml, punctuation.definition.tag.begin.html, punctuation.definition.tag.end.html, punctuation.definition.tag.xml, meta.tag.xml, meta.tag.preprocessor.xml, meta.tag.other.html, meta.tag.block.any.html, meta.tag.inline.any.html",
settings: {
foreground: palette.green,
},
},
{
name: "Html purple",
scope: "variable.language.documentroot.xml, meta.tag.sgml.doctype.xml",
settings: {
foreground: palette.purple,
},
},
// }}}
// Proto{{{
{
name: "Proto yellow",
scope: "storage.type.proto",
settings: {
foreground: palette.yellow,
},
},
{
name: "Proto green",
scope:
"string.quoted.double.proto.syntax, string.quoted.single.proto.syntax, string.quoted.double.proto, string.quoted.single.proto",
settings: {
foreground: palette.green,
},
},
{
name: "Proto aqua",
scope: "entity.name.class.proto, entity.name.class.message.proto",
settings: {
foreground: palette.aqua,
},
},
// }}}
// CSS{{{
{
name: "CSS grey",
scope:
"punctuation.definition.entity.css, punctuation.separator.key-value.css, punctuation.terminator.rule.css, punctuation.separator.list.comma.css",
settings: {
foreground: palette.grey1,
},
},
{
name: "CSS red",
scope: "entity.other.attribute-name.class.css",
settings: {
foreground: palette.red,
},
},
{
name: "CSS orange",
scope: "keyword.other.unit",
settings: {
foreground: palette.orange,
},
},
{
name: "CSS yellow",
scope:
"entity.other.attribute-name.pseudo-class.css, entity.other.attribute-name.pseudo-element.css",
settings: {
foreground: palette.yellow,
},
},
{
name: "CSS green",
scope:
"string.quoted.single.css, string.quoted.double.css, support.constant.property-value.css, meta.property-value.css, punctuation.definition.string.begin.css, punctuation.definition.string.end.css, constant.numeric.css, support.constant.font-name.css, variable.parameter.keyframe-list.css",
settings: {
foreground: palette.green,
},
},
{
name: "CSS aqua",
scope: "support.type.property-name.css",
settings: {
foreground: palette.aqua,
},
},
{
name: "CSS blue",
scope: "support.type.vendored.property-name.css",
settings: {
foreground: palette.blue,
},
},
{
name: "CSS purple",
scope:
"entity.name.tag.css, entity.other.keyframe-offset.css, punctuation.definition.keyword.css, keyword.control.at-rule.keyframes.css, meta.selector.css",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// SASS{{{
{
name: "SASS grey",
scope:
"punctuation.definition.entity.scss, punctuation.separator.key-value.scss, punctuation.terminator.rule.scss, punctuation.separator.list.comma.scss",
settings: {
foreground: palette.grey1,
},
},
{
name: "SASS orange",
scope: "keyword.control.at-rule.keyframes.scss",
settings: {
foreground: palette.orange,
},
},
{
name: "SASS yellow",
scope:
"punctuation.definition.interpolation.begin.bracket.curly.scss, punctuation.definition.interpolation.end.bracket.curly.scss",
settings: {
foreground: palette.yellow,
},
},
{
name: "SASS green",
scope:
"punctuation.definition.string.begin.scss, punctuation.definition.string.end.scss, string.quoted.double.scss, string.quoted.single.scss, constant.character.css.sass, meta.property-value.scss",
settings: {
foreground: palette.green,
},
},
{
name: "SASS purple",
scope:
"keyword.control.at-rule.include.scss, keyword.control.at-rule.use.scss, keyword.control.at-rule.mixin.scss, keyword.control.at-rule.extend.scss, keyword.control.at-rule.import.scss",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Stylus{{{
{
name: "Stylus white",
scope: "meta.function.stylus",
settings: {
foreground: palette.fg,
},
},
{
name: "Stylus yellow",
scope: "entity.name.function.stylus",
settings: {
foreground: palette.yellow,
},
},
// }}}
// JavaScript{{{
{
name: "JavaScript white",
scope: "string.unquoted.js",
settings: {
foreground: palette.fg,
},
},
{
name: "JavaScript grey",
scope:
"punctuation.accessor.js, punctuation.separator.key-value.js, punctuation.separator.label.js, keyword.operator.accessor.js",
settings: {
foreground: palette.grey1,
},
},
{
name: "JavaScript red",
scope: "punctuation.definition.block.tag.jsdoc",
settings: {
foreground: palette.red,
},
},
{
name: "JavaScript orange",
scope: "storage.type.js, storage.type.function.arrow.js",
settings: {
foreground: palette.orange,
},
},
// }}}
// JSX{{{
{
name: "JSX white",
scope: "JSXNested",
settings: {
foreground: palette.fg,
},
},
{
name: "JSX green",
scope:
"punctuation.definition.tag.jsx, entity.other.attribute-name.jsx, punctuation.definition.tag.begin.js.jsx, punctuation.definition.tag.end.js.jsx, entity.other.attribute-name.js.jsx",
settings: {
foreground: palette.green,
},
},
// }}}
// TypeScript{{{
{
name: "TypeScript white",
scope: "entity.name.type.module.ts",
settings: {
foreground: palette.fg,
},
},
{
name: "TypeScript grey",
scope:
"keyword.operator.type.annotation.ts, punctuation.accessor.ts, punctuation.separator.key-value.ts",
settings: {
foreground: palette.grey1,
},
},
{
name: "TypeScript green",
scope:
"punctuation.definition.tag.directive.ts, entity.other.attribute-name.directive.ts",
settings: {
foreground: palette.green,
},
},
{
name: "TypeScript aqua",
scope:
"entity.name.type.ts, entity.name.type.interface.ts, entity.other.inherited-class.ts, entity.name.type.alias.ts, entity.name.type.class.ts, entity.name.type.enum.ts",
settings: {
foreground: palette.aqua,
},
},
{
name: "TypeScript orange",
scope:
"storage.type.ts, storage.type.function.arrow.ts, storage.type.type.ts",
settings: {
foreground: palette.orange,
},
},
{
name: "TypeScript blue",
scope: "entity.name.type.module.ts",
settings: {
foreground: palette.blue,
},
},
{
name: "TypeScript purple",
scope:
"keyword.control.import.ts, keyword.control.export.ts, storage.type.namespace.ts",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// TSX{{{
{
name: "TSX white",
scope: "entity.name.type.module.tsx",
settings: {
foreground: palette.fg,
},
},
{
name: "TSX grey",
scope:
"keyword.operator.type.annotation.tsx, punctuation.accessor.tsx, punctuation.separator.key-value.tsx",
settings: {
foreground: palette.grey1,
},
},
{
name: "TSX green",
scope:
"punctuation.definition.tag.directive.tsx, entity.other.attribute-name.directive.tsx, punctuation.definition.tag.begin.tsx, punctuation.definition.tag.end.tsx, entity.other.attribute-name.tsx",
settings: {
foreground: palette.green,
},
},
{
name: "TSX aqua",
scope:
"entity.name.type.tsx, entity.name.type.interface.tsx, entity.other.inherited-class.tsx, entity.name.type.alias.tsx, entity.name.type.class.tsx, entity.name.type.enum.tsx",
settings: {
foreground: palette.aqua,
},
},
{
name: "TSX blue",
scope: "entity.name.type.module.tsx",
settings: {
foreground: palette.blue,
},
},
{
name: "TSX purple",
scope:
"keyword.control.import.tsx, keyword.control.export.tsx, storage.type.namespace.tsx",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
{
name: "TSX orange",
scope:
"storage.type.tsx, storage.type.function.arrow.tsx, storage.type.type.tsx, support.class.component.tsx",
settings: {
foreground: palette.orange,
},
},
// }}}
// CoffeeScript{{{
{
name: "CoffeeScript orange",
scope: "storage.type.function.coffee",
settings: {
foreground: palette.orange,
},
},
// }}}
// PureScript{{{
{
name: "PureScript white",
scope: "meta.type-signature.purescript",
settings: {
foreground: palette.fg,
},
},
{
name: "PureScript orange",
scope:
"keyword.other.double-colon.purescript, keyword.other.arrow.purescript, keyword.other.big-arrow.purescript",
settings: {
foreground: palette.orange,
},
},
{
name: "PureScript yellow",
scope: "entity.name.function.purescript",
settings: {
foreground: palette.yellow,
},
},
{
name: "PureScript green",
scope:
"string.quoted.single.purescript, string.quoted.double.purescript, punctuation.definition.string.begin.purescript, punctuation.definition.string.end.purescript, string.quoted.triple.purescript, entity.name.type.purescript",
settings: {
foreground: palette.green,
},
},
{
name: "PureScript purple",
scope: "support.other.module.purescript",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Dart{{{
{
name: "Dart grey",
scope: "punctuation.dot.dart",
settings: {
foreground: palette.grey1,
},
},
{
name: "Dart orange",
scope: "storage.type.primitive.dart",
settings: {
foreground: palette.orange,
},
},
{
name: "Dart yellow",
scope: "support.class.dart",
settings: {
foreground: palette.yellow,
},
},
{
name: "Dart green",
scope:
"entity.name.function.dart, string.interpolated.single.dart, string.interpolated.double.dart",
settings: {
foreground: palette.green,
},
},
{
name: "Dart blue",
scope: "variable.language.dart",
settings: {
foreground: palette.blue,
},
},
{
name: "Dart purple",
scope: "keyword.other.import.dart, storage.type.annotation.dart",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Pug{{{
{
name: "Pug red",
scope: "entity.other.attribute-name.class.pug",
settings: {
foreground: palette.red,
},
},
{
name: "Pug orange",
scope: "storage.type.function.pug",
settings: {
foreground: palette.orange,
},
},
{
name: "Pug aqua",
scope: "entity.other.attribute-name.tag.pug",
settings: {
foreground: palette.aqua,
},
},
{
name: "Pug purple",
scope: "entity.name.tag.pug, storage.type.import.include.pug",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// C{{{
{
name: "C white",
scope:
"meta.function-call.c, storage.modifier.array.bracket.square.c, meta.function.definition.parameters.c",
settings: {
foreground: palette.fg,
},
},
{
name: "C grey",
scope:
"punctuation.separator.dot-access.c, constant.character.escape.line-continuation.c",
settings: {
foreground: palette.grey1,
},
},
{
name: "C red",
scope:
"keyword.control.directive.include.c, punctuation.definition.directive.c, keyword.control.directive.pragma.c, keyword.control.directive.line.c, keyword.control.directive.define.c, keyword.control.directive.conditional.c, keyword.control.directive.diagnostic.error.c, keyword.control.directive.undef.c, keyword.control.directive.conditional.ifdef.c, keyword.control.directive.endif.c, keyword.control.directive.conditional.ifndef.c, keyword.control.directive.conditional.if.c, keyword.control.directive.else.c",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "C orange",
scope: "punctuation.separator.pointer-access.c",
settings: {
foreground: palette.orange,
},
},
{
name: "C aqua",
scope: "variable.other.member.c",
settings: {
foreground: palette.aqua,
},
},
// }}}
// C++{{{
{
name: "C++ white",
scope:
"meta.function-call.cpp, storage.modifier.array.bracket.square.cpp, meta.function.definition.parameters.cpp, meta.body.function.definition.cpp",
settings: {
foreground: palette.fg,
},
},
{
name: "C++ grey",
scope:
"punctuation.separator.dot-access.cpp, constant.character.escape.line-continuation.cpp",
settings: {
foreground: palette.grey1,
},
},
{
name: "C++ red",
scope:
"keyword.control.directive.include.cpp, punctuation.definition.directive.cpp, keyword.control.directive.pragma.cpp, keyword.control.directive.line.cpp, keyword.control.directive.define.cpp, keyword.control.directive.conditional.cpp, keyword.control.directive.diagnostic.error.cpp, keyword.control.directive.undef.cpp, keyword.control.directive.conditional.ifdef.cpp, keyword.control.directive.endif.cpp, keyword.control.directive.conditional.ifndef.cpp, keyword.control.directive.conditional.if.cpp, keyword.control.directive.else.cpp, storage.type.namespace.definition.cpp, keyword.other.using.directive.cpp, storage.type.struct.cpp",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "C++ orange",
scope:
"punctuation.separator.pointer-access.cpp, punctuation.section.angle-brackets.begin.template.call.cpp, punctuation.section.angle-brackets.end.template.call.cpp",
settings: {
foreground: palette.orange,
},
},
{
name: "C++ aqua",
scope: "variable.other.member.cpp",
settings: {
foreground: palette.aqua,
},
},
// }}}
// C#{{{
{
name: "C# red",
scope: "keyword.other.using.cs",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "C# yellow",
scope:
"keyword.type.cs, constant.character.escape.cs, punctuation.definition.interpolation.begin.cs, punctuation.definition.interpolation.end.cs",
settings: {
foreground: palette.yellow,
},
},
{
name: "C# green",
scope:
"string.quoted.double.cs, string.quoted.single.cs, punctuation.definition.string.begin.cs, punctuation.definition.string.end.cs",
settings: {
foreground: palette.green,
},
},
{
name: "C# aqua",
scope: "variable.other.object.property.cs",
settings: {
foreground: palette.aqua,
},
},
{
name: "C# purple",
scope: "entity.name.type.namespace.cs",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// F#{{{
{
name: "F# white",
scope: "keyword.symbol.fsharp, constant.language.unit.fsharp",
settings: {
foreground: palette.fg,
},
},
{
name: "F# yellow",
scope: "keyword.format.specifier.fsharp, entity.name.type.fsharp",
settings: {
foreground: palette.yellow,
},
},
{
name: "F# green",
scope:
"string.quoted.double.fsharp, string.quoted.single.fsharp, punctuation.definition.string.begin.fsharp, punctuation.definition.string.end.fsharp",
settings: {
foreground: palette.green,
},
},
{
name: "F# blue",
scope: "entity.name.section.fsharp",
settings: {
foreground: palette.blue,
},
},
{
name: "F# purple",
scope: "support.function.attribute.fsharp",
settings: {
foreground: palette.purple,
},
},
// }}}
// Java{{{
{
name: "Java grey",
scope: "punctuation.separator.java, punctuation.separator.period.java",
settings: {
foreground: palette.grey1,
},
},
{
name: "Java red",
scope: "keyword.other.import.java, keyword.other.package.java",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Java orange",
scope: "storage.type.function.arrow.java, keyword.control.ternary.java",
settings: {
foreground: palette.orange,
},
},
{
name: "Java aqua",
scope: "variable.other.property.java",
settings: {
foreground: palette.aqua,
},
},
{
name: "Java purple",
scope:
"variable.language.wildcard.java, storage.modifier.import.java, storage.type.annotation.java, punctuation.definition.annotation.java, storage.modifier.package.java, entity.name.type.module.java",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Kotlin{{{
{
name: "Kotlin red",
scope: "keyword.other.import.kotlin",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Kotlin orange",
scope: "storage.type.kotlin",
settings: {
foreground: palette.orange,
},
},
{
name: "Kotlin aqua",
scope: "constant.language.kotlin",
settings: {
foreground: palette.aqua,
},
},
{
name: "Kotlin purple",
scope: "entity.name.package.kotlin, storage.type.annotation.kotlin",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Scala{{{
{
name: "Scala purple",
scope: "entity.name.package.scala",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
{
name: "Scala blue",
scope: "constant.language.scala",
settings: {
foreground: palette.blue,
},
},
{
name: "Scala aqua",
scope: "entity.name.import.scala",
settings: {
foreground: palette.aqua,
},
},
{
name: "Scala green",
scope:
"string.quoted.double.scala, string.quoted.single.scala, punctuation.definition.string.begin.scala, punctuation.definition.string.end.scala, string.quoted.double.interpolated.scala, string.quoted.single.interpolated.scala, string.quoted.triple.scala",
settings: {
foreground: palette.green,
},
},
{
name: "Scala yellow",
scope: "entity.name.class, entity.other.inherited-class.scala",
settings: {
foreground: palette.yellow,
},
},
{
name: "Scala orange",
scope: "keyword.declaration.stable.scala, keyword.other.arrow.scala",
settings: {
foreground: palette.orange,
},
},
{
name: "Scala red",
scope: "keyword.other.import.scala",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
// }}}
// Groovy{{{
{
name: "Groovy white",
scope:
"keyword.operator.navigation.groovy, meta.method.body.java, meta.definition.method.groovy, meta.definition.method.signature.java",
settings: {
foreground: palette.fg,
},
},
{
name: "Scala grey",
scope: "punctuation.separator.groovy",
settings: {
foreground: palette.grey1,
},
},
{
name: "Scala red",
scope:
"keyword.other.import.groovy, keyword.other.package.groovy, keyword.other.import.static.groovy",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Groovy orange",
scope: "storage.type.def.groovy",
settings: {
foreground: palette.orange,
},
},
{
name: "Groovy green",
scope: "variable.other.interpolated.groovy, meta.method.groovy",
settings: {
foreground: palette.green,
},
},
{
name: "Groovy aqua",
scope: "storage.modifier.import.groovy, storage.modifier.package.groovy",
settings: {
foreground: palette.aqua,
},
},
{
name: "Groovy purple",
scope: "storage.type.annotation.groovy",
settings: {
foreground: palette.purple,
},
},
// }}}
// Go{{{
{
name: "Go red",
scope: "keyword.type.go",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Go aqua",
scope: "entity.name.package.go",
settings: {
foreground: palette.aqua,
},
},
{
name: "Go purple",
scope: "keyword.import.go, keyword.package.go",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Rust{{{
{
name: "Rust white",
scope: "entity.name.type.mod.rust",
settings: {
foreground: palette.fg,
},
},
{
name: "Rust grey",
scope: "keyword.operator.path.rust, keyword.operator.member-access.rust",
settings: {
foreground: palette.grey1,
},
},
{
name: "Rust orange",
scope: "storage.type.rust",
settings: {
foreground: palette.orange,
},
},
{
name: "Rust aqua",
scope: "support.constant.core.rust",
settings: {
foreground: palette.aqua,
},
},
{
name: "Rust purple",
scope:
"meta.attribute.rust, variable.language.rust, storage.type.module.rust",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Swift{{{
{
name: "Swift white",
scope: "meta.function-call.swift, support.function.any-method.swift",
settings: {
foreground: palette.fg,
},
},
{
name: "Swift aqua",
scope: "support.variable.swift",
settings: {
foreground: palette.aqua,
},
},
// }}}
// PHP{{{
{
name: "PHP white",
scope: "keyword.operator.class.php",
settings: {
foreground: palette.fg,
},
},
{
name: "PHP orange",
scope: "storage.type.trait.php",
settings: {
foreground: palette.orange,
},
},
{
name: "PHP aqua",
scope: "constant.language.php, support.other.namespace.php",
settings: {
foreground: palette.aqua,
},
},
{
name: "PHP blue",
scope:
"storage.type.modifier.access.control.public.cpp, storage.type.modifier.access.control.private.cpp",
settings: {
foreground: palette.blue,
},
},
{
name: "PHP purple",
scope: "keyword.control.import.include.php, storage.type.php",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Python{{{
{
name: "Python white",
scope: "meta.function-call.arguments.python",
settings: {
foreground: palette.fg,
},
},
{
name: "Python grey",
scope:
"punctuation.definition.decorator.python, punctuation.separator.period.python",
settings: {
foreground: palette.grey1,
},
},
{
name: "Python aqua",
scope: "constant.language.python",
settings: {
foreground: palette.aqua,
},
},
{
name: "Python purple",
scope:
"keyword.control.import.python, keyword.control.import.from.python",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Lua{{{
{
name: "Lua aqua",
scope: "constant.language.lua",
settings: {
foreground: palette.aqua,
},
},
{
name: "Lua blue",
scope: "entity.name.class.lua",
settings: {
foreground: palette.blue,
},
},
// }}}
// Ruby{{{
{
name: "Ruby white",
scope: "meta.function.method.with-arguments.ruby",
settings: {
foreground: palette.fg,
},
},
{
name: "Ruby grey",
scope: "punctuation.separator.method.ruby",
settings: {
foreground: palette.grey1,
},
},
{
name: "Ruby orange",
scope: "keyword.control.pseudo-method.ruby, storage.type.variable.ruby",
settings: {
foreground: palette.orange,
},
},
{
name: "Ruby green",
scope: "keyword.other.special-method.ruby",
settings: {
foreground: palette.green,
},
},
{
name: "Ruby purple italic",
scope: "keyword.control.module.ruby",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
{
name: "Ruby purple regular",
scope: "punctuation.definition.constant.ruby",
settings: {
foreground: palette.purple,
},
},
{
name: "Ruby yellow",
scope:
"string.regexp.character-class.ruby,string.regexp.interpolated.ruby,punctuation.definition.character-class.ruby,string.regexp.group.ruby, punctuation.section.regexp.ruby, punctuation.definition.group.ruby",
settings: {
foreground: palette.yellow,
},
},
{
name: "Ruby blue",
scope: "variable.other.constant.ruby",
settings: {
foreground: palette.blue,
},
},
// }}}
// Haskell{{{
{
name: "Haskell orange",
scope:
"keyword.other.arrow.haskell, keyword.other.big-arrow.haskell, keyword.other.double-colon.haskell",
settings: {
foreground: palette.orange,
},
},
{
name: "Haskell yellow",
scope: "storage.type.haskell",
settings: {
foreground: palette.yellow,
},
},
{
name: "Haskell green",
scope:
"constant.other.haskell, string.quoted.double.haskell, string.quoted.single.haskell, punctuation.definition.string.begin.haskell, punctuation.definition.string.end.haskell",
settings: {
foreground: palette.green,
},
},
{
name: "Haskell blue",
scope: "entity.name.function.haskell",
settings: {
foreground: palette.blue,
},
},
{
name: "Haskell aqua",
scope: "entity.name.namespace, meta.preprocessor.haskell",
settings: {
foreground: palette.aqua,
fontStyle: "italic",
},
},
// }}}
// Julia{{{
{
name: "Julia red",
scope:
"keyword.control.import.julia, keyword.control.export.julia, keyword.other.julia",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Julia orange",
scope: "keyword.storage.modifier.julia",
settings: {
foreground: palette.orange,
},
},
{
name: "Julia aqua",
scope: "constant.language.julia",
settings: {
foreground: palette.aqua,
},
},
{
name: "Julia purple",
scope: "support.function.macro.julia",
settings: {
foreground: palette.purple,
},
},
// }}}
// Elm{{{
{
name: "Elm white",
scope: "keyword.other.period.elm",
settings: {
foreground: palette.fg,
},
},
{
name: "Elm yellow",
scope: "storage.type.elm",
settings: {
foreground: palette.yellow,
},
},
// }}}
// R{{{
{
name: "R orange",
scope: "keyword.other.r",
settings: {
foreground: palette.orange,
},
},
{
name: "R green",
scope: "entity.name.function.r, variable.function.r",
settings: {
foreground: palette.green,
},
},
{
name: "R aqua",
scope: "constant.language.r",
settings: {
foreground: palette.aqua,
},
},
{
name: "R purple",
scope: "entity.namespace.r",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Erlang{{{
{
name: "Erlang grey",
scope:
"punctuation.separator.module-function.erlang, punctuation.section.directive.begin.erlang",
settings: {
foreground: palette.grey1,
},
},
{
name: "Erlang red",
scope:
"keyword.control.directive.erlang, keyword.control.directive.define.erlang",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Erlang yellow",
scope: "entity.name.type.class.module.erlang",
settings: {
foreground: palette.yellow,
},
},
{
name: "Erlang green",
scope:
"string.quoted.double.erlang, string.quoted.single.erlang, punctuation.definition.string.begin.erlang, punctuation.definition.string.end.erlang",
settings: {
foreground: palette.green,
},
},
{
name: "Erlang purple",
scope:
"keyword.control.directive.export.erlang, keyword.control.directive.module.erlang, keyword.control.directive.import.erlang, keyword.control.directive.behaviour.erlang",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// Elixir{{{
{
name: "Elixir aqua",
scope:
"variable.other.readwrite.module.elixir, punctuation.definition.variable.elixir",
settings: {
foreground: palette.aqua,
},
},
{
name: "Elixir blue",
scope: "constant.language.elixir",
settings: {
foreground: palette.blue,
},
},
{
name: "Elixir purple",
scope: "keyword.control.module.elixir",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
// }}}
// OCaml{{{
{
name: "OCaml white",
scope: "entity.name.type.value-signature.ocaml",
settings: {
foreground: palette.fg,
},
},
{
name: "OCaml orange",
scope: "keyword.other.ocaml",
settings: {
foreground: palette.orange,
},
},
{
name: "OCaml aqua",
scope: "constant.language.variant.ocaml",
settings: {
foreground: palette.aqua,
},
},
// }}}
// Perl{{{
{
name: "Perl red",
scope: "storage.type.sub.perl, storage.type.declare.routine.perl",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
// }}}
// Common Lisp{{{
{
name: "Lisp white",
scope: "meta.function.lisp",
settings: {
foreground: palette.fg,
},
},
{
name: "Lisp red",
scope: "storage.type.function-type.lisp",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Lisp green",
scope: "keyword.constant.lisp",
settings: {
foreground: palette.green,
},
},
{
name: "Lisp aqua",
scope: "entity.name.function.lisp",
settings: {
foreground: palette.aqua,
},
},
// }}}
// Clojure{{{
{
name: "Clojure green",
scope:
"constant.keyword.clojure, support.variable.clojure, meta.definition.variable.clojure",
settings: {
foreground: palette.green,
},
},
{
name: "Clojure purple",
scope: "entity.global.clojure",
settings: {
foreground: palette.purple,
fontStyle: "italic",
},
},
{
name: "Clojure blue",
scope: "entity.name.function.clojure",
settings: {
foreground: palette.blue,
},
},
// }}}
// Shell{{{
{
name: "Shell white",
scope: "meta.scope.if-block.shell, meta.scope.group.shell",
settings: {
foreground: palette.fg,
},
},
{
name: "Shell yellow",
scope: "support.function.builtin.shell, entity.name.function.shell",
settings: {
foreground: palette.yellow,
},
},
{
name: "Shell green",
scope:
"string.quoted.double.shell, string.quoted.single.shell, punctuation.definition.string.begin.shell, punctuation.definition.string.end.shell, string.unquoted.heredoc.shell",
settings: {
foreground: palette.green,
},
},
{
name: "Shell purple",
scope:
"keyword.control.heredoc-token.shell, variable.other.normal.shell, punctuation.definition.variable.shell, variable.other.special.shell, variable.other.positional.shell, variable.other.bracket.shell",
settings: {
foreground: palette.purple,
},
},
// }}}
// Fish{{{
{
name: "Fish red",
scope: "support.function.builtin.fish",
settings: {
foreground: palette.red,
fontStyle: "italic",
},
},
{
name: "Fish orange",
scope: "support.function.unix.fish",
settings: {
foreground: palette.orange,
},
},
{
name: "Fish blue",
scope:
"variable.other.normal.fish, punctuation.definition.variable.fish, variable.other.fixed.fish, variable.other.special.fish",
settings: {
foreground: palette.blue,
},
},
{
name: "Fish green",
scope:
"string.quoted.double.fish, punctuation.definition.string.end.fish, punctuation.definition.string.begin.fish, string.quoted.single.fish",
settings: {
foreground: palette.green,
},
},
{
name: "Fish purple",
scope: "constant.character.escape.single.fish",
settings: {
foreground: palette.purple,
},
},
// }}}
// PowerShell{{{
{
name: "PowerShell grey",
scope: "punctuation.definition.variable.powershell",
settings: {
foreground: palette.grey1,
},
},
{
name: "PowerShell yellow",
scope:
"entity.name.function.powershell, support.function.attribute.powershell, support.function.powershell",
settings: {
foreground: palette.yellow,
},
},
{
name: "PowerShell green",
scope:
"string.quoted.single.powershell, string.quoted.double.powershell, punctuation.definition.string.begin.powershell, punctuation.definition.string.end.powershell, string.quoted.double.heredoc.powershell",
settings: {
foreground: palette.green,
},
},
{
name: "PowerShell aqua",
scope: "variable.other.member.powershell",
settings: {
foreground: palette.aqua,
},
},
// }}}
// GraphQL{{{
{
name: "GraphQL white",
scope: "string.unquoted.alias.graphql",
settings: {
foreground: palette.fg,
},
},
{
name: "GraphQL red",
scope: "keyword.type.graphql",
settings: {
foreground: palette.red,
},
},
{
name: "GraphQL purple",
scope: "entity.name.fragment.graphql",
settings: {
foreground: palette.purple,
},
},
// }}}
// {{{Makefile
{
name: "Makefile orange",
scope: "entity.name.function.target.makefile",
settings: {
foreground: palette.orange,
},
},
{
name: "Makefile yellow",
scope: "variable.other.makefile",
settings: {
foreground: palette.yellow,
},
},
{
name: "Makefile green",
scope: "meta.scope.prerequisites.makefile",
settings: {
foreground: palette.green,
},
},
// }}}
// {{{CMake
{
name: "CMake green",
scope: "string.source.cmake",
settings: {
foreground: palette.green,
},
},
{
name: "CMake aqua",
scope: "entity.source.cmake",
settings: {
foreground: palette.aqua,
},
},
{
name: "CMake purple",
scope: "storage.source.cmake",
settings: {
foreground: palette.purple,
},
},
// }}}
// {{{VimL
{
name: "VimL grey",
scope: "punctuation.definition.map.viml",
settings: {
foreground: palette.grey1,
},
},
{
name: "VimL orange",
scope: "storage.type.map.viml",
settings: {
foreground: palette.orange,
},
},
{
name: "VimL green",
scope: "constant.character.map.viml, constant.character.map.key.viml",
settings: {
foreground: palette.green,
},
},
{
name: "VimL blue",
scope: "constant.character.map.special.viml",
settings: {
foreground: palette.blue,
},
},
// }}}
// {{{Tmux
{
name: "Tmux green",
scope: "constant.language.tmux, constant.numeric.tmux",
settings: {
foreground: palette.green,
},
},
// }}}
// {{{Dockerfile
{
name: "Dockerfile orange",
scope: "entity.name.function.package-manager.dockerfile",
settings: {
foreground: palette.orange,
},
},
{
name: "Dockerfile yellow",
scope: "keyword.operator.flag.dockerfile",
settings: {
foreground: palette.yellow,
},
},
{
name: "Dockerfile green",
scope: "string.quoted.double.dockerfile, string.quoted.single.dockerfile",
settings: {
foreground: palette.green,
},
},
{
name: "Dockerfile aqua",
scope: "constant.character.escape.dockerfile",
settings: {
foreground: palette.aqua,
},
},
{
name: "Dockerfile purple",
scope:
"entity.name.type.base-image.dockerfile, entity.name.image.dockerfile",
settings: {
foreground: palette.purple,
},
},
// }}}
// Diff{{{
{
name: "Diff grey",
scope: "punctuation.definition.separator.diff",
settings: {
foreground: palette.grey1,
},
},
{
name: "Diff red",
scope: "markup.deleted.diff, punctuation.definition.deleted.diff",
settings: {
foreground: palette.red,
},
},
{
name: "Diff orange",
scope: "meta.diff.range.context, punctuation.definition.range.diff",
settings: {
foreground: palette.orange,
},
},
{
name: "Diff yellow",
scope: "meta.diff.header.from-file",
settings: {
foreground: palette.yellow,
},
},
{
name: "Diff green",
scope: "markup.inserted.diff, punctuation.definition.inserted.diff",
settings: {
foreground: palette.green,
},
},
{
name: "Diff blue",
scope: "markup.changed.diff, punctuation.definition.changed.diff",
settings: {
foreground: palette.blue,
},
},
{
name: "Diff purple",
scope: "punctuation.definition.from-file.diff",
settings: {
foreground: palette.purple,
},
},
// }}}
// {{{Git
{
name: "Git red",
scope:
"entity.name.section.group-title.ini, punctuation.definition.entity.ini",
settings: {
foreground: palette.red,
},
},
{
name: "Git orange",
scope: "punctuation.separator.key-value.ini",
settings: {
foreground: palette.orange,
},
},
{
name: "Git green",
scope:
"string.quoted.double.ini, string.quoted.single.ini, punctuation.definition.string.begin.ini, punctuation.definition.string.end.ini",
settings: {
foreground: palette.green,
},
},
{
name: "Git aqua",
scope: "keyword.other.definition.ini",
settings: {
foreground: palette.aqua,
},
},
// }}}
// SQL{{{
{
name: "SQL yellow",
scope: "support.function.aggregate.sql",
settings: {
foreground: palette.yellow,
},
},
{
name: "SQL green",
scope:
"string.quoted.single.sql, punctuation.definition.string.end.sql, punctuation.definition.string.begin.sql, string.quoted.double.sql",
settings: {
foreground: palette.green,
},
},
// }}}
// GraphQL{{{
{
name: "GraphQL yellow",
scope: "support.type.graphql",
settings: {
foreground: palette.yellow,
},
},
{
name: "GraphQL blue",
scope: "variable.parameter.graphql",
settings: {
foreground: palette.blue,
},
},
{
name: "GraphQL aqua",
scope: "constant.character.enum.graphql",
settings: {
foreground: palette.aqua,
},
},
// }}}
// JSON{{{
{
name: "JSON grey",
scope:
"punctuation.support.type.property-name.begin.json, punctuation.support.type.property-name.end.json, punctuation.separator.dictionary.key-value.json, punctuation.definition.string.begin.json, punctuation.definition.string.end.json, punctuation.separator.dictionary.pair.json, punctuation.separator.array.json",
settings: {
foreground: palette.grey1,
},
},
{
name: "JSON orange",
scope: "support.type.property-name.json",
settings: {
foreground: palette.orange,
},
},
{
name: "JSON green",
scope: "string.quoted.double.json",
settings: {
foreground: palette.green,
},
},
// }}}
// YAML{{{
{
name: "YAML grey",
scope: "punctuation.separator.key-value.mapping.yaml",
settings: {
foreground: palette.grey1,
},
},
{
name: "YAML green",
scope:
"string.unquoted.plain.out.yaml, string.quoted.single.yaml, string.quoted.double.yaml, punctuation.definition.string.begin.yaml, punctuation.definition.string.end.yaml, string.unquoted.plain.in.yaml, string.unquoted.block.yaml",
settings: {
foreground: palette.green,
},
},
{
name: "YAML aqua",
scope:
"punctuation.definition.anchor.yaml, punctuation.definition.block.sequence.item.yaml",
settings: {
foreground: palette.aqua,
},
},
// }}}
// TOML{{{
{
name: "TOML orange",
scope: "keyword.key.toml",
settings: {
foreground: palette.orange,
},
},
{
name: "TOML green",
scope:
"string.quoted.single.basic.line.toml, string.quoted.single.literal.line.toml, punctuation.definition.keyValuePair.toml",
settings: {
foreground: palette.green,
},
},
{
name: "TOML blue",
scope: "constant.other.boolean.toml",
settings: {
foreground: palette.blue,
},
},
{
name: "TOML purple",
scope:
"entity.other.attribute-name.table.toml, punctuation.definition.table.toml, entity.other.attribute-name.table.array.toml, punctuation.definition.table.array.toml",
settings: {
foreground: palette.purple,
},
},
// }}}
];
if (italicComments) {
syntax.push({
name: "Comment",
scope: "comment, string.comment, punctuation.definition.comment",
settings: {
foreground: palette.grey1,
fontStyle: "italic",
},
});
} else {
syntax.push({
name: "Comment",
scope: "comment, string.comment, punctuation.definition.comment",
settings: {
foreground: palette.grey1,
},
});
}
return syntax;
} | the_stack |
import { adoptACLDefault, getProspectiveHolder, makeACLGraphbyCombo, sameACL } from './acl'
import { graph, NamedNode, UpdateManager } from 'rdflib'
import { AccessGroups } from './access-groups'
import { DataBrowserContext } from 'pane-registry'
import { shortNameForFolder } from './acl-control'
import * as utils from '../utils'
import * as debug from '../debug'
/**
* Rendered HTML component used in the databrowser's Sharing pane.
*/
export class AccessController {
public mainCombo: AccessGroups
public defaultsCombo: AccessGroups | null
private readonly isContainer: boolean
private defaultsDiffer: boolean
private readonly rootElement: HTMLElement
private isUsingDefaults: boolean
constructor (
public subject: NamedNode,
public noun: string,
public context: DataBrowserContext,
private statusElement: HTMLElement,
public classes: Record<string, string>,
public targetIsProtected: boolean,
private targetDoc: NamedNode,
private targetACLDoc: NamedNode,
private defaultHolder: NamedNode | null,
private defaultACLDoc: NamedNode | null,
private prospectiveDefaultHolder: NamedNode | undefined,
public store,
public dom
) {
this.rootElement = dom.createElement('div')
this.rootElement.classList.add(classes.aclGroupContent)
this.isContainer = targetDoc.uri.slice(-1) === '/' // Give default for all directories
if (defaultHolder && defaultACLDoc) {
this.isUsingDefaults = true
const aclDefaultStore = adoptACLDefault(this.targetDoc, targetACLDoc, defaultHolder, defaultACLDoc)
this.mainCombo = new AccessGroups(targetDoc, targetACLDoc, this, aclDefaultStore, { defaults: this.isContainer })
this.defaultsCombo = null
this.defaultsDiffer = false
} else {
this.isUsingDefaults = false
this.mainCombo = new AccessGroups(targetDoc, targetACLDoc, this, store)
this.defaultsCombo = new AccessGroups(targetDoc, targetACLDoc, this, store, { defaults: this.isContainer })
this.defaultsDiffer = !sameACL(this.mainCombo.aclMap, this.defaultsCombo.aclMap)
}
}
public get isEditable (): boolean {
return !this.isUsingDefaults
}
public render (): HTMLElement {
this.rootElement.innerHTML = ''
if (this.isUsingDefaults) {
this.renderStatus(`The sharing for this ${this.noun} is the default for folder `)
if (this.defaultHolder) {
const defaultHolderLink = this.statusElement.appendChild(this.dom.createElement('a'))
defaultHolderLink.href = this.defaultHolder.uri
defaultHolderLink.innerText = shortNameForFolder(this.defaultHolder)
}
} else if (!this.defaultsDiffer && this.isContainer) {
this.renderStatus('This is also the default for things in this folder.')
} else {
this.renderStatus('')
}
this.rootElement.appendChild(this.mainCombo.render())
if (this.defaultsCombo && this.defaultsDiffer) {
this.rootElement.appendChild(this.renderRemoveDefaultsController())
this.rootElement.appendChild(this.defaultsCombo.render())
} else if (this.isEditable && this.isContainer) {
this.rootElement.appendChild(this.renderAddDefaultsController())
}
if (!this.targetIsProtected && this.isUsingDefaults) {
this.rootElement.appendChild(this.renderAddAclsController())
} else if (!this.targetIsProtected) {
this.rootElement.appendChild(this.renderRemoveAclsController())
}
return this.rootElement
}
private renderRemoveAclsController (): HTMLElement {
const useDefaultButton = this.dom.createElement('button')
useDefaultButton.innerText = `Remove custom sharing settings for this ${this.noun} -- just use default${this.prospectiveDefaultHolder ? ` for ${utils.label(this.prospectiveDefaultHolder)}` : ''}`
useDefaultButton.classList.add(this.classes.bigButton)
useDefaultButton.addEventListener('click', () => this.removeAcls()
.then(() => this.render())
.catch(error => this.renderStatus(error)))
return useDefaultButton
}
private renderAddAclsController (): HTMLElement {
const addAclButton = this.dom.createElement('button')
addAclButton.innerText = `Set specific sharing for this ${this.noun}`
addAclButton.classList.add(this.classes.bigButton)
addAclButton.addEventListener('click', () => this.addAcls()
.then(() => this.render())
.catch(error => this.renderStatus(error)))
return addAclButton
}
private renderAddDefaultsController (): HTMLElement {
const containerElement = this.dom.createElement('div')
containerElement.classList.add(this.classes.defaultsController)
const noticeElement = containerElement.appendChild(this.dom.createElement('div'))
noticeElement.innerText = 'Sharing for things within the folder currently tracks sharing for the folder.'
noticeElement.classList.add(this.classes.defaultsControllerNotice)
const button = containerElement.appendChild(this.dom.createElement('button'))
button.innerText = 'Set the sharing of folder contents separately from the sharing for the folder'
button.classList.add(this.classes.bigButton)
button.addEventListener('click', () => this.addDefaults()
.then(() => this.render()))
return containerElement
}
private renderRemoveDefaultsController (): HTMLElement {
const containerElement = this.dom.createElement('div')
containerElement.classList.add(this.classes.defaultsController)
const noticeElement = containerElement.appendChild(this.dom.createElement('div'))
noticeElement.innerText = 'Access to things within this folder:'
noticeElement.classList.add(this.classes.defaultsControllerNotice)
const button = containerElement.appendChild(this.dom.createElement('button'))
button.innerText = 'Set default for folder contents to just track the sharing for the folder'
button.classList.add(this.classes.bigButton)
button.addEventListener('click', () => this.removeDefaults()
.then(() => this.render())
.catch(error => this.renderStatus(error)))
return containerElement
}
public renderTemporaryStatus (message: string): void {
// @@ TODO Introduce better system for error notification to user https://github.com/solid/mashlib/issues/87
this.statusElement.classList.add(this.classes.aclControlBoxStatusRevealed)
this.statusElement.innerText = message
this.statusElement.classList.add(this.classes.temporaryStatusInit)
setTimeout(() => {
this.statusElement.classList.add(this.classes.temporaryStatusEnd)
})
setTimeout(() => {
this.statusElement.innerText = ''
}, 5000)
}
public renderStatus (message: string): void {
// @@ TODO Introduce better system for error notification to user https://github.com/solid/mashlib/issues/87
this.statusElement.classList.toggle(this.classes.aclControlBoxStatusRevealed, !!message)
this.statusElement.innerText = message
}
private async addAcls (): Promise<void> {
if (!this.defaultHolder || !this.defaultACLDoc) {
const message = 'Unable to find defaults to copy'
debug.error(message)
return Promise.reject(message)
}
const aclGraph = adoptACLDefault(this.targetDoc, this.targetACLDoc, this.defaultHolder, this.defaultACLDoc)
aclGraph.statements.forEach(st => this.store.add(st.subject, st.predicate, st.object, this.targetACLDoc))
try {
await this.store.fetcher.putBack(this.targetACLDoc)
this.isUsingDefaults = false
return Promise.resolve()
} catch (error) {
const message = ` Error writing back access control file! ${error}`
debug.error(message)
return Promise.reject(message)
}
}
private async addDefaults (): Promise<void> {
this.defaultsCombo = new AccessGroups(this.targetDoc, this.targetACLDoc, this, this.store, { defaults: true })
this.defaultsDiffer = true
}
private async removeAcls (): Promise<void> {
try {
await this.store.fetcher.delete(this.targetACLDoc.uri, {})
this.isUsingDefaults = true
try {
this.prospectiveDefaultHolder = await getProspectiveHolder(this.targetDoc.uri)
} catch (error) {
// No need to show this error in status, but good to warn about it in console
debug.warn(error)
}
} catch (error) {
const message = `Error deleting access control file: ${this.targetACLDoc}: ${error}`
debug.error(message)
return Promise.reject(message)
}
}
private async removeDefaults (): Promise<void> {
const fallbackCombo = this.defaultsCombo
try {
this.defaultsCombo = null
this.defaultsDiffer = false
await this.save()
} catch (error) {
this.defaultsCombo = fallbackCombo
this.defaultsDiffer = true
debug.error(error)
return Promise.reject(error)
}
}
public save (): Promise<void> {
// build graph
const newAClGraph = graph()
if (!this.isContainer) {
makeACLGraphbyCombo(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true)
} else if (this.defaultsCombo && this.defaultsDiffer) {
// Pair of controls
makeACLGraphbyCombo(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true)
makeACLGraphbyCombo(newAClGraph, this.targetDoc, this.defaultsCombo.byCombo, this.targetACLDoc, false, true)
} else {
// Linked controls
makeACLGraphbyCombo(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true, true)
}
const updater = newAClGraph.updater || new UpdateManager(newAClGraph)
// save ACL resource
return new Promise((resolve, reject) => {
updater.put(
this.targetACLDoc,
newAClGraph.statementsMatching(undefined, undefined, undefined, this.targetACLDoc),
'text/turtle',
(uri, ok, message) => {
if (!ok) {
return reject(new Error(`ACL file save failed: ${message}`))
}
this.store.fetcher.unload(this.targetACLDoc)
this.store.add(newAClGraph.statements)
this.store.fetcher.requested[this.targetACLDoc.uri] = 'done' // missing: save headers
this.mainCombo.store = this.store
if (this.defaultsCombo) {
this.defaultsCombo.store = this.store
}
this.defaultsDiffer = !!this.defaultsCombo && !sameACL(this.mainCombo.aclMap, this.defaultsCombo.aclMap)
debug.log('ACL modification: success!')
resolve()
}
)
})
}
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec } from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Alert } from '../model/models';
import { AlertInput } from '../model/models';
import { AlertStatusResponse } from '../model/models';
import { ApisResponse } from '../model/models';
import { Application } from '../model/models';
import { ApplicationInput } from '../model/models';
import { ApplicationType } from '../model/models';
import { ApplicationsResponse } from '../model/models';
import { CountAnalytics, DateHistoAnalytics, GroupByAnalytics } from '../model/models';
import { ErrorResponse } from '../model/models';
import { Hook } from '../model/models';
import { Log } from '../model/models';
import { LogsResponse } from '../model/models';
import { Member } from '../model/models';
import { MemberInput } from '../model/models';
import { MembersResponse } from '../model/models';
import { NotificationInput } from '../model/models';
import { ReferenceMetadata } from '../model/models';
import { ReferenceMetadataInput } from '../model/models';
import { ReferenceMetadataResponse } from '../model/models';
import { TransferOwnershipInput } from '../model/models';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
export interface CreateApplicationRequestParams {
/** Use to create an application. */
applicationInput?: ApplicationInput;
}
export interface CreateApplicationAlertRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to create a post. */
alertInput?: AlertInput;
}
export interface CreateApplicationMemberRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to create a member. */
memberInput?: MemberInput;
}
export interface CreateApplicationMetadataRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to create a metadata. */
referenceMetadataInput?: ReferenceMetadataInput;
}
export interface DeleteApplicationAlertRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of an alert. */
alertId: string;
}
export interface DeleteApplicationByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface DeleteApplicationMemberRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of a member. */
memberId: string;
}
export interface DeleteApplicationMetadataRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of an application metadata. */
metadataId: string;
}
export interface ExportApplicationLogsByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** Lower bound of timestamp for filtering. */
from?: number;
/** Upper bound of timestamp for filtering. Must be greater than *from* query param. */
to?: number;
/** Query used for filtering. */
query?: string;
/** Field used for filtering. **required** when type is **GROUP_BY**. */
field?: string;
/** Order used to sort the result list. */
order?: 'ASC' | 'DESC';
}
export interface GetAlertsByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationAlertStatusRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationAnalyticsRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** Lower bound of timestamp for filtering. */
from?: number;
/** Upper bound of timestamp for filtering. Must be greater than *from* query param. */
to?: number;
/** Interval for time search. Must be >= 1 000 and <= 1 000 000 000. */
interval?: number;
/** Query used for filtering. */
query?: string;
/** Field used for filtering. **required** when type is **GROUP_BY**. */
field?: string;
/** Type of analytics that is expected : - GROUP_BY : Used to group total hits by a specific field (Application, Status, Path, ...).\\ Query params : - from - to - interval - query - field - order - ranges - DATE_HISTO : Used to retrieve total hits per range of time, on a specific time interval.\\ Query params : - from - to - interval - query - aggs - COUNT : Used to retrieve total hits, on a specific time interval.\\ Query params : - from - to - interval - query - STATS : Used to retrieve stats data, on a specific time interval.\\ Query params : - from - to - query */
type?: 'GROUP_BY' | 'DATE_HISTO' | 'COUNT' | 'STATS';
/** Used with GROUP_BY type only. A semicolon separated list of \"from:to\" elements. **_/!\\\\ Different from *from* and *to* query params** */
ranges?: string;
/** Used with DATE_HISTO type only. A semicolon separated list of \"type:field\" elements. **_/!\\\\ Different from *type* and *field* query params**\\ Type can be **FIELD**, **AVG**, **MIN**, **MAX** */
aggs?: string;
/** Used with GROUP_BY type only. A colon separated list of \"type:field\" elements. **_/!\\\\ Different from *type* and *field* query params**\\ By default, sort is ASC. If *type* starts with \'-\', the order sort is DESC.\\ Currently, only **AVG** is supported. */
order?: string;
}
export interface GetApplicationBackgroundByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationLogByApplicationIdAndLogIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of a log. */
logId: string;
/** Used to select the right index */
timestamp?: number;
}
export interface GetApplicationLogsRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** Lower bound of timestamp for filtering. */
from?: number;
/** Upper bound of timestamp for filtering. Must be greater than *from* query param. */
to?: number;
/** Query used for filtering. */
query?: string;
/** Field used for filtering. **required** when type is **GROUP_BY**. */
field?: string;
/** Order used to sort the result list. */
order?: 'ASC' | 'DESC';
}
export interface GetApplicationMemberByApplicationIdAndMemberIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of a member. */
memberId: string;
}
export interface GetApplicationMetadataByApplicationIdAndMetadataIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of an application metadata. */
metadataId: string;
}
export interface GetApplicationPictureByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationTypeRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetApplicationsRequestParams {
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** If true, only return applications with APPLICATION_SUBSCRIPTION[CREATE] permission. */
forSubscription?: boolean;
/** By default, sort is ASC. If *field* starts with \'-\', the order sort is DESC.\\ Currently, only **name** and **nbSubscriptions** are supported. */
order?: string;
}
export interface GetMembersByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
}
export interface GetMetadataByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
}
export interface GetNotificationsByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface GetSubscriberApisByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
/** The page number for pagination. */
page?: number;
/** The number of items per page for pagination. If the size is 0, the response contains only metadata and returns the values as for a non-paged resource. If the size is -1, the response contains all datas. */
size?: number;
/** status of subscription. */
statuses?: Array<'ACCEPTED' | 'CLOSED' | 'PAUSED' | 'PENDING' | 'REJECTED'>;
}
export interface RenewApplicationSecretRequestParams {
/** Id of an application. */
applicationId: string;
}
export interface TransferMemberOwnershipRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to transfer ownership of an application. */
transferOwnershipInput?: TransferOwnershipInput;
}
export interface UpdateAlertRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of an alert. */
alertId: string;
/** Use to update an application alert. */
alertInput?: AlertInput;
}
export interface UpdateApplicationByApplicationIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to update an application. */
application?: Application;
}
export interface UpdateApplicationMemberByApplicationIdAndMemberIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of a member. */
memberId: string;
/** Use to update a member. */
memberInput?: MemberInput;
}
export interface UpdateApplicationMetadataByApplicationIdAndMetadataIdRequestParams {
/** Id of an application. */
applicationId: string;
/** Id of an application metadata. */
metadataId: string;
/** Use to update a metadata. */
referenceMetadataInput?: ReferenceMetadataInput;
}
export interface UpdateApplicationNotificationsRequestParams {
/** Id of an application. */
applicationId: string;
/** Use to update application notifications. */
notificationInput?: NotificationInput;
}
@Injectable({
providedIn: 'root'
})
export class ApplicationService {
protected basePath = 'http://localhost:8083/portal/environments/DEFAULT';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key,
(value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* Create an application
* Create an application. User must have MANAGEMENT_APPLICATION[CREATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createApplication(requestParameters: CreateApplicationRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Application>;
public createApplication(requestParameters: CreateApplicationRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Application>>;
public createApplication(requestParameters: CreateApplicationRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Application>>;
public createApplication(requestParameters: CreateApplicationRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationInput = requestParameters.applicationInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<Application>(`${this.configuration.basePath}/applications`,
applicationInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Create an application alert
* Create an application alert. User must have the APPLICATION_ALERT[CREATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createApplicationAlert(requestParameters: CreateApplicationAlertRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Alert>;
public createApplicationAlert(requestParameters: CreateApplicationAlertRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Alert>>;
public createApplicationAlert(requestParameters: CreateApplicationAlertRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Alert>>;
public createApplicationAlert(requestParameters: CreateApplicationAlertRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling createApplicationAlert.');
}
const alertInput = requestParameters.alertInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<Alert>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/alerts`,
alertInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Create an application member
* Create an application member. User must have the APPLICATION_MEMBER[CREATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createApplicationMember(requestParameters: CreateApplicationMemberRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Member>;
public createApplicationMember(requestParameters: CreateApplicationMemberRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Member>>;
public createApplicationMember(requestParameters: CreateApplicationMemberRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Member>>;
public createApplicationMember(requestParameters: CreateApplicationMemberRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling createApplicationMember.');
}
const memberInput = requestParameters.memberInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<Member>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members`,
memberInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Create an application metadata
* Create an application metadata. User must have the APPLICATION_METADATA[CREATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createApplicationMetadata(requestParameters: CreateApplicationMetadataRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ReferenceMetadata>;
public createApplicationMetadata(requestParameters: CreateApplicationMetadataRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ReferenceMetadata>>;
public createApplicationMetadata(requestParameters: CreateApplicationMetadataRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ReferenceMetadata>>;
public createApplicationMetadata(requestParameters: CreateApplicationMetadataRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling createApplicationMetadata.');
}
const referenceMetadataInput = requestParameters.referenceMetadataInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<ReferenceMetadata>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/metadata`,
referenceMetadataInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Delete a alert for an Application
* Delete a alert for an Application. The current user must have APPLICATION_ALERT[DELETE] permission to delete a alert.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteApplicationAlert(requestParameters: DeleteApplicationAlertRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public deleteApplicationAlert(requestParameters: DeleteApplicationAlertRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public deleteApplicationAlert(requestParameters: DeleteApplicationAlertRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public deleteApplicationAlert(requestParameters: DeleteApplicationAlertRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling deleteApplicationAlert.');
}
const alertId = requestParameters.alertId;
if (alertId === null || alertId === undefined) {
throw new Error('Required parameter alertId was null or undefined when calling deleteApplicationAlert.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.delete<any>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/alerts/${encodeURIComponent(String(alertId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Delete an application
* Delete an application. User must have the APPLICATION_DEFINITION[DELETE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteApplicationByApplicationId(requestParameters: DeleteApplicationByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public deleteApplicationByApplicationId(requestParameters: DeleteApplicationByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public deleteApplicationByApplicationId(requestParameters: DeleteApplicationByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public deleteApplicationByApplicationId(requestParameters: DeleteApplicationByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling deleteApplicationByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.delete<any>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Remove an application member
* Remove an application member. User must have the APPLICATION_MEMBER[DELETE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteApplicationMember(requestParameters: DeleteApplicationMemberRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public deleteApplicationMember(requestParameters: DeleteApplicationMemberRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public deleteApplicationMember(requestParameters: DeleteApplicationMemberRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public deleteApplicationMember(requestParameters: DeleteApplicationMemberRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling deleteApplicationMember.');
}
const memberId = requestParameters.memberId;
if (memberId === null || memberId === undefined) {
throw new Error('Required parameter memberId was null or undefined when calling deleteApplicationMember.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.delete<any>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members/${encodeURIComponent(String(memberId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Remove an application metadata
* Remove an application metadata. User must have the APPLICATION_METADATA[DELETE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteApplicationMetadata(requestParameters: DeleteApplicationMetadataRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public deleteApplicationMetadata(requestParameters: DeleteApplicationMetadataRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public deleteApplicationMetadata(requestParameters: DeleteApplicationMetadataRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public deleteApplicationMetadata(requestParameters: DeleteApplicationMetadataRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling deleteApplicationMetadata.');
}
const metadataId = requestParameters.metadataId;
if (metadataId === null || metadataId === undefined) {
throw new Error('Required parameter metadataId was null or undefined when calling deleteApplicationMetadata.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.delete<any>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/metadata/${encodeURIComponent(String(metadataId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Export application logs as CSV
* Export application logs as CSV. User must have the APPLICATION_LOG[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public exportApplicationLogsByApplicationId(requestParameters: ExportApplicationLogsByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json'}): Observable<string>;
public exportApplicationLogsByApplicationId(requestParameters: ExportApplicationLogsByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json'}): Observable<HttpResponse<string>>;
public exportApplicationLogsByApplicationId(requestParameters: ExportApplicationLogsByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json'}): Observable<HttpEvent<string>>;
public exportApplicationLogsByApplicationId(requestParameters: ExportApplicationLogsByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'text/plain' | 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling exportApplicationLogsByApplicationId.');
}
const page = requestParameters.page;
const size = requestParameters.size;
const from = requestParameters.from;
const to = requestParameters.to;
const query = requestParameters.query;
const field = requestParameters.field;
const order = requestParameters.order;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (from !== undefined && from !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>from, 'from');
}
if (to !== undefined && to !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>to, 'to');
}
if (query !== undefined && query !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>query, 'query');
}
if (field !== undefined && field !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>field, 'field');
}
if (order !== undefined && order !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>order, 'order');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'text/plain',
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<string>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/logs/_export`,
null,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get application alerts
* Get application alerts. User must have APPLICATION_ALERT[READ] permission to get alerts.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getAlertsByApplicationId(requestParameters: GetAlertsByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<Alert>>;
public getAlertsByApplicationId(requestParameters: GetAlertsByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<Alert>>>;
public getAlertsByApplicationId(requestParameters: GetAlertsByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<Alert>>>;
public getAlertsByApplicationId(requestParameters: GetAlertsByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getAlertsByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Array<Alert>>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/alerts`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get application alert status
* Get application alert status. User must have APPLICATION_ALERT[READ] permission to get alert status.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationAlertStatus(requestParameters: GetApplicationAlertStatusRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<AlertStatusResponse>;
public getApplicationAlertStatus(requestParameters: GetApplicationAlertStatusRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<AlertStatusResponse>>;
public getApplicationAlertStatus(requestParameters: GetApplicationAlertStatusRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<AlertStatusResponse>>;
public getApplicationAlertStatus(requestParameters: GetApplicationAlertStatusRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationAlertStatus.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<AlertStatusResponse>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/alerts/status`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get Application analytics
* Get the application analytics. User must have the APPLICATION_ANALYTICS[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationAnalytics(requestParameters: GetApplicationAnalyticsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<DateHistoAnalytics | GroupByAnalytics | CountAnalytics>;
public getApplicationAnalytics(requestParameters: GetApplicationAnalyticsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<DateHistoAnalytics | GroupByAnalytics | CountAnalytics>>;
public getApplicationAnalytics(requestParameters: GetApplicationAnalyticsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<DateHistoAnalytics | GroupByAnalytics | CountAnalytics>>;
public getApplicationAnalytics(requestParameters: GetApplicationAnalyticsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationAnalytics.');
}
const page = requestParameters.page;
const size = requestParameters.size;
const from = requestParameters.from;
const to = requestParameters.to;
const interval = requestParameters.interval;
const query = requestParameters.query;
const field = requestParameters.field;
const type = requestParameters.type;
const ranges = requestParameters.ranges;
const aggs = requestParameters.aggs;
const order = requestParameters.order;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (from !== undefined && from !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>from, 'from');
}
if (to !== undefined && to !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>to, 'to');
}
if (interval !== undefined && interval !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>interval, 'interval');
}
if (query !== undefined && query !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>query, 'query');
}
if (field !== undefined && field !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>field, 'field');
}
if (type !== undefined && type !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>type, 'type');
}
if (ranges !== undefined && ranges !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>ranges, 'ranges');
}
if (aggs !== undefined && aggs !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>aggs, 'aggs');
}
if (order !== undefined && order !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>order, 'order');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<DateHistoAnalytics | GroupByAnalytics | CountAnalytics>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/analytics`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get the application\'s background
* Get the application\'s background. User must have APPLICATION_DEFINITION[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationBackgroundByApplicationId(requestParameters: GetApplicationBackgroundByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<Blob>;
public getApplicationBackgroundByApplicationId(requestParameters: GetApplicationBackgroundByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpResponse<Blob>>;
public getApplicationBackgroundByApplicationId(requestParameters: GetApplicationBackgroundByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpEvent<Blob>>;
public getApplicationBackgroundByApplicationId(requestParameters: GetApplicationBackgroundByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationBackgroundByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'image/_*',
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/background`,
{
responseType: "blob",
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get an application.
* Get an application. User must have the APPLICATION_DEFINITION[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationByApplicationId(requestParameters: GetApplicationByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Application>;
public getApplicationByApplicationId(requestParameters: GetApplicationByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Application>>;
public getApplicationByApplicationId(requestParameters: GetApplicationByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Application>>;
public getApplicationByApplicationId(requestParameters: GetApplicationByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Application>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get a specific log of an application
* Get a specific log of an application. User must have the APPLICATION_LOG[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationLogByApplicationIdAndLogId(requestParameters: GetApplicationLogByApplicationIdAndLogIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Log>;
public getApplicationLogByApplicationIdAndLogId(requestParameters: GetApplicationLogByApplicationIdAndLogIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Log>>;
public getApplicationLogByApplicationIdAndLogId(requestParameters: GetApplicationLogByApplicationIdAndLogIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Log>>;
public getApplicationLogByApplicationIdAndLogId(requestParameters: GetApplicationLogByApplicationIdAndLogIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationLogByApplicationIdAndLogId.');
}
const logId = requestParameters.logId;
if (logId === null || logId === undefined) {
throw new Error('Required parameter logId was null or undefined when calling getApplicationLogByApplicationIdAndLogId.');
}
const timestamp = requestParameters.timestamp;
let queryParameters = new HttpParams({encoder: this.encoder});
if (timestamp !== undefined && timestamp !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>timestamp, 'timestamp');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Log>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/logs/${encodeURIComponent(String(logId))}`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get Application logs
* Get the application logs. User must have the APPLICATION_LOG[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationLogs(requestParameters: GetApplicationLogsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<LogsResponse>;
public getApplicationLogs(requestParameters: GetApplicationLogsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<LogsResponse>>;
public getApplicationLogs(requestParameters: GetApplicationLogsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<LogsResponse>>;
public getApplicationLogs(requestParameters: GetApplicationLogsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationLogs.');
}
const page = requestParameters.page;
const size = requestParameters.size;
const from = requestParameters.from;
const to = requestParameters.to;
const query = requestParameters.query;
const field = requestParameters.field;
const order = requestParameters.order;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (from !== undefined && from !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>from, 'from');
}
if (to !== undefined && to !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>to, 'to');
}
if (query !== undefined && query !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>query, 'query');
}
if (field !== undefined && field !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>field, 'field');
}
if (order !== undefined && order !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>order, 'order');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<LogsResponse>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/logs`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get an application member
* Get an application member. User must have the APPLICATION_MEMBER[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationMemberByApplicationIdAndMemberId(requestParameters: GetApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Member>;
public getApplicationMemberByApplicationIdAndMemberId(requestParameters: GetApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Member>>;
public getApplicationMemberByApplicationIdAndMemberId(requestParameters: GetApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Member>>;
public getApplicationMemberByApplicationIdAndMemberId(requestParameters: GetApplicationMemberByApplicationIdAndMemberIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationMemberByApplicationIdAndMemberId.');
}
const memberId = requestParameters.memberId;
if (memberId === null || memberId === undefined) {
throw new Error('Required parameter memberId was null or undefined when calling getApplicationMemberByApplicationIdAndMemberId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Member>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members/${encodeURIComponent(String(memberId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get an application metadata
* Get an application metadata. User must have the APPLICATION_METADATA[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationMetadataByApplicationIdAndMetadataId(requestParameters: GetApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ReferenceMetadata>;
public getApplicationMetadataByApplicationIdAndMetadataId(requestParameters: GetApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ReferenceMetadata>>;
public getApplicationMetadataByApplicationIdAndMetadataId(requestParameters: GetApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ReferenceMetadata>>;
public getApplicationMetadataByApplicationIdAndMetadataId(requestParameters: GetApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationMetadataByApplicationIdAndMetadataId.');
}
const metadataId = requestParameters.metadataId;
if (metadataId === null || metadataId === undefined) {
throw new Error('Required parameter metadataId was null or undefined when calling getApplicationMetadataByApplicationIdAndMetadataId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<ReferenceMetadata>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/metadata/${encodeURIComponent(String(metadataId))}`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get the application\'s picture
* Get the application\'s picture. User must have APPLICATION_DEFINITION[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationPictureByApplicationId(requestParameters: GetApplicationPictureByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<Blob>;
public getApplicationPictureByApplicationId(requestParameters: GetApplicationPictureByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpResponse<Blob>>;
public getApplicationPictureByApplicationId(requestParameters: GetApplicationPictureByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<HttpEvent<Blob>>;
public getApplicationPictureByApplicationId(requestParameters: GetApplicationPictureByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'image/_*' | 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationPictureByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'image/_*',
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
return this.httpClient.get(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/picture`,
{
responseType: "blob",
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get the application type configuration.
* Get application type.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplicationType(requestParameters: GetApplicationTypeRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ApplicationType>;
public getApplicationType(requestParameters: GetApplicationTypeRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ApplicationType>>;
public getApplicationType(requestParameters: GetApplicationTypeRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ApplicationType>>;
public getApplicationType(requestParameters: GetApplicationTypeRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getApplicationType.');
}
let headers = this.defaultHeaders;
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<ApplicationType>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/configuration`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List all the applications accessible to authenticated user. Default order is by *name* ASC.
* List all the applications accessible to authenticated user. User must have MANAGEMENT_APPLICATION[READ] and PORTAL_APPLICATION[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getApplications(requestParameters: GetApplicationsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ApplicationsResponse>;
public getApplications(requestParameters: GetApplicationsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ApplicationsResponse>>;
public getApplications(requestParameters: GetApplicationsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ApplicationsResponse>>;
public getApplications(requestParameters: GetApplicationsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const page = requestParameters.page;
const size = requestParameters.size;
const forSubscription = requestParameters.forSubscription;
const order = requestParameters.order;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (forSubscription !== undefined && forSubscription !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>forSubscription, 'forSubscription');
}
if (order !== undefined && order !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>order, 'order');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<ApplicationsResponse>(`${this.configuration.basePath}/applications`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get the application\'s hooks list.
* Get application\'s hooks that can be used in the portal.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getHooks(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<Hook>>;
public getHooks(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<Hook>>>;
public getHooks(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<Hook>>>;
public getHooks(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
let headers = this.defaultHeaders;
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Array<Hook>>(`${this.configuration.basePath}/applications/hooks`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List application members
* List application members. User must have the APPLICATION_MEMBER[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getMembersByApplicationId(requestParameters: GetMembersByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<MembersResponse>;
public getMembersByApplicationId(requestParameters: GetMembersByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<MembersResponse>>;
public getMembersByApplicationId(requestParameters: GetMembersByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<MembersResponse>>;
public getMembersByApplicationId(requestParameters: GetMembersByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getMembersByApplicationId.');
}
const page = requestParameters.page;
const size = requestParameters.size;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<MembersResponse>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List application metadata
* List application metadata. User must have the APPLICATION_METADATA[READ] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getMetadataByApplicationId(requestParameters: GetMetadataByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ReferenceMetadataResponse>;
public getMetadataByApplicationId(requestParameters: GetMetadataByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ReferenceMetadataResponse>>;
public getMetadataByApplicationId(requestParameters: GetMetadataByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ReferenceMetadataResponse>>;
public getMetadataByApplicationId(requestParameters: GetMetadataByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getMetadataByApplicationId.');
}
const page = requestParameters.page;
const size = requestParameters.size;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<ReferenceMetadataResponse>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/metadata`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get application notifications
* Get application notifications. User must have APPLICATION_NOTIFICATION[READ] permission to get notifications.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getNotificationsByApplicationId(requestParameters: GetNotificationsByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<string>>;
public getNotificationsByApplicationId(requestParameters: GetNotificationsByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<string>>>;
public getNotificationsByApplicationId(requestParameters: GetNotificationsByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<string>>>;
public getNotificationsByApplicationId(requestParameters: GetNotificationsByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getNotificationsByApplicationId.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<Array<string>>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/notifications`,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* List APIs that subscribed with an application
* Lists API that current user is allowed to access. May be filtered by status. Ordered by nimber of hits. This application has to be accessible by the current user, otherwise a 404 will be returned.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getSubscriberApisByApplicationId(requestParameters: GetSubscriberApisByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ApisResponse>;
public getSubscriberApisByApplicationId(requestParameters: GetSubscriberApisByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ApisResponse>>;
public getSubscriberApisByApplicationId(requestParameters: GetSubscriberApisByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ApisResponse>>;
public getSubscriberApisByApplicationId(requestParameters: GetSubscriberApisByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling getSubscriberApisByApplicationId.');
}
const page = requestParameters.page;
const size = requestParameters.size;
const statuses = requestParameters.statuses;
let queryParameters = new HttpParams({encoder: this.encoder});
if (page !== undefined && page !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>page, 'page');
}
if (size !== undefined && size !== null) {
queryParameters = this.addToHttpParams(queryParameters,
<any>size, 'size');
}
if (statuses) {
statuses.forEach((element) => {
queryParameters = this.addToHttpParams(queryParameters,
<any>element, 'statuses');
})
}
let headers = this.defaultHeaders;
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.get<ApisResponse>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/subscribers`,
{
params: queryParameters,
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Renew the client secret for an OAuth2 application
* Renew the client secret for an OAuth2 application. User must have the APPLICATION_DEFINITION[UPDATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public renewApplicationSecret(requestParameters: RenewApplicationSecretRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Application>;
public renewApplicationSecret(requestParameters: RenewApplicationSecretRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Application>>;
public renewApplicationSecret(requestParameters: RenewApplicationSecretRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Application>>;
public renewApplicationSecret(requestParameters: RenewApplicationSecretRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling renewApplicationSecret.');
}
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<Application>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/_renew_secret`,
null,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Transfer the ownership of the application
* Transfer the ownership of the application. User must have the APPLICATION_MEMBER[UPDATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public transferMemberOwnership(requestParameters: TransferMemberOwnershipRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<any>;
public transferMemberOwnership(requestParameters: TransferMemberOwnershipRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<any>>;
public transferMemberOwnership(requestParameters: TransferMemberOwnershipRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<any>>;
public transferMemberOwnership(requestParameters: TransferMemberOwnershipRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling transferMemberOwnership.');
}
const transferOwnershipInput = requestParameters.transferOwnershipInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.post<any>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members/_transfer_ownership`,
transferOwnershipInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update alert for an application.
* Update alert for an application. User must have APPLICATION_ALERT[UPDATE] permission to update alerts.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateAlert(requestParameters: UpdateAlertRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Alert>;
public updateAlert(requestParameters: UpdateAlertRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Alert>>;
public updateAlert(requestParameters: UpdateAlertRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Alert>>;
public updateAlert(requestParameters: UpdateAlertRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling updateAlert.');
}
const alertId = requestParameters.alertId;
if (alertId === null || alertId === undefined) {
throw new Error('Required parameter alertId was null or undefined when calling updateAlert.');
}
const alertInput = requestParameters.alertInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.put<Alert>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/alerts/${encodeURIComponent(String(alertId))}`,
alertInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update an application.
* Update an application. User must have APPLICATION_DEFINITION[UPDATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateApplicationByApplicationId(requestParameters: UpdateApplicationByApplicationIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Application>;
public updateApplicationByApplicationId(requestParameters: UpdateApplicationByApplicationIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Application>>;
public updateApplicationByApplicationId(requestParameters: UpdateApplicationByApplicationIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Application>>;
public updateApplicationByApplicationId(requestParameters: UpdateApplicationByApplicationIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling updateApplicationByApplicationId.');
}
const application = requestParameters.application;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.put<Application>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}`,
application,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update an application member.
* Update an application member. User must have the APPLICATION_MEMBER[UPDATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateApplicationMemberByApplicationIdAndMemberId(requestParameters: UpdateApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Member>;
public updateApplicationMemberByApplicationIdAndMemberId(requestParameters: UpdateApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Member>>;
public updateApplicationMemberByApplicationIdAndMemberId(requestParameters: UpdateApplicationMemberByApplicationIdAndMemberIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Member>>;
public updateApplicationMemberByApplicationIdAndMemberId(requestParameters: UpdateApplicationMemberByApplicationIdAndMemberIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling updateApplicationMemberByApplicationIdAndMemberId.');
}
const memberId = requestParameters.memberId;
if (memberId === null || memberId === undefined) {
throw new Error('Required parameter memberId was null or undefined when calling updateApplicationMemberByApplicationIdAndMemberId.');
}
const memberInput = requestParameters.memberInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.put<Member>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/members/${encodeURIComponent(String(memberId))}`,
memberInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update an application metadata.
* Update an application metadata. User must have the APPLICATION_METADATA[UPDATE] permission.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateApplicationMetadataByApplicationIdAndMetadataId(requestParameters: UpdateApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<ReferenceMetadata>;
public updateApplicationMetadataByApplicationIdAndMetadataId(requestParameters: UpdateApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<ReferenceMetadata>>;
public updateApplicationMetadataByApplicationIdAndMetadataId(requestParameters: UpdateApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<ReferenceMetadata>>;
public updateApplicationMetadataByApplicationIdAndMetadataId(requestParameters: UpdateApplicationMetadataByApplicationIdAndMetadataIdRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling updateApplicationMetadataByApplicationIdAndMetadataId.');
}
const metadataId = requestParameters.metadataId;
if (metadataId === null || metadataId === undefined) {
throw new Error('Required parameter metadataId was null or undefined when calling updateApplicationMetadataByApplicationIdAndMetadataId.');
}
const referenceMetadataInput = requestParameters.referenceMetadataInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.put<ReferenceMetadata>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/metadata/${encodeURIComponent(String(metadataId))}`,
referenceMetadataInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update notifications for an application.
* Update notifications for an application. User must have APPLICATION_NOTIFICATION[UPDATE] permission to update notifications.
* @param requestParameters
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateApplicationNotifications(requestParameters: UpdateApplicationNotificationsRequestParams, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<Array<string>>;
public updateApplicationNotifications(requestParameters: UpdateApplicationNotificationsRequestParams, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<Array<string>>>;
public updateApplicationNotifications(requestParameters: UpdateApplicationNotificationsRequestParams, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<Array<string>>>;
public updateApplicationNotifications(requestParameters: UpdateApplicationNotificationsRequestParams, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
const applicationId = requestParameters.applicationId;
if (applicationId === null || applicationId === undefined) {
throw new Error('Required parameter applicationId was null or undefined when calling updateApplicationNotifications.');
}
const notificationInput = requestParameters.notificationInput;
let headers = this.defaultHeaders;
// authentication (BasicAuth) required
if (this.configuration.username || this.configuration.password) {
headers = headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password));
}
// authentication (CookieAuth) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["CookieAuth"] || this.configuration.apiKeys["Auth-Graviteeio-APIM"];
if (key) {
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
headers = headers.set('Content-Type', httpContentTypeSelected);
}
let responseType: 'text' | 'json' = 'json';
if(httpHeaderAcceptSelected && httpHeaderAcceptSelected.startsWith('text')) {
responseType = 'text';
}
return this.httpClient.put<Array<string>>(`${this.configuration.basePath}/applications/${encodeURIComponent(String(applicationId))}/notifications`,
notificationInput,
{
responseType: <any>responseType,
withCredentials: this.configuration.withCredentials,
headers: headers,
observe: observe,
reportProgress: reportProgress
}
);
}
} | the_stack |
import { buildMarkdownParser } from "../../src/shared/markdown-parser";
import { richTextSchema } from "../../src/shared/schema";
import "../matchers";
const markdownParser = buildMarkdownParser(
{
snippets: true,
html: true,
tagLinks: {
allowNonAscii: false,
allowMetaTags: false,
},
},
richTextSchema,
null
);
describe("SOMarkdownParser", () => {
describe("html support", () => {
it.skip("should support inline html", () => {
const doc = markdownParser.parse("<strong>test</strong>");
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "paragraph",
"childCount": 1,
"content": [
{
"type.name": "html_inline",
"childCount": 1,
"content": [
{
"isText": true,
"text": "test",
"marks.length": 1,
"marks.0.type.name": "strong",
},
],
},
],
},
],
});
});
it.skip("should support single block html without nesting", () => {
const doc = markdownParser.parse("<h1>test</h1>");
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "html_block",
"childCount": 1,
"content": [
{
"type.name": "heading",
"childCount": 1,
"content": [
{
isText: true,
text: "test",
},
],
},
],
},
],
});
});
it.skip("should support block html with inline nesting", () => {
//const doc = markdownParser.parse("<h1><em>test</em></h1>");
});
it.skip("should support block html with block nesting", () => {
//const doc = markdownParser.parse("<ul><li>test</li></ul>");
});
it.skip("should support block html with mixed nesting", () => {
// const doc = markdownParser.parse(
// "<h1><strong>str</strong><p>test</p></h1>"
// );
});
it.skip("should support block html with deep nesting", () => {
//const doc = markdownParser.parse("<ul><li><em>test</em></li></ul>");
});
});
// NOTE: detailed / edge case testing is done in the plugin specific tests,
// these tests simply check that the correct Prosemirror nodes are generated for use in the editor
describe("custom markdown plugins", () => {
it.skip("should support stack snippets", () => {
const doc = markdownParser.parse(`
<!-- begin snippet: js hide: true console: true babel: true -->
\`\`\`html
<h1>test</h1>
\`\`\`
\`\`\`css
h1 {
color: red;
}
\`\`\`
\`\`\`js
console.log("test");
\`\`\`
<!-- end snippet -->
`);
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "stack_snippet",
"childCount": 3,
"attrs.data": "js hide: true console: true babel: true",
"content": [
{
"type.name": "code_block",
"attrs.params": "html",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": "<h1>test</h1>",
},
],
},
{
"type.name": "code_block",
"attrs.params": "css",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": "h1 {\n color: red;\n}",
},
],
},
{
"type.name": "code_block",
"attrs.params": "js",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": 'console.log("test");',
},
],
},
],
},
],
});
});
it("should support stack language(-all) comments", () => {
const doc = markdownParser.parse(`
<!-- language-all: lang-python -->
<!-- language: lang-js -->
console.log("test");
`);
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "code_block",
"attrs.params": "js",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": 'console.log("test");',
},
],
},
],
});
});
it("should parse tag links", () => {
const doc = markdownParser.parse("[tag:python]");
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "paragraph",
"childCount": 1,
"content": [
{
"type.name": "tagLink",
"childCount": 1,
"content": [{ text: "python" }],
},
],
},
],
});
});
it("should not parse tag links", () => {
const mdParserWithoutTagLinks = buildMarkdownParser(
{},
richTextSchema,
null
);
const doc = mdParserWithoutTagLinks.parse("[tag:python]");
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "paragraph",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": "[tag:python]",
},
],
},
],
});
});
});
describe("softbreaks", () => {
it("should be parsed as nodes containing a space", () => {
const doc = markdownParser.parse("test1\ntest2");
expect(doc).toMatchNodeTree({
childCount: 1,
content: [
{
"type.name": "paragraph",
"childCount": 3,
"content": [
{
isText: true,
text: "test1",
},
{
"type.name": "softbreak",
"childCount": 1,
"content": [
{
"type.name": "text",
"text": " ",
},
],
},
{
isText: true,
text: "test2",
},
],
},
],
});
});
});
describe("autolinking", () => {
it.each([
"https://www.test.com/?param=test",
"mailto:test@example.com",
"ftp://example.com/path/to/file",
])("should autolink valid links (%s)", (input) => {
const doc = markdownParser.parse(input).toJSON();
expect(doc.content[0].type).toBe("paragraph");
expect(doc.content[0].content).toHaveLength(1);
expect(doc.content[0].content[0].text).toBe(input);
expect(doc.content[0].content[0].marks[0].type).toBe("link");
});
it.each(["file://invalid", "://inherit_scheme.com", "invalid.com"])(
"should not autolink invalid links (%s)",
(input) => {
const doc = markdownParser.parse(input).toJSON();
expect(doc.content[0].type).toBe("paragraph");
expect(doc.content[0].content).toHaveLength(1);
expect(doc.content[0].content[0].text).toBe(input);
expect(doc.content[0].content[0].marks).toBeUndefined();
}
);
});
describe("lists", () => {
it.each([
["- test1\n- test2", true],
["- test1\n\n- test2", false],
["1. test1\n1. test2", true],
["1. test1\n\n1. test2", false],
])("should parse tight/loose lists", (input, isTight) => {
const doc = markdownParser.parse(input).toJSON();
expect(doc.content[0].type).toContain("_list");
expect(doc.content[0].attrs.tight).toBe(isTight);
});
});
}); | the_stack |
'use strict';
import * as jsonc from 'jsonc-parser';
import * as path from 'path';
import * as vscode from 'vscode';
import { IPreferences } from 'vscode-wpilibapi';
import { localize as i18n } from './locale';
import { IPreferencesJson } from './shared/preferencesjson';
import { existsAsync, mkdirAsync, readFileAsync, writeFileAsync } from './utilities';
const defaultPreferences: IPreferencesJson = {
currentLanguage: 'none',
enableCppIntellisense: false,
projectYear: 'none',
teamNumber: -1,
};
export async function requestTeamNumber(): Promise<number> {
const teamNumber = await vscode.window.showInputBox({
prompt: i18n('ui', 'Enter a team number'),
validateInput: (v) => {
const match = v.match(/^\d{1,5}$/gm);
if (match === null || match.length === 0) {
return i18n('ui', 'Invalid team number');
}
return undefined;
},
});
if (teamNumber === undefined) {
return -1;
}
return parseInt(teamNumber, 10);
}
// Stores the preferences for a specific workspace
export class Preferences implements IPreferences {
public static readonly preferenceFileName: string = 'wpilib_preferences.json';
public static readonly wpilibPreferencesFolder: string = '.wpilib';
// Create for a specific workspace
public static async Create(workspace: vscode.WorkspaceFolder): Promise<Preferences> {
const prefs = new Preferences(workspace);
await prefs.asyncInitialize();
return prefs;
}
public static getPrefrencesFilePath(root: string): string {
return path.join(root, Preferences.wpilibPreferencesFolder, Preferences.preferenceFileName);
}
// Workspace these preferences are assigned to.
public workspace: vscode.WorkspaceFolder;
private preferencesFile?: vscode.Uri;
private preferencesJson: IPreferencesJson = defaultPreferences;
private configFileWatcher: vscode.FileSystemWatcher;
private readonly preferencesGlob: string = '**/' + Preferences.preferenceFileName;
private disposables: vscode.Disposable[] = [];
private isWPILibProject: boolean = false;
private constructor(workspace: vscode.WorkspaceFolder) {
this.workspace = workspace;
const rp = new vscode.RelativePattern(workspace, this.preferencesGlob);
this.configFileWatcher = vscode.workspace.createFileSystemWatcher(rp);
this.disposables.push(this.configFileWatcher);
this.configFileWatcher.onDidCreate(async (uri) => {
await vscode.commands.executeCommand('setContext', 'isWPILibProject', true);
this.isWPILibProject = true;
this.preferencesFile = uri;
await this.updatePreferences();
});
this.configFileWatcher.onDidDelete(async () => {
await vscode.commands.executeCommand('setContext', 'isWPILibProject', false);
this.isWPILibProject = false;
this.preferencesFile = undefined;
await this.updatePreferences();
});
this.configFileWatcher.onDidChange(async () => {
await this.updatePreferences();
});
}
public getIsWPILibProject(): boolean {
return this.isWPILibProject;
}
public async getTeamNumber(): Promise<number> {
// If always ask, get it.
const alwaysAsk = this.getConfiguration().get<boolean>('alwaysAskForTeamNumber');
if (alwaysAsk !== undefined && alwaysAsk === true) {
return requestTeamNumber();
}
if (this.preferencesJson.teamNumber < 0) {
return this.noTeamNumberLogic();
}
return this.preferencesJson.teamNumber;
}
public async setTeamNumber(teamNumber: number): Promise<void> {
this.preferencesJson.teamNumber = teamNumber;
await this.writePreferences();
}
public getCurrentLanguage(): string {
return this.preferencesJson.currentLanguage;
}
public getEnableCppIntellisense(): boolean {
return this.preferencesJson.enableCppIntellisense;
}
public async setEnableCppIntellisense(set: boolean): Promise<void> {
this.preferencesJson.enableCppIntellisense = set;
await this.writePreferences();
}
public getProjectYear(): string {
return this.preferencesJson.projectYear;
}
public async setProjectYear(year: string): Promise<void> {
this.preferencesJson.projectYear = year;
await this.writePreferences();
}
public async setCurrentLanguage(language: string): Promise<void> {
this.preferencesJson.currentLanguage = language;
await this.writePreferences();
}
public getAutoStartRioLog(): boolean {
const res = this.getConfiguration().get<boolean>('autoStartRioLog');
if (res === undefined) {
return false;
}
return res;
}
public async setAutoStartRioLog(autoStart: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('autoStartRioLog', autoStart, target);
}
public async setOffline(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('offline', value, target);
}
public async setStopSimulationOnEntry(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('stopSimulationOnEntry', value, target);
}
public async setSkipTests(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('skipTests', value, target);
}
public async setSkipSelectSimulateExtension(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('skipSelectSimulateExtension', value, target);
}
public async setSelectDefaultSimulateExtension(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('selectDefaultSimulateExtension', value, target);
}
public getAutoSaveOnDeploy(): boolean {
const res = this.getConfiguration().get<boolean>('autoSaveOnDeploy');
if (res === undefined) {
return false;
}
return res;
}
public async setAutoSaveOnDeploy(autoSave: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('autoSaveOnDeploy', autoSave, target);
}
public getAdditionalGradleArguments(): string {
const res = this.getConfiguration().get<string>('additionalGradleArguments');
if (res === undefined) {
return '';
}
return res;
}
public getOffline(): boolean {
const res = this.getConfiguration().get<boolean>('offline');
if (res === undefined) {
return false;
}
return res;
}
public getSkipTests(): boolean {
const res = this.getConfiguration().get<boolean>('skipTests');
if (res === undefined) {
return false;
}
return res;
}
public getSkipSelectSimulateExtension(): boolean {
const res = this.getConfiguration().get<boolean>('skipSelectSimulateExtension');
if (res === undefined) {
return false;
}
return res;
}
public getSelectDefaultSimulateExtension(): boolean {
const res = this.getConfiguration().get<boolean>('selectDefaultSimulateExtension');
if (res === undefined) {
return false;
}
return res;
}
public getStopSimulationOnEntry(): boolean {
const res = this.getConfiguration().get<boolean>('stopSimulationOnEntry');
if (res === undefined) {
return false;
}
return res;
}
public async setDeployOffline(value: boolean, global: boolean): Promise<void> {
let target: vscode.ConfigurationTarget = vscode.ConfigurationTarget.Global;
if (!global) {
target = vscode.ConfigurationTarget.WorkspaceFolder;
}
return this.getConfiguration().update('deployOffline', value, target);
}
public getDeployOffline(): boolean {
const res = this.getConfiguration().get<boolean>('deployOffline');
if (res === undefined) {
return false;
}
return res;
}
public dispose() {
for (const d of this.disposables) {
d.dispose();
}
}
private async asyncInitialize() {
const configFilePath = Preferences.getPrefrencesFilePath(this.workspace.uri.fsPath);
if (await existsAsync(configFilePath)) {
vscode.commands.executeCommand('setContext', 'isWPILibProject', true);
this.isWPILibProject = true;
this.preferencesFile = vscode.Uri.file(configFilePath);
this.preferencesJson = defaultPreferences;
await this.updatePreferences();
} else {
// Set up defaults, and create
this.preferencesJson = defaultPreferences;
}
}
private getConfiguration(): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration('wpilib', this.workspace.uri);
}
private async updatePreferences() {
if (this.preferencesFile === undefined) {
this.preferencesJson = defaultPreferences;
return;
}
const results = await readFileAsync(this.preferencesFile.fsPath, 'utf8');
this.preferencesJson = jsonc.parse(results) as IPreferencesJson;
}
private async writePreferences(): Promise<void> {
if (this.preferencesFile === undefined) {
const configFilePath = Preferences.getPrefrencesFilePath(this.workspace.uri.fsPath);
this.preferencesFile = vscode.Uri.file(configFilePath);
await mkdirAsync(path.dirname(this.preferencesFile.fsPath));
}
await writeFileAsync(this.preferencesFile.fsPath, JSON.stringify(this.preferencesJson, null, 4));
}
private async noTeamNumberLogic(): Promise<number> {
// Ask if user wants to set team number.
const teamRequest = await vscode.window.showInformationMessage(i18n('message', 'No team number, would you like to save one?'), {
modal: true,
}, i18n('ui', 'Yes'), i18n('ui', 'No'));
if (teamRequest === undefined) {
return -1;
}
const teamNumber = await requestTeamNumber();
if (teamRequest === i18n('ui', 'No')) {
return teamNumber;
} else if (teamNumber >= 0) {
await this.setTeamNumber(teamNumber);
}
return teamNumber;
}
} | the_stack |
import { DeleteAllResponse } from '@destinyitemmanager/dim-api-types';
import { needsDeveloper } from 'app/accounts/actions';
import { compareAccounts } from 'app/accounts/destiny-account';
import { currentAccountSelector } from 'app/accounts/selectors';
import { getActiveToken as getBungieToken } from 'app/bungie-api/authenticated-fetch';
import { dimErrorToaster } from 'app/bungie-api/error-toaster';
import { t } from 'app/i18next-t';
import { showNotification } from 'app/notifications/notifications';
import { initialSettingsState, Settings } from 'app/settings/initial-settings';
import { readyResolve } from 'app/settings/settings';
import { refresh$ } from 'app/shell/refresh';
import { RootState, ThunkResult } from 'app/store/types';
import { errorLog, infoLog } from 'app/utils/log';
import { delay } from 'app/utils/util';
import { deepEqual } from 'fast-equals';
import { get, set } from 'idb-keyval';
import _ from 'lodash';
import { AnyAction } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import { getPlatforms } from '../accounts/platforms';
import {
deleteAllData,
getDimApiProfile,
getGlobalSettings,
postUpdates,
} from '../dim-api/dim-api';
import { observeStore } from '../utils/redux-utils';
import { promptForApiPermission } from './api-permission-prompt';
import { ProfileUpdateWithRollback } from './api-types';
import {
allDataDeleted,
finishedUpdates,
flushUpdatesFailed,
globalSettingsLoaded,
prepareToFlushUpdates,
ProfileIndexedDBState,
profileLoaded,
profileLoadedFromIDB,
profileLoadError,
setApiPermissionGranted,
} from './basic-actions';
import { DimApiState } from './reducer';
import { apiPermissionGrantedSelector } from './selectors';
const installApiPermissionObserver = _.once(() => {
// Observe API permission and reflect it into local storage
// We could also use a thunk action instead of an observer... either way
observeStore(
(state) => state.dimApi.apiPermissionGranted,
(_prev, apiPermissionGranted) => {
if (apiPermissionGranted !== null) {
// Save the permission preference to local storage
localStorage.setItem('dim-api-enabled', apiPermissionGranted ? 'true' : 'false');
}
}
);
});
/**
* Watch the redux store and write out values to indexedDB, etc.
*/
const installObservers = _.once((dispatch: ThunkDispatch<RootState, undefined, AnyAction>) => {
// Watch the state and write it out to IndexedDB
observeStore(
(state) => state.dimApi,
_.debounce((currentState: DimApiState, nextState: DimApiState) => {
// Avoid writing back what we just loaded from IDB
if (currentState?.profileLoadedFromIndexedDb) {
// Only save the difference between the current and default settings
const settingsToSave = subtractObject(nextState.settings, initialSettingsState) as Settings;
const savedState: ProfileIndexedDBState = {
settings: settingsToSave,
profiles: nextState.profiles,
updateQueue: nextState.updateQueue,
itemHashTags: nextState.itemHashTags,
searches: nextState.searches,
};
infoLog('dim sync', 'Saving profile data to IDB');
set('dim-api-profile', savedState);
}
}, 1000)
);
// Watch the update queue and flush updates
observeStore(
(state) => state.dimApi.updateQueue,
_.debounce((_prev, queue: ProfileUpdateWithRollback[]) => {
if (queue.length) {
dispatch(flushUpdates());
}
}, 1000)
);
// Observe the current account and reload data
// Another one that should probably be a thunk action once account transitions are actions
observeStore(currentAccountSelector, (oldAccount, newAccount) => {
// Force load profile data if the account changed
if (oldAccount && newAccount && !compareAccounts(oldAccount, newAccount)) {
dispatch(loadDimApiData(true));
}
});
// Every time data is refreshed, maybe load DIM API data too
refresh$.subscribe(() => dispatch(loadDimApiData()));
});
/**
* Load global API configuration from the server. This doesn't even require the user to be logged in.
*/
export function loadGlobalSettings(): ThunkResult {
return async (dispatch, getState) => {
// TODO: better to use a state machine (UNLOADED => LOADING => LOADED)
if (!getState().dimApi.globalSettingsLoaded) {
try {
const globalSettings = await getGlobalSettings();
infoLog('dim sync', 'globalSettings', globalSettings);
dispatch(globalSettingsLoaded(globalSettings));
} catch (e) {
errorLog('dim sync', 'Failed to load global settings from DIM API', e);
}
}
};
}
/**
* Wait, with exponential backoff - we'll try infinitely otherwise, in a tight loop!
* Double the wait time, starting with 30 seconds, until we reach 5 minutes.
*/
function getBackoffWaitTime(backoff: number) {
return Math.min(5 * 60 * 1000, Math.random() * Math.pow(2, backoff) * 15000);
}
// Backoff multiplier
let getProfileBackoff = 0;
let waitingForApiPermission = false;
/**
* Load all API data (including global settings). This should be called at start and whenever the account is changed.
*
* This action effectively drives a workflow that enables DIM Sync, as well. We check for whether the user has
* opted in to Sync, and if they haven't we prompt. We also use this action to kick off auto-import of legacy data.
*/
export function loadDimApiData(forceLoad = false): ThunkResult {
return async (dispatch, getState) => {
installApiPermissionObserver();
if (!getState().dimApi.globalSettingsLoaded) {
await dispatch(loadGlobalSettings());
}
// API is disabled, give up
if (!getState().dimApi.globalSettings.dimApiEnabled) {
return;
}
// Check if we're even logged into Bungie.net. Don't need to load or sync if not.
const bungieToken = await getBungieToken();
if (!bungieToken) {
return;
}
// Don't let actions pile up blocked on the approval UI
if (waitingForApiPermission) {
return;
}
// Show a prompt if the user has not said one way or another whether they want to use the API
if (getState().dimApi.apiPermissionGranted === null) {
waitingForApiPermission = true;
try {
const useApi = await promptForApiPermission();
dispatch(setApiPermissionGranted(useApi));
} finally {
waitingForApiPermission = false;
}
}
const getPlatformsPromise = dispatch(getPlatforms()); // in parallel, we'll wait later
if (!getState().dimApi.profileLoadedFromIndexedDb && !getState().dimApi.profileLoaded) {
await dispatch(loadProfileFromIndexedDB());
}
installObservers(dispatch); // idempotent
if (!getState().dimApi.apiPermissionGranted) {
// They don't want to sync to the server, stay local only
readyResolve();
return;
}
// don't load from remote if there is already an update queue from IDB - we'd roll back data otherwise!
if (getState().dimApi.updateQueue.length > 0) {
await dispatch(flushUpdates()); // flushUpdates will call loadDimApiData again at the end
return;
}
// How long before the API data is considered stale is controlled from the server
const profileOutOfDate =
Date.now() - getState().dimApi.profileLastLoaded >
getState().dimApi.globalSettings.dimProfileMinimumRefreshInterval * 1000;
if (forceLoad || !getState().dimApi.profileLoaded || profileOutOfDate) {
// get current account
const accounts = await getPlatformsPromise;
if (!accounts) {
// User isn't logged in or has no accounts, nothing to load!
return;
}
const currentAccount = currentAccountSelector(getState());
try {
const profileResponse = await getDimApiProfile(currentAccount);
dispatch(profileLoaded({ profileResponse, account: currentAccount }));
// Quickly heal from being failure backoff
getProfileBackoff = Math.floor(getProfileBackoff / 2);
} catch (e) {
// Only notify error once
if (!getState().dimApi.profileLoadedError) {
showProfileLoadErrorNotification(e);
}
dispatch(profileLoadError(e));
errorLog('loadDimApiData', 'Unable to get profile from DIM API', e);
if (e.name !== 'FatalTokenError') {
// Wait, with exponential backoff
getProfileBackoff++;
const waitTime = getBackoffWaitTime(getProfileBackoff);
infoLog('loadDimApiData', 'Waiting', waitTime, 'ms before re-attempting profile fetch');
await delay(waitTime);
// Retry
dispatch(loadDimApiData(forceLoad));
} else if ($DIM_FLAVOR === 'dev') {
dispatch(needsDeveloper());
}
return;
} finally {
readyResolve();
}
}
// Make sure any queued updates get sent to the server
await dispatch(flushUpdates());
};
}
// Backoff multiplier
let flushUpdatesBackoff = 0;
/**
* Process the queue of updates by sending them to the server
*/
export function flushUpdates(): ThunkResult {
return async (dispatch, getState) => {
let dimApiState = getState().dimApi;
// Skip flushing state if the API is disabled
if (!dimApiState.globalSettings.dimApiEnabled) {
return;
}
if (dimApiState.updateInProgressWatermark === 0 && dimApiState.updateQueue.length > 0) {
// Prepare the queue
dispatch(prepareToFlushUpdates());
dimApiState = getState().dimApi;
if (dimApiState.updateInProgressWatermark === 0) {
return;
}
infoLog(
'flushUpdates',
'Flushing queue of',
dimApiState.updateInProgressWatermark,
'updates'
);
// Only select the items that were frozen for update. They're guaranteed
// to not change while we're updating and they'll be for a single profile.
const updates = dimApiState.updateQueue.slice(0, dimApiState.updateInProgressWatermark);
try {
const firstWithAccount = updates.find((u) => u.platformMembershipId) || updates[0];
const results = await postUpdates(
firstWithAccount.platformMembershipId,
firstWithAccount.destinyVersion,
updates
);
infoLog('flushUpdates', 'got results', updates, results);
// Quickly heal from being failure backoff
flushUpdatesBackoff = Math.floor(flushUpdatesBackoff / 2);
dispatch(finishedUpdates(results));
} catch (e) {
if (flushUpdatesBackoff === 0) {
showUpdateErrorNotification(e);
}
errorLog('flushUpdates', 'Unable to save updates to DIM API', e);
// Wait, with exponential backoff
flushUpdatesBackoff++;
const waitTime = getBackoffWaitTime(flushUpdatesBackoff);
infoLog('flushUpdates', 'Waiting', waitTime, 'ms before re-attempting updates');
await delay(waitTime);
// Now mark the queue failed so it can be retried. Until
// updateInProgressWatermark gets reset no other flushUpdates call will
// do anything.
dispatch(flushUpdatesFailed());
} finally {
dimApiState = getState().dimApi;
if (dimApiState.updateQueue.length > 0) {
// Flush more updates!
dispatch(flushUpdates());
} else if (!dimApiState.profileLoaded) {
// Load API data in case we didn't do it before
dispatch(loadDimApiData());
}
}
}
};
}
export function loadProfileFromIndexedDB(): ThunkResult {
return async (dispatch, getState) => {
// If we already got it from the server, don't bother
if (getState().dimApi.profileLoaded || getState().dimApi.profileLoadedFromIndexedDb) {
return;
}
const profile = await get<ProfileIndexedDBState | undefined>('dim-api-profile');
// If we already got it from the server, don't bother
if (getState().dimApi.profileLoaded || getState().dimApi.profileLoadedFromIndexedDb) {
return;
}
dispatch(profileLoadedFromIDB(profile));
};
}
/** Produce a new object that's only the key/values of obj that are also keys in defaults and which have values different from defaults. */
function subtractObject<T>(obj: T | undefined, defaults: T): Partial<T> {
const result: Partial<T> = {};
if (obj) {
for (const key in defaults) {
if (obj[key] !== undefined && !deepEqual(obj[key], defaults[key])) {
result[key] = obj[key];
}
}
}
return result;
}
/**
* Wipe out all data in the DIM Sync cloud storage. Not recoverable!
*/
export function deleteAllApiData(): ThunkResult<DeleteAllResponse['deleted']> {
return async (dispatch, getState) => {
const result = await deleteAllData();
// If they have the API enabled, also clear out everything locally. Otherwise we'll just clear out the remote data.
if (apiPermissionGrantedSelector(getState())) {
dispatch(allDataDeleted());
}
return result;
};
}
function showProfileLoadErrorNotification(e: Error) {
showNotification(
dimErrorToaster(t('Storage.ProfileErrorTitle'), t('Storage.ProfileErrorBody'), e)
);
}
function showUpdateErrorNotification(e: Error) {
showNotification(dimErrorToaster(t('Storage.UpdateErrorTitle'), t('Storage.UpdateErrorBody'), e));
} | the_stack |
import { EventEmitter } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { FileModel, FileUploadOptions, FileUploadStatus } from '../models/file.model';
import { AppConfigModule } from '../app-config/app-config.module';
import { UploadService } from './upload.service';
import { AppConfigService } from '../app-config/app-config.service';
import { setupTestBed } from '../testing/setup-test-bed';
import { CoreTestingModule } from '../testing/core.testing.module';
import { AssocChildBody, AssociationBody } from '@alfresco/js-api';
import { TranslateModule } from '@ngx-translate/core';
import { DiscoveryApiService } from './discovery-api.service';
import { BehaviorSubject } from 'rxjs';
import { EcmProductVersionModel } from '../models';
declare let jasmine: any;
describe('UploadService', () => {
let service: UploadService;
let appConfigService: AppConfigService;
let uploadFileSpy: jasmine.Spy;
const mockProductInfo = new BehaviorSubject<EcmProductVersionModel>(null);
setupTestBed({
imports: [
TranslateModule.forRoot(),
CoreTestingModule,
AppConfigModule
],
providers: [
{
provide: DiscoveryApiService,
useValue: {
ecmProductInfo$: mockProductInfo
}
}
]
});
beforeEach(() => {
appConfigService = TestBed.inject(AppConfigService);
appConfigService.config = {
ecmHost: 'http://localhost:9876/ecm',
files: {
excluded: ['.DS_Store', 'desktop.ini', '.git', '*.git', '*.SWF'],
'match-options': {
/* cspell:disable-next-line */
nocase: true
}
},
folders: {
excluded: ['ROLLINGPANDA'],
'match-options': {
/* cspell:disable-next-line */
nocase: true
}
}
};
service = TestBed.inject(UploadService);
service.queue = [];
service.activeTask = null;
uploadFileSpy = spyOn(service.uploadApi, 'uploadFile').and.callThrough();
jasmine.Ajax.install();
mockProductInfo.next({ status: { isThumbnailGenerationEnabled: true } } as EcmProductVersionModel);
});
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('should return an empty queue if no elements are added', () => {
expect(service.getQueue().length).toEqual(0);
});
it('should add an element in the queue and returns it', () => {
const filesFake = new FileModel(<File> { name: 'fake-name', size: 10 });
service.addToQueue(filesFake);
expect(service.getQueue().length).toEqual(1);
});
it('should add two elements in the queue and returns them', () => {
const filesFake = [
new FileModel(<File> { name: 'fake-name', size: 10 }),
new FileModel(<File> { name: 'fake-name2', size: 20 })
];
service.addToQueue(...filesFake);
expect(service.getQueue().length).toEqual(2);
});
it('should not have the queue uploading if all files are complete, cancelled, aborted, errored or deleted', () => {
const file1 = new FileModel(<File> { name: 'fake-file-1', size: 10 });
const file2 = new FileModel(<File> { name: 'fake-file-2', size: 20 });
const file3 = new FileModel(<File> { name: 'fake-file-3', size: 30 });
const file4 = new FileModel(<File> { name: 'fake-file-4', size: 40 });
const file5 = new FileModel(<File> { name: 'fake-file-5', size: 50 });
file1.status = FileUploadStatus.Complete;
file2.status = FileUploadStatus.Cancelled;
file3.status = FileUploadStatus.Aborted;
file4.status = FileUploadStatus.Error;
file5.status = FileUploadStatus.Deleted;
service.addToQueue(file1, file2, file3, file4, file5);
expect(service.isUploading()).toBe(false);
});
it('should have the queue still uploading if some files are still pending, starting or in progress', () => {
const file1 = new FileModel(<File> { name: 'fake-file-1', size: 10 });
const file2 = new FileModel(<File> { name: 'fake-file-2', size: 20 });
service.addToQueue(file1, file2);
file1.status = FileUploadStatus.Complete;
file2.status = FileUploadStatus.Pending;
expect(service.isUploading()).toBe(true);
file2.status = FileUploadStatus.Starting;
expect(service.isUploading()).toBe(true);
file2.status = FileUploadStatus.Progress;
expect(service.isUploading()).toBe(true);
});
it('should skip hidden macOS files', () => {
const file1 = new FileModel(new File([''], '.git'));
const file2 = new FileModel(new File([''], 'readme.md'));
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should match the extension in case insensitive way', () => {
const file1 = new FileModel(new File([''], 'test.swf'));
const file2 = new FileModel(new File([''], 'readme.md'));
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should make XHR done request after the file is added in the queue', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((e) => {
expect(e.value).toBe('File uploaded');
emitterDisposable.unsubscribe();
done();
});
const fileFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
<FileUploadOptions> { parentId: '-root-', path: 'fake-dir' }
);
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'text/plain',
responseText: 'File uploaded'
});
});
it('should make XHR error request after an error occur', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((e) => {
expect(e.value).toBe('Error file uploaded');
emitterDisposable.unsubscribe();
done();
});
const fileFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
<FileUploadOptions> { parentId: '-root-' }
);
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(null, emitter);
expect(jasmine.Ajax.requests.mostRecent().url)
.toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 404,
contentType: 'text/plain',
responseText: 'Error file uploaded'
});
});
it('should abort file only if it is safe to abort', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((event) => {
expect(event.value).toEqual('File aborted');
emitterDisposable.unsubscribe();
done();
});
const fileFake = new FileModel(<File> { name: 'fake-name', size: 10000000 });
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
const file = service.getQueue();
service.cancelUpload(...file);
});
it('should let file complete and then delete node if it is not safe to abort', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((event) => {
expect(event.value).toEqual('File deleted');
emitterDisposable.unsubscribe();
const deleteRequest = jasmine.Ajax.requests.mostRecent();
expect(deleteRequest.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/myNodeId?permanent=true');
expect(deleteRequest.method).toBe('DELETE');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'text/plain',
responseText: 'File deleted'
});
done();
});
const fileFake = new FileModel(<File> { name: 'fake-name', size: 10 });
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
const file = service.getQueue();
service.cancelUpload(...file);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?autoRename=true&include=allowableOperations');
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'json',
responseText: {
entry: {
id: 'myNodeId'
}
}
});
});
it('should delete node version when cancelling the upload of the new file version', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((event) => {
expect(event.value).toEqual('File deleted');
emitterDisposable.unsubscribe();
const deleteRequest = jasmine.Ajax.requests.mostRecent();
expect(deleteRequest.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/myNodeId/versions/1.1');
expect(deleteRequest.method).toBe('DELETE');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'text/plain',
responseText: 'File deleted'
});
done();
});
const fileFake = new FileModel(<File> {name: 'fake-name', size: 10}, null, 'fakeId');
service.addToQueue(fileFake);
service.uploadFilesInTheQueue(emitter);
const file = service.getQueue();
service.cancelUpload(...file);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/fakeId/content?include=allowableOperations');
expect(request.method).toBe('PUT');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'json',
responseText: {
entry: {
id: 'myNodeId',
properties: {
'cm:versionLabel': '1.1'
}
}
}
});
});
it('If newVersion is set, name should be a param', () => {
const emitter = new EventEmitter();
const filesFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
{ newVersion: true }
);
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
expect(uploadFileSpy).toHaveBeenCalledWith(
{
name: 'fake-name',
size: 10
},
undefined,
undefined,
{ newVersion: true },
{
renditions: 'doclib',
include: ['allowableOperations'],
overwrite: true,
majorVersion: undefined,
comment: undefined,
name: 'fake-name'
}
);
});
it('should use custom root folder ID given to the service', (done) => {
const emitter = new EventEmitter();
const emitterDisposable = emitter.subscribe((e) => {
expect(e.value).toBe('File uploaded');
emitterDisposable.unsubscribe();
done();
});
const filesFake = new FileModel(
<File> { name: 'fake-file-name', size: 10 },
<FileUploadOptions> { parentId: '123', path: 'fake-dir' }
);
service.addToQueue(filesFake);
service.uploadFilesInTheQueue(emitter);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('http://localhost:9876/ecm/alfresco/api/-default-/public/alfresco/versions/1/nodes/123/children?autoRename=true&include=allowableOperations');
expect(request.method).toBe('POST');
jasmine.Ajax.requests.mostRecent().respondWith({
'status': 200,
contentType: 'text/plain',
responseText: 'File uploaded'
});
});
describe('versioningEnabled', () => {
it('should upload with "versioningEnabled" parameter taken from file options', () => {
const model = new FileModel(
<File> { name: 'file-name', size: 10 },
<FileUploadOptions> {
versioningEnabled: true
}
);
service.addToQueue(model);
service.uploadFilesInTheQueue();
expect(uploadFileSpy).toHaveBeenCalledWith(
{
name: 'file-name',
size: 10
},
undefined,
undefined,
{ newVersion: false },
{
include: [ 'allowableOperations' ],
renditions: 'doclib',
versioningEnabled: true,
autoRename: true
}
);
});
it('should not use "versioningEnabled" if not explicitly provided', () => {
const model = new FileModel(
<File> { name: 'file-name', size: 10 },
<FileUploadOptions> {}
);
service.addToQueue(model);
service.uploadFilesInTheQueue();
expect(uploadFileSpy).toHaveBeenCalledWith(
{
name: 'file-name',
size: 10
},
undefined,
undefined,
{ newVersion: false },
{
include: [ 'allowableOperations' ],
renditions: 'doclib',
autoRename: true
}
);
});
});
it('should append the extra upload options to the request', () => {
const filesFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
<FileUploadOptions> {
parentId: '123',
path: 'fake-dir',
secondaryChildren: [<AssocChildBody> { assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [<AssociationBody> { assocType: 'target-assoc', targetId: 'fake-target-id' }]
});
service.addToQueue(filesFake);
service.uploadFilesInTheQueue();
expect(uploadFileSpy).toHaveBeenCalledWith(
{
name: 'fake-name',
size: 10
},
'fake-dir',
'123',
{
newVersion: false,
parentId: '123',
path: 'fake-dir',
secondaryChildren: [<AssocChildBody> { assocType: 'assoc-1', childId: 'child-id' }],
association: { assocType: 'fake-assoc' },
targets: [<AssociationBody> { assocType: 'target-assoc', targetId: 'fake-target-id' }]
},
{
renditions: 'doclib',
include: ['allowableOperations'],
autoRename: true
}
);
});
it('should start downloading the next one if a file of the list is aborted', (done) => {
service.fileUploadAborted.subscribe((e) => {
expect(e).not.toBeNull();
});
service.fileUploadCancelled.subscribe((e) => {
expect(e).not.toBeNull();
done();
});
const fileFake1 = new FileModel(<File> { name: 'fake-name1', size: 10 });
const fileFake2 = new FileModel(<File> { name: 'fake-name2', size: 10 });
const fileList = [fileFake1, fileFake2];
service.addToQueue(...fileList);
service.uploadFilesInTheQueue();
const file = service.getQueue();
service.cancelUpload(...file);
});
it('should remove from the queue all the files in the excluded list', () => {
const file1 = new FileModel(new File([''], '.git'));
const file2 = new FileModel(new File([''], '.DS_Store'));
const file3 = new FileModel(new File([''], 'desktop.ini'));
const file4 = new FileModel(new File([''], 'readme.md'));
const file5 = new FileModel(new File([''], 'test.git'));
const result = service.addToQueue(file1, file2, file3, file4, file5);
expect(result.length).toBe(1);
expect(result[0]).toBe(file4);
});
it('should skip files if they are in an excluded folder', () => {
const file1: any = { name: 'readmetoo.md', file : { webkitRelativePath: '/rollingPanda/' }};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should match the folder in case insensitive way', () => {
const file1: any = { name: 'readmetoo.md', file : { webkitRelativePath: '/rollingPanda/' }};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should skip files if they are in an excluded folder when path is in options', () => {
const file1: any = { name: 'readmetoo.md', file : {}, options: { path: '/rollingPanda/'}};
const file2: any = { name: 'readme.md', file : { webkitRelativePath: '/test/' }};
const result = service.addToQueue(file1, file2);
expect(result.length).toBe(1);
expect(result[0]).toBe(file2);
});
it('should call onUploadDeleted if file was deleted', () => {
const file = <FileModel> { status: FileUploadStatus.Deleted };
spyOn(service.fileUploadDeleted, 'next');
service.cancelUpload(file);
expect(service.fileUploadDeleted.next).toHaveBeenCalled();
});
it('should call fileUploadError if file has error status', () => {
const file = <any> ({ status: FileUploadStatus.Error });
spyOn(service.fileUploadError, 'next');
service.cancelUpload(file);
expect(service.fileUploadError.next).toHaveBeenCalled();
});
it('should call fileUploadCancelled if file is in pending', () => {
const file = <any> ({ status: FileUploadStatus.Pending });
spyOn(service.fileUploadCancelled, 'next');
service.cancelUpload(file);
expect(service.fileUploadCancelled.next).toHaveBeenCalled();
});
it('Should not pass rendition if it is disabled', () => {
mockProductInfo.next({ status: { isThumbnailGenerationEnabled: false } } as EcmProductVersionModel);
const filesFake = new FileModel(
<File> { name: 'fake-name', size: 10 },
{ newVersion: true}
);
service.addToQueue(filesFake);
service.uploadFilesInTheQueue();
expect(uploadFileSpy).toHaveBeenCalledWith(
{
name: 'fake-name',
size: 10
},
undefined,
undefined,
{ newVersion: true },
{
include: ['allowableOperations'],
overwrite: true,
majorVersion: undefined,
comment: undefined,
name: 'fake-name'
}
);
});
}); | the_stack |
// check out PR#54998 for the possibility of a rewrite (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/54998)
// as well as this branch: https://github.com/vanitasboi/DefinitelyTyped/tree/steam-user-rewrite
/// <reference types="node" />
import type SteamID = require('steamid');
import type ByteBuffer = require('bytebuffer');
import EventEmitter = require('events');
import SteamChatRoomClient = require('./components/chatroom');
export = SteamUser;
declare class SteamUser extends EventEmitter {
constructor(options?: Options);
/**
* Formats a currency value and returns a string
*/
static formatCurrency(amount: number, currency: SteamUser.ECurrencyCode): string;
// PROPERTIES
/**
* Use this object to chat with friends and chat rooms.
*/
chat: SteamChatRoomClient;
/**
* `null` if not connected, a `SteamID` containing your SteamID otherwise.
*/
steamID: SteamID | null;
/**
* An object containing options for this `SteamUser`. Read-only; use `setOption` or `setOptions` to change an option.
*/
readonly options: Options;
/**
* Only defined if you're currently logged on. This is your public IP as reported by Steam, in "x.x.x.x" format.
*/
publicIP: string;
/**
* Only defined if you're currently logged on. This is your cell (region ID) on the Steam network.
*/
cellID: number;
/**
* Only defined if you're currently logged on. This is your vanity URL (the part that goes after `/id/` in your profile URL). Falsy if you don't have one.
*/
vanityURL: string | null;
/**
* An object containing information about your account. `null` until `accountInfo` is emitted.
*/
accountInfo: AccountInfo | null;
/**
* An object containing information about your account's email address. `null` until `emailInfo` is emitted.
*/
emailInfo: { adress: string; validated: boolean } | null;
/**
* An object containing information about your account's limitations. `null` until `accountLimitations` is emitted.
*/
limitations: AccountLimitations | null;
/**
* An object containing information about your account's VAC bans. `null` until `vacBans` is emitted.
*/
vac: { numBans: number; appids: number[] } | null;
/**
* An object containing information about your Steam Wallet. `null` until `wallet` is emitted.
*/
wallet: { hasWallet: boolean; currency: SteamUser.ECurrencyCode; balance: number } | null;
/**
* An array containing license data for the packages which your Steam account owns. `null` until `licenses` is emitted.
*/
licenses: Array<Record<string, any>>;
/**
* An array containing gifts and guest passes you've received but haven't accepted (to your library or to your inventory) or declined. `null` until `gifts` is emitted.
*/
gifts: Gift[];
/**
* An object containing persona data about all Steam users we've encountered or requested data for.
* Key are 64-bit SteamIDs, and values are identical to the objects received in the user event.
* This property may not be updated unless you set your instance to online.
*/
users: Record<string, any>;
/**
* An object containing information about all Steam groups we've encountered.
* Keys are 64-bit SteamIDs, and values are identical to those received in the group event.
* This property may not be updated unless you set your instance to online.
*/
groups: Record<string, any>;
/**
* An object containing information about all legacy chat rooms we're in. Keys are 64-bit SteamIDs.
*/
chats: Record<string, Chat>;
/**
* An object whose keys are 64-bit SteamIDs, and whose values are values from the `EFriendRelationship` enum.
* When we get unfriended, instead of setting the value to `EFriendRelationship.None`, the key is deleted from the object entirely.
* This isn't populated after logon until `friendsList` is emitted.
*/
myFriends: Record<string, SteamUser.EFriendRelationship>;
/**
* An object whose keys are 64-bit SteamIDs, and whose values are from the `EClanRelationship` enum.
* When we leave a group, instead of setting the value to `EClanRelationship.None`, the key is deleted from the object entirely.
* This isn't populated after logon until `groupList` is emitted.
*/
myGroups: Record<string, SteamUser.EClanRelationship>;
/**
* An object containing your friend groups (in the official client, these are called tags). Keys are numeric group IDs.
*/
myFriendGroups: Record<string, { name: string; members: SteamID[] }>;
/**
* An object containing the nicknames you have assigned to other users.
* Keys are numeric 64-bit SteamIDs, properties are strings containing that user's nickname.
* This is empty until `nicknameList` is emitted.
*/
myNicknames: Record<string, string>;
/**
* An object containing cached data about known apps and packages. Only useful if the `enablePicsCache` option is `true`.
*/
picsCache: { changenumber: number; apps: Record<string, any>; packages: Record<string, any> };
/**
* Contains the name of this package. This allows other modules to verify interoperability.
*/
packageName: 'steam-user';
/**
* Contains the version of this package. For example, "4.2.0". This allows other modules to verify interoperability.
*/
packageVersion: string;
// EVENTS
on<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
once<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
off<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
removeListener<K extends keyof Events>(event: K, listener: (...args: Events[K]) => void): this;
removeAllListeners(event?: keyof Events): this;
/**
* Set a configuration option.
* @param option
* @param value
*/
setOption(option: keyof Options, value: any): void;
/**
* Set one or more configuration options
* @param options
*/
setOptions(options: Options): void;
/**
* Set a sentry file
* @param sentry Binary Sentry File
*/
setSentry(sentry: Buffer | null): void;
logOn(details?: LogOnDetailsAnon | LogOnDetailsNamePass | LogOnDetailsNameKey | LogOnDetailsNameToken): void;
/**
* Log off of Steam gracefully.
*/
logOff(): void;
relog(): void;
webLogOn(): void;
requestValidationEmail(callback?: (err: Error | null) => void): Promise<void>;
/**
* Start the process to enable TOTP two-factor authentication for your account
* @param [callback] - Called when an activation SMS has been sent.
*/
enableTwoFactor(callback?: (err: Error | null, response: Record<string, any>) => void): Promise<Record<string, any>>;
/**
* Finalize the process of enabling TOTP two-factor authentication
* @param secret - Your shared secret
* @param activationCode - The activation code you got in your email
* @param [callback] - Called with a single Error argument, or null on success
*/
finalizeTwoFactor(secret: Buffer, activationCode: string, callback?: (err: Error | null) => void): Promise<void>;
getSteamGuardDetails(callback?: (
err: Error | null,
canTrade: boolean,
isSteamGuardEnabled: boolean,
timestampSteamGuardEnabled: Date | null,
timestampMachineSteamGuardEnabled: Date | null,
isTwoFactorEnabled: boolean,
timestampTwoFactorEnabled: Date | null,
isPhoneVerified: boolean,
) => void,
): Promise<SteamGuardDetails>;
getCredentialChangeTimes(callback?: (
err: Error | null,
timestampLastPasswordChange: Date | null,
timestampLastPasswordReset: Date | null,
timestampLastEmailChange: Date | null,
) => void,
): Promise<CredentialChangeTimes>;
getAuthSecret(callback?: (err: Error | null, secretID: number, key: Buffer) => void): Promise<AuthSecret>;
/**
* Get your account's profile privacy settings.
* @param [callback]
*/
getPrivacySettings(callback?: (err: Error | null, response: PrivacySettings) => void): Promise<PrivacySettings>;
/**
* Kick any other session logged into your account which is playing a game from Steam.
* @param [callback] - Single err parameter
*/
kickPlayingSession(callback?: (err: Error | null) => void): Promise<void>;
/**
* Tell Steam that you're "playing" zero or more games.
* @param apps - Array of integers (AppIDs) or strings (non-Steam game names) for the games you're playing. Empty to play nothing.
* @param [force=false] If true, kick any other sessions logged into this account and playing games from Steam
*/
gamesPlayed(apps: number | string | PlayedGame | Array<number | string | PlayedGame>, force?: boolean): void;
/**
* Get count of people playing a Steam app. Use appid 0 to get number of people connected to Steam.
* @param appid
* @param [callback] - Args (eresult, player count)
*/
getPlayerCount(appid: number, callback?: (err: Error | null, playerCount: number) => void): Promise<{ playerCount: number }>;
/**
* Query the GMS for a list of game server IPs, and their current player counts.
* @param conditions - A filter string (https://mckay.media/hEW8A) or object
* @param [callback]
*/
serverQuery(conditions: ServerQueryConditions | string, callback?: (err: Error | null, servers: ServerQueryResponse) => void): Promise<ServerQueryResponse>;
/**
* Get a list of servers including game data.
* @param filter - A filter string (https://mckay.media/hEW8A)
* @param [callback]
*/
getServerList(filter: string, limit?: number, callback?: (err: Error | null, servers: Server) => void): Promise<Server>;
/**
* Get the associated SteamIDs for given server IPs.
* @param ips
* @param [callback]
*/
getServerSteamIDsByIP(ips: string[], callback?: (err: Error | null, servers: Record<string, SteamID>) => void): Promise<{ servers: Record<string, SteamID> }>;
/**
* Get the associated IPs for given server SteamIDs.
* @param steamids
* @param [callback]
*/
getServerIPsBySteamID(steamids: Array<SteamID | string>, callback?: (err: Error | null, servers: Record<string, string>) => void): Promise<{ servers: Record<string, string> }>;
/**
* Get a list of apps or packages which have changed since a particular changenumber.
* @param sinceChangenumber - Changenumber to get changes since. Use 0 to get the latest changenumber, but nothing else
* @param [callback] - Args (current changenumber, array of appids that changed, array of packageids that changed)
*/
getProductChanges(sinceChangenumber: number, callback?: (
err: Error | null,
currentChangenumber: number,
appChanges: AppChanges,
packageChanges: PackageChanges,
) => void,
): Promise<ProductChanges>;
/**
* Get info about some apps and/or packages from Steam.
* @param apps - Array of AppIDs. May be empty. May also contain objects with keys {appid, access_token}
* @param packages - Array of package IDs. May be empty. May also contain objects with keys {packageid, access_token}
* @param [inclTokens=false] - If true, automatically retrieve access tokens if needed
* @param [callback] - Args (array of app data, array of package data, array of appids that don't exist, array of packageids that don't exist)
* @param [requestType] - Don't touch
*/
getProductInfo(apps: Array<number | App>, packages: Array<number | Package>, inclTokens?: boolean, callback?: (
err: Error | null,
apps: Record<number, AppInfo>,
packages: Record<number, PackageInfo>,
unknownApps: number[],
unknownPackages: number[],
) => void,
): Promise<ProductInfo>;
/**
* Get access tokens for some apps and/or packages
* @param apps - Array of appids
* @param packages - Array of packageids
* @param [callback] - First arg is an object of (appid => access token), second is the same for packages, third is array of appids for which tokens are denied, fourth is the same for packages
*/
getProductAccessToken(apps: number[], packages: number[], callback?: (
err: Error | null,
appTokens: Record<string, string>,
packageTokens: Record<string, string>,
appDeniedTokens: number[],
packageDeniedTokens: number[],
) => void,
): Promise<ProductAccessTokens>;
/**
* Get list of appids this account owns. Only works if enablePicsCache option is enabled and appOwnershipCached event
* has been emitted.
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
getOwnedApps(excludeSharedLicenses?: boolean): number[];
/**
* Check if this account owns an app. Only works if enablePicsCache option is enabled and appOwnershipCached event
* has been emitted.
* @param appid
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
ownsApp(appid: number, excludeSharedLicenses?: boolean): boolean;
/**
* has been emitted.
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
getOwnedDepots(excludeSharedLicenses?: boolean): number[];
/**
* Check if this account owns a depot. Only works if enablePicsCache option is enabled and appOwnershipCached event
* has been emitted.
* @param depotid
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
ownsDepot(depotid: number, excludeSharedLicenses?: boolean): boolean;
/**
* has been emitted.
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
getOwnedPackages(excludeSharedLicenses?: boolean): number[];
/**
* Check if this account owns a package. Only works if enablePicsCache option is enabled and appOwnershipCached event
* has been emitted.
* @param packageid
* @param [excludeSharedLicenses=false] - Pass true to exclude licenses that we have through family sharing
*/
ownsPackage(packageid: number, excludeSharedLicenses?: boolean): boolean;
/**
* Get the localized names for given store tags.
* @param language - The full name of the language you're interested in, e.g. "english" or "spanish"
* @param tagIDs - The IDs of the tags you're interested in
* @param [callback]
*/
getStoreTagNames(language: string, tagIDs: number[], callback?: (err: Error | null, tags: StoreTagNames) => void): Promise<{ tags: StoreTagNames }>;
/**
* Get details for some UGC files.
* @param ids
* @param [callback]
*/
getPublishedFileDetails(ids: number | number[], callback?: (err: Error | null, files: PublishedFileDetails) => void): Promise<PublishedFileDetails>;
/**
* Remove a friend from your friends list (or decline an invitiation)
* @param steamID - Either a SteamID object of the user to remove, or a string which can parse into one.
*/
removeFriend(steamID: SteamID | string): void;
/**
* Set your persona online state and optionally name.
* @param state - Your new online state
* @param [name] - Optional. Set a new profile name.
*/
setPersona(state: SteamUser.EPersonaState, name?: string): void;
/**
* Set your current UI mode (displays next to your Steam online status in friends)
* @param mode - Your new UI mode
*/
setUIMode(mode: SteamUser.EClientUIMode): void;
/**
* Send (or accept) a friend invitiation.
* @param steamID - Either a SteamID object of the user to add, or a string which can parse into one.
* @param [callback] - Optional. Called with `err` and `name` parameters on completion.
*/
addFriend(steamID: SteamID | string, callback?: (err: Error | null, personaName: string) => void): Promise<{ personaName: string }>;
/**
* Block all communication with a user.
* @param steamID - Either a SteamID object of the user to block, or a string which can parse into one.
* @param [callback] - Optional. Called with an `err` parameter on completion.
*/
blockUser(steamID: SteamID | string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Unblock all communication with a user.
* @param steamID - Either a SteamID object of the user to unblock, or a string which can parse into one.
* @param [callback] - Optional. Called with an `err` parameter on completion.
*/
unblockUser(steamID: SteamID | string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Create a new quick-invite link that can be used by any Steam user to directly add you as a friend.
* @param [options]
* @param [callback]
*/
createQuickInviteLink(options?: CreateQuickInviteLinkOptions, callback?: (err: Error | null, response: QuickInviteLink) => void): Promise<QuickInviteLink>;
/**
* Get a list of friend quick-invite links for your account.
* @param [callback]
*/
listQuickInviteLinks(callback?: (err: Error | null, response: QuickInviteLink[]) => void): Promise<QuickInviteLink[]>;
/**
* Revoke an active quick-invite link.
* @param linkOrToken - Either the full link, or just the token from the link
* @param [callback]
*/
revokeQuickInviteLink(linkOrToken: string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Get the SteamID to whom a quick-invite link belongs.
* @param link
*/
getQuickInviteLinkSteamID(link: string): SteamID | null;
/**
* Check whether a given quick-invite link is valid.
* @param link
* @param [callback]
*/
checkQuickInviteLinkValidity(link: string, callback?: (err: Error | null, response: QuickInviteLinkValidity) => void): Promise<QuickInviteLinkValidity>;
/**
* Redeem a quick-invite link and add the sender to your friends list.
* @param link
* @param [callback]
*/
redeemQuickInviteLink(link: string, callback?: (err: Error | null) => void): Promise<any>;
/**
* Requests information about one or more user profiles.
* @param steamids - An array of SteamID objects or strings which can parse into them.
* @param [callback] - Optional. Called with `err`, and an object whose keys are 64-bit SteamIDs as strings, and whose values are persona objects.
*/
getPersonas(steamids: Array<SteamID | string>, callback?: (
err: Error | null,
personas: Record<string, any>,
) => void
): Promise<{ personas: Record<string, any> }>; // maybe specify the response further?
/**
* Upload some rich presence data to Steam.
* @param appid
* @param richPresence
*/
uploadRichPresence(appid: number, richPresence: Record<string, string>): void;
/**
* Get the localization keys for rich presence for an app on Steam.
* @param appID - The app you want rich presence localizations for
* @param [language] - The full name of the language you want localizations for (e.g. "english" or "spanish"); defaults to language passed to constructor
* @param [callback]
*/
getAppRichPresenceLocalization(appID: number, language: string, callback?: (
err: Error | null,
response: { tokens: Record<string, string> },
) => void
): Promise<{ tokens: Record<string, string> }>;
/**
* Request rich presence data of one or more users for an appid.
* @param appid - The appid to get rich presence data for
* @param steamIDs - SteamIDs of users to request rich presence data for
* @param [language] - Language to get localized strings in. Defaults to language passed to constructor.
* @param [callback] - Called or resolved with 'users' property with each key being a SteamID and value being the rich presence response if received
*/
requestRichPresence(appid: number, steamIDs: Array<SteamID | string>, language: string, callback?: (
err: Error | null,
response: { users: Record<string, { richPresence: RichPresence; localizedString: string | null }> },
) => void
): Promise<{ users: Record<string, { richPresence: RichPresence; localizedString: string | null }> }>;
/**
* Gets the Steam Level of one or more Steam users.
* @param steamids - An array of SteamID objects, or strings which can parse into one.
* @param [callback] - Called on completion with `err`, and an object whose keys are 64-bit SteamIDs as strings, and whose values are Steam Level numbers.
*/
getSteamLevels(steamids: Array<SteamID | string>, callback?: (err: Error | null, users: Record<string, number>) => void): Promise<Record<string, number>>;
/**
* Get persona name history for one or more users.
* @param userSteamIDs - SteamIDs of users to request aliases for
* @param [callback]
*/
getAliases(userSteamIDs: Array<SteamID | string>, callback?: (
err: Error | null,
users: Record<string, { name: string; name_since: Date }>,
) => void
): Promise<Record<string, { name: string; name_since: Date }>>;
/**
* Get the list of nicknames you've given to other users.
* @param [callback]
*/
getNicknames(callback?: (err: Error | null, nicknames: Record<string, string>) => void): Promise<{ nicknames: Record<string, string> }>;
/**
* Set a friend's private nickname.
* @param steamID
* @param nickname
* @param [callback]
*/
setNickname(steamID: SteamID | string, nickname: string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Get the level of your game badge (and also your Steam level).
* @param appid - AppID of game in question
* @param [callback]
*/
getGameBadgeLevel(appid: number, callback?: (
err: Error | null,
steamLevel?: number,
regularBadgeLevel?: number,
foilBadgeLavel?: number,
) => void
): Promise<{ steamLevel: number; regularBadgeLevel: number; foilBadgeLavel: number }>;
/**
* Get the list of a user's owned apps.
* @param steamID - Either a SteamID object or a string that can parse into one
* @param [options]
* @param [callback]
*/
getUserOwnedApps(steamID: SteamID | string, options?: GetUserOwnedAppsOptions, callback?: (
err: Error | null,
response: UserOwnedApps,
) => void
): Promise<UserOwnedApps>;
/**
* Get a listing of profile items you own.
* @param [options]
* @param [callback]
*/
getOwnedProfileItems(options?: { language: string }, callback?: (
err: Error | null,
response: ProfileItems,
) => void
): Promise<ProfileItems>;
/**
* Get a user's equipped profile items.
* @param steamID - Either a SteamID object or a string that can parse into one
* @param [options]
* @param [callback]
*/
getEquippedProfileItems(steamID: SteamID | string, options?: { language: string }, callback?: (
err: Error | null,
response: ProfileItems,
) => void
): Promise<ProfileItems>;
/**
* Change your current profile background.
* @param backgroundAssetID
* @param [callback]
*/
setProfileBackground(backgroundAssetID: number, callback?: (err: Error | null) => void): Promise<void>;
/**
* Invites a user to a Steam group. Only send group invites in response to a user's request; sending automated group
* invites is a violation of the Steam Subscriber Agreement and can get you banned.
* @param userSteamID - The SteamID of the user you're inviting as a SteamID object, or a string that can parse into one
* @param groupSteamID - The SteamID of the group you're inviting the user to as a SteamID object, or a string that can parse into one
*/
inviteToGroup(usersteamID: SteamID | string, groupsteamID: SteamID | string): void;
/**
* Respond to an incoming group invite.
* @param groupSteamID - The group you were invited to, as a SteamID object or a string which can parse into one
* @param accept - true to join the group, false to ignore invitation
*/
respondToGroupInvite(groupsteamID: SteamID | string, accept: boolean): void;
/**
* Creates a friends group (or tag)
* @param groupName - The name to create the friends group with
* @param [callback]
*/
createFriendsGroup(groupName: string, callback?: (err: Error | null, groupID: number) => void): Promise<{ groupID: number }>;
/**
* Deletes a friends group (or tag)
* @param groupID - The friends group id
* @param [callback]
*/
deleteFriendsGroup(groupID: number, callback?: (err: Error | null) => void): Promise<void>;
/**
* Rename a friends group (tag)
* @param groupID - The friends group id
* @param newName - The new name to update the friends group with
* @param [callback]
*/
renameFriendsGroup(groupID: number, newName: string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Add an user to friends group (tag)
* @param groupID - The friends group
* @param userSteamID - The user to invite to the friends group with, as a SteamID object or a string which can parse into one
* @param [callback]
*/
addFriendToGroup(groupID: number, userSteamID: SteamID | string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Remove an user to friends group (tag)
* @param groupID - The friends group
* @param userSteamID - The user to remove from the friends group with, as a SteamID object or a string which can parse into one
* @param [callback]
*/
removeFriendFromGroup(groupID: any, usersteamID: SteamID | string, callback?: (err: Error | null) => void): Promise<void>;
trade(steamID: SteamID | string): void;
cancelTradeRequest(steamID: SteamID | string): void;
/**
* Get the list of currently-available content servers.
* @param language
* @param appid
* @param classes
* @param [callback]
*/
getAssetClassInfo(language: string, appid: number, classes: Array<{ classid: number, instanceid?: number }>, callback?: (
err: Error | null,
descriptions: Array<Record<string, any>>,
) => void
): Promise<{ descriptions: Array<Record<string, any>> }>;
/**
* Gets your account's trade URL.
* @param [callback]
*/
getTradeURL(callback?: (err: Error | null, response: TradeURL) => void): Promise<TradeURL>;
/**
* Makes a new trade URL for your account.
* @param [callback]
*/
changeTradeURL(callback?: (err: Error | null, response: TradeURL) => void): Promise<TradeURL>;
/**
* Gets the list of emoticons your account can use.
* @param [callback]
*/
getEmoticonList(callback?: (err: Error | null, response: { emoticons: Record<string, Emoticon> }) => void): Promise<{ emoticons: Record<string, Emoticon> }>;
/**
* Redeem a product code on this account.
* @param key
* @param [callback] - Args (eresult value, SteamUser.EPurchaseResult value, object of (packageid => package names)
*/
redeemKey(key: string, callback?: (
err: Error | null,
purchaseResultDetails: SteamUser.EPurchaseResult,
packageList: Record<string, string>,
) => void
): Promise<{ purchaseResultDetails: SteamUser.EPurchaseResult; packageList: Record<string, string> }>;
/**
* Request licenses for one or more free-on-demand apps.
* @param appIDs
* @param [callback] - Args (err, array of granted packageids, array of granted appids)
*/
requestFreeLicense(appIDs: number[], callback?: (
err: Error | null,
grantedPackageIds: number[],
grantedAppIds: number[],
) => void
): Promise< { grantedPackageIds: number[]; grantedAppIds: number[] }>;
/**
* Request an encrypted appticket for a particular app. The app must be set up on the Steam backend for encrypted apptickets.
* @param appid - The Steam AppID of the app you want a ticket for
* @param [userData] - If the app expects some "user data", provide it here
* @param [callback] - First argument is "err", second is the ticket as a Buffer (on success)
*/
getEncryptedAppTicket(appid: number, userData?: Buffer, callback?: (err: Error | null, encryptedAppTicket: Buffer) => void): Promise<{ encryptedAppTicket: Buffer }>;
//#region "GC INTERACTION"
// https://github.com/DoctorMcKay/node-steam-user/wiki/Game-Coordinator
/**
* Send a message to a GC. You should be currently "in-game" for the specified app for the message to make it.
* @param appid - The ID of the app you want to send a GC message to
* @param msgType - The GC-specific msg ID for this message
* @param protoBufHeader - An object (can be empty) containing the protobuf header for this message, or null if this is not a protobuf message.
* @param payload
* @param [callback] - If this is a job-based message, pass a function here to get the response
*/
sendToGC(appid: number, msgType: number, protoBufHeader: Record<string, any> | null, payload: Buffer | ByteBuffer, callback?: (
appid: number,
msgType: number,
payload: Buffer,
) => void): void;
//#endregion "GC INTERACTION"
//#region "FAMILY SHARING"
// https://github.com/DoctorMcKay/node-steam-user/wiki/Family-Sharing
/**
* Add new borrowers.
* @param borrowersSteamID
* @param [callback]
*/
addAuthorizedBorrowers(borrowersSteamID: Array<SteamID | string> | SteamID | string, callback?: (err: Error | null) => void): Promise<void>;
/**
* Remove borrowers.
* @param borrowersSteamID
* @param [callback]
*/
removeAuthorizedBorrowers(borrowerssteamID: Array<SteamID | string>, callback?: (err: Error | null) => void): Promise<void>;
/**
* Retrieve a list of Steam accounts authorized to borrow your library.
* @param [options]
* @param [callback]
*/
getAuthorizedBorrowers(options?: { includeCanceled?: boolean, includePending ?: boolean }, callback?: (
err: Error | null,
response: { borrowers: Borrowers[] },
) => void
): Promise< { borrowers: Borrowers[] } >;
/**
* Get a list of devices we have authorized.
* @param [options]
* @param [callback]
*/
getAuthorizedSharingDevices(options?: { includeCancelled?: boolean }, callback?: (
err: Error | null,
response: { devices: Device[] }
) => void
): Promise< { devices: Device[] } >;
/**
* Authorize local device for library sharing.
* @param deviceName
* @param [callback]
*/
authorizeLocalSharingDevice(deviceName: string, callback?: (
err: Error | null, response: { deviceToken: string }) => void
): Promise< { deviceToken: string } >;
/**
* Deauthorize a device from family sharing.
* @param deviceToken
* @param [callback]
*/
deauthorizeSharingDevice(deviceToken: string | { deviceToken: string }, callback?: (err: Error | null) => void): Promise<void>;
/**
* Use local device authorizations to allow usage of shared licenses.
* If successful, `licenses` will be emitted with the newly-acquired licenses.
* @param ownerSteamID
* @param deviceToken
*/
activateSharingAuthorization(ownerSteamID: SteamID | string, deviceToken: string | { deviceToken: string }): void;
/**
* Deactivate family sharing authorizations. Removes shared licenses.
*/
deactivateSharingAuthorization(): void;
//#endregion "FAMILY SHARING"
}
//#region "Events"
interface Events {
appLaunched: [appid: number];
appQuit: [appid: number];
receivedFromGC: [appid: number, msgType: number, payload: Buffer];
loggedOn: [details: Record<string, any>, parental: Record<string, any>];
steamGuard: [domain: string | null, callback: (code: string) => void, lastCodeWrong: boolean];
error: [err: Error];
disconnected: [eresult: SteamUser.EResult, msg?: string];
sentry: [sentry: Buffer];
webSession: [sessionID: string, cookies: string[]];
loginKey: [key: string];
newItems: [count: number];
newComments: [count: number, myItems: number, discussions: number];
tradeOffers: [count: number];
communityMessages: [count: number];
offlineMessages: [count: number, friends: SteamID[]];
vanityURL: [url: string];
accountInfo: [name: string, country: string, authedMachines: number, flags: SteamUser.EAccountFlags, facebookID: string, facebookName: string];
emailInfo: [adress: string, validated: boolean];
accountLimitations: [limited: boolean, communityBanned: boolean, locked: boolean, canInviteFriends: boolean];
vacBans: [numBans: number, appids: number[]];
wallet: [hasWallet: boolean, currency: SteamUser.ECurrencyCode, balance: number];
licenses: [licenses: Array<Record<string, any>>];
gifts: [gifts: Gift[]];
appOwnershipCached: [];
changelist: [changenumber: number, apps: number[], packages: number[]];
appUpdate: [appid: number, data: ProductInfo];
packageUpdate: [appid: number, data: ProductInfo];
marketingMessages: [timestamp: Date, messages: Array<{ id: string; url: string; flags: number }>];
tradeRequest: [steamID: SteamID, respond: (accept: boolean) => void];
tradeResponse: [steamID: SteamID, response: SteamUser.EEconTradeResponse, restrictions: TradeRestrictions];
tradeStarted: [steamID: SteamID];
playingState: [blocked: boolean, playingApp: number];
user: [sid: SteamID, user: Record<string, any>];
group: [sid: SteamID, group: Record<string, any>];
groupEvent: [sid: SteamID, headline: string, date: Date, gid: number | string, gameID: number]; // not sure
groupAnnouncement: [sid: SteamID, headline: string, gid: number | string]; // not sure
friendRelationship: [sid: SteamID, relationship: SteamUser.EFriendRelationship];
groupRelationship: [sid: SteamID, relationship: SteamUser.EClanRelationship];
friendsList: [];
friendPersonasLoad: [];
groupList: [];
friendsGroupList: [groups: Record<string, { name: string; members: SteamID[] }>];
nicknameList: [];
nickname: [steamID: SteamID, newNickname: string | null];
lobbyInvite: [inviterID: SteamID, lobbyID: SteamID];
}
//#endregion "Events"
//#region "Helper Types"
type RegionCode = 0x00 | 0x01| 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | 0xFF; // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol#Region_codes
//#endregion "Helper Types"
//#region "Response Types"
type StoreTagNames = Record<string, {name: string, englishName: string}>;
type PublishedFileDetails = Record<string, Record<string, any>>;
//#endregion "Response Types"
//#region "General Interfaces"
interface Options {
localPort?: number | null;
protocol?: SteamUser.EConnectionProtocol;
httpProxy?: string | null;
localAddress?: string | null;
autoRelogin?: boolean;
singleSentryfile?: boolean;
machineIdType?: SteamUser.EMachineIDType;
machineIdFormat?: [string, string, string];
enablePicsCache?: boolean;
language?: string;
picsCacheAll?: boolean;
changelistUpdateInterval?: number;
saveAppTickets?: boolean;
additionalHeaders?: Record<string, string>;
webCompatibilityMode?: boolean;
}
interface CreateQuickInviteLinkOptions {
inviteLimit?: number;
inviteDuration?: number | null;
}
interface PlayedGame {
game_id: number;
game_extra_info: string;
}
interface ServerQueryConditions {
app_id?: number;
geo_location_ip?: string;
region_code?: RegionCode;
filter_text?: string; // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol#Filter
max_servers?: number;
}
interface AppChanges {
appid: number;
change_number: number;
needs_token: boolean;
}
interface PackageChanges {
packageid: number;
change_number: number;
needs_token: boolean;
}
interface App {
appid: number;
access_token: string;
}
interface Package {
packageid: number;
access_token: string;
}
interface AppInfo {
changenumber: number;
missingToken: boolean;
appinfo: any; // too complex to describe
}
interface PackageInfo {
changenumber: number;
missingToken: boolean;
packageinfo: any; // too complex to describe
}
interface RichPresence {
status: string;
version: string;
time?: string;
'game:state': string;
steam_display: string;
connect: string;
}
interface OwnedApp {
appid: number;
name: string;
playtime_2weeks: number | null;
playtime_forever: number;
img_icon_url: string;
img_logo_url: string;
has_community_visible_stats: boolean;
playtime_windows_forever: number;
playtime_mac_forever: number;
playtime_linux_forever: number;
}
interface GetUserOwnedAppsOptions {
includePlayedFreeGames?: boolean;
filterAppids?: number[];
includeFreeSub?: boolean;
}
interface ProfileItem {
communityitemid: number;
image_small: string | null;
image_large: string | null;
name: string;
item_title: string;
item_description: string;
appid: number;
item_type: unknown; // could be improved
item_class: unknown; // could be improved
movie_webm: string;
movie_mp4: string;
equipped_flags: unknown; // could be improved
}
interface Emoticon {
name: string;
count: number;
time_last_used: Date | null;
use_count: number;
time_received: Date | null;
}
interface Borrowers {
steamid: SteamID;
isPending: boolean;
isCanceled: boolean;
timeCreated: Date;
}
interface Device {
deviceToken: string;
deviceName: string;
isPending: boolean;
isCanceled: boolean;
isLimited: boolean;
lastTimeUsed: Date | null;
lastBorrower: SteamID | null;
lastAppPlayed: Date | null;
}
interface AccountInfo {
name: string;
country: string;
authedMachines: number;
flags: SteamUser.EAccountFlags;
facebookID: string;
facebookName: string;
}
interface AccountLimitations {
limited: boolean;
communityBanned: boolean;
locked: boolean;
canInviteFriends: boolean;
}
interface Gift {
gid: string;
packageid: number;
TimeCreated: Date;
TimeExpiration: Date;
TimeSent: Date;
TimeAcked: Date;
TimeRedeemed: null; // appears to always be null
RecipientAddress: ''; // appears to alway be ''
SenderAddress: ''; // appears to alway be ''
SenderName: string;
}
interface Chat {
name: string | null;
private: boolean;
invisibleToFriends: boolean;
officersOnlyChat: boolean;
unjoinable: boolean;
members: {
rank: SteamUser.EClanRank;
permissions: SteamUser.EChatPermission;
};
}
interface TradeRestrictions {
steamguardRequiredDays?: number;
newDeviceCooldownDays?: number;
defaultPasswordResetProbationDays?: number;
passwordResetProbationDays?: number;
defaultEmailChangeProbationDays?: number;
emailChangeProbationDays?: number;
}
//#endregion "General Interfaces"
//#region "Response Interfaces"
interface QuickInviteLinkValidity {
valid: boolean;
steamid: SteamID;
invite_duration: number | null;
}
interface TradeURL {
token: string;
url: string;
}
interface QuickInviteLink {
invite_link: string;
invite_token: string;
invite_limit: number;
invite_duration: number | null;
time_created: Date;
valid: boolean;
}
interface LogOnDetailsAnon {
password?: string;
loginKey?: string;
webLogonToken?: string;
steamID?: SteamID | string;
authCode?: string;
twoFactorCode?: string;
rememberPassword?: boolean;
logonID?: number | string;
machineName?: string;
clientOS?: SteamUser.EOSType;
dontRememberMachine?: boolean;
autoRelogin?: boolean;
}
interface LogOnDetailsNamePass {
accountName: string;
password: string;
authCode?: string;
twoFactorCode?: string;
rememberPassword?: boolean;
logonID?: number | string;
machineName?: string;
clientOS?: SteamUser.EOSType;
dontRememberMachine?: boolean;
autoRelogin?: boolean;
}
interface LogOnDetailsNameKey {
accountName: string;
loginKey: string;
rememberPassword?: boolean;
logonID?: number | string;
machineName?: string;
clientOS?: SteamUser.EOSType;
autoRelogin?: boolean;
}
interface LogOnDetailsNameToken {
accountName: string;
webLogonToken: string;
steamID: SteamID | string;
autoRelogin?: boolean;
}
interface SteamGuardDetails {
canTrade: boolean;
isSteamGuardEnabled: boolean;
timestampSteamGuardEnabled: Date | null;
timestampMachineSteamGuardEnabled: Date | null;
isTwoFactorEnabled: boolean;
timestampTwoFactorEnabled: Date | null;
isPhoneVerified: boolean;
}
interface CredentialChangeTimes {
timestampLastPasswordChange: Date | null;
timestampLastPasswordReset: Date | null;
timestampLastEmailChange: Date | null;
}
interface AuthSecret {
secretID: number;
key: Buffer;
}
interface PrivacySettings {
privacy_state: SteamUser.EPrivacyState;
privacy_state_inventory: SteamUser.EPrivacyState;
privacy_state_gifts: SteamUser.EPrivacyState;
privacy_state_ownedgames: SteamUser.EPrivacyState;
privacy_state_playtime: SteamUser.EPrivacyState;
privacy_state_friendslist: SteamUser.EPrivacyState;
}
interface ServerQueryResponse {
ip: string;
port: number;
players: number;
gameport: number;
}
interface Server {
addr: string;
specport: number | null;
steamid: SteamID;
name: string;
appid: number;
gamedir: string;
version: string;
product: string;
region: RegionCode;
players: number;
max_players: number;
bots: number;
map: string;
secure: boolean;
dedicated: boolean;
os: 'w' | 'l';
gametype: string;
}
interface ProductChanges {
currentChangenumber: number;
appChanges: AppChanges;
packageChanges: PackageChanges;
}
interface ProductInfo {
apps: Record<number, AppInfo>;
packages: Record<number, PackageInfo>;
unknownApps: number[];
unknownPackages: number[];
}
interface ProductAccessTokens {
appTokens: Record<string, string>;
packageTokens: Record<string, string>;
appDeniedTokens: number[];
packageDeniedTokens: number[];
}
interface UserOwnedApps {
game_count: number;
games: OwnedApp[];
}
interface ProfileItems {
profile_backgrounds: ProfileItem[];
mini_profile_backgrounds: ProfileItem[];
avatar_frames: ProfileItem[];
animated_avatars: ProfileItem[];
profile_modifiers: ProfileItem[];
}
//#endregion "Response Interfaces"
declare namespace SteamUser {
//#region "ENUMS"
enum EAccountFlags {
NormalUser = 0,
PersonaNameSet = 1,
Unbannable = 2,
PasswordSet = 4,
Support = 8,
Admin = 16,
Supervisor = 32,
AppEditor = 64,
HWIDSet = 128,
PersonalQASet = 256,
VacBeta = 512,
Debug = 1024,
Disabled = 2048,
LimitedUser = 4096,
LimitedUserForce = 8192,
EmailValidated = 16384,
MarketingTreatment = 32768,
OGGInviteOptOut = 65536,
ForcePasswordChange = 131072,
ForceEmailVerification = 262144,
LogonExtraSecurity = 524288,
LogonExtraSecurityDisabled = 1048576,
Steam2MigrationComplete = 2097152,
NeedLogs = 4194304,
Lockdown = 8388608,
MasterAppEditor = 16777216,
BannedFromWebAPI = 33554432,
ClansOnlyFromFriends = 67108864,
GlobalModerator = 134217728,
ParentalSettings = 268435456,
ThirdPartySupport = 536870912,
NeedsSSANextSteamLogon = 1073741824,
}
enum EAccountType {
Invalid = 0,
Individual = 1,
Multiseat = 2,
GameServer = 3,
AnonGameServer = 4,
Pending = 5,
ContentServer = 6,
Clan = 7,
Chat = 8,
ConsoleUser = 9,
AnonUser = 10,
}
enum EActivationCodeClass {
WonCDKey = 0,
ValveCDKey = 1,
Doom3CDKey = 2,
DBLookup = 3,
Steam2010Key = 4,
Max = 5,
Test = 2147483647,
Invalid = 4294967295,
}
enum EAppAssociationType {
Invalid = 0,
Publisher = 1,
Developer = 2,
Franchise = 3,
}
enum EAppControllerSupportLevel {
None = 0,
Partial = 1,
Full = 2,
}
enum EAppInfoSection {
Unknown = 0,
All = 1,
First = 2,
Common = 2,
Extended = 3,
Config = 4,
Stats = 5,
Install = 6,
Depots = 7,
VAC = 8,
VAC_UNUSED = 8,
DRM = 9,
DRM_UNUSED = 9,
UFS = 10,
OGG = 11,
Items = 12,
ItemsUNUSED = 12,
Policies = 13,
SysReqs = 14,
Community = 15,
Store = 16,
Localization = 17,
Broadcastgamedata = 18,
Computed = 19,
Albummetadata = 20,
}
enum EAppType {
Invalid = 0,
Game = 1,
Application = 2,
Tool = 4,
Demo = 8,
Deprected = 16,
DLC = 32,
Guide = 64,
Driver = 128,
Config = 256,
Hardware = 512,
Franchise = 1024,
Video = 2048,
Plugin = 4096,
Music = 8192,
Series = 16384,
Comic = 32768,
Beta = 65536,
Shortcut = 1073741824,
DepotOnly = -2147483648,
}
enum EAppUsageEvent {
GameLaunch = 1,
GameLaunchTrial = 2,
Media = 3,
PreloadStart = 4,
PreloadFinish = 5,
MarketingMessageView = 6,
InGameAdViewed = 7,
GameLaunchFreeWeekend = 8,
}
enum EAudioFormat {
None = 0,
'16BitLittleEndian' = 1,
Float = 2,
}
enum EAuthSessionResponse {
OK = 0,
UserNotConnectedToSteam = 1,
NoLicenseOrExpired = 2,
VACBanned = 3,
LoggedInElseWhere = 4,
VACCheckTimedOut = 5,
AuthTicketCanceled = 6,
AuthTicketInvalidAlreadyUsed = 7,
AuthTicketInvalid = 8,
PublisherIssuedBan = 9,
}
enum EBillingType {
NoCost = 0,
BillOnceOnly = 1,
BillMonthly = 2,
ProofOfPrepurchaseOnly = 3,
GuestPass = 4,
HardwarePromo = 5,
Gift = 6,
AutoGrant = 7,
OEMTicket = 8,
RecurringOption = 9,
BillOnceOrCDKey = 10,
Repurchaseable = 11,
FreeOnDemand = 12,
Rental = 13,
CommercialLicense = 14,
FreeCommercialLicense = 15,
NumBillingTypes = 16,
}
enum EBroadcastChatPermission {
Public = 0,
OwnsApp = 1,
}
enum EBroadcastWatchLocation {
Invalid = 0,
SteamTV_Tab = 1,
SteamTV_WatchParty = 2,
Chat_Tab = 3,
Chat_WatchParty = 4,
CommunityPage = 5,
StoreAppPage = 6,
InGame = 7,
BigPicture = 8,
SalesPage = 9,
CuratorPage = 10,
DeveloperPage = 11,
Chat_Friends = 12,
SteamTV_Web = 13,
}
enum EChatAction {
InviteChat = 1,
Kick = 2,
Ban = 3,
UnBan = 4,
StartVoiceSpeak = 5,
EndVoiceSpeak = 6,
LockChat = 7,
UnlockChat = 8,
CloseChat = 9,
SetJoinable = 10,
SetUnjoinable = 11,
SetOwner = 12,
SetInvisibleToFriends = 13,
SetVisibleToFriends = 14,
SetModerated = 15,
SetUnmoderated = 16,
}
enum EChatActionResult {
Success = 1,
Error = 2,
NotPermitted = 3,
NotAllowedOnClanMember = 4,
NotAllowedOnBannedUser = 5,
NotAllowedOnChatOwner = 6,
NotAllowedOnSelf = 7,
ChatDoesntExist = 8,
ChatFull = 9,
VoiceSlotsFull = 10,
}
enum EChatEntryType {
Invalid = 0,
ChatMsg = 1,
Typing = 2,
InviteGame = 3,
Emote = 4,
LobbyGameStart = 5,
LeftConversation = 6,
Entered = 7,
WasKicked = 8,
WasBanned = 9,
Disconnected = 10,
HistoricalChat = 11,
Reserved1 = 12,
Reserved2 = 13,
LinkBlocked = 14,
}
enum EChatFlags {
Locked = 1,
InvisibleToFriends = 2,
Moderated = 4,
Unjoinable = 8,
}
enum EChatInfoType {
StateChange = 1,
InfoUpdate = 2,
MemberLimitChange = 3,
}
enum EChatMemberStateChange {
Entered = 1,
Left = 2,
Disconnected = 4,
Kicked = 8,
Banned = 16,
VoiceSpeaking = 4096,
VoiceDoneSpeaking = 8192,
}
enum EChatPermission {
Close = 1,
Invite = 2,
Talk = 8,
Kick = 16,
Mute = 32,
SetMetadata = 64,
ChangePermissions = 128,
Ban = 256,
ChangeAccess = 512,
Mask = 1019,
}
enum EChatRoomEnterResponse {
Success = 1,
DoesntExist = 2,
NotAllowed = 3,
Full = 4,
Error = 5,
Banned = 6,
Limited = 7,
ClanDisabled = 8,
CommunityBan = 9,
MemberBlockedYou = 10,
YouBlockedMember = 11,
NoRankingDataLobby = 12,
NoRankingDataUser = 13,
RankOutOfRange = 14,
}
enum EChatRoomGroupAction {
Default = 0,
CreateRenameDeleteChannel = 1,
Kick = 2,
Ban = 3,
Invite = 4,
ChangeTaglineAvatarName = 5,
Chat = 6,
ViewHistory = 7,
ChangeGroupRoles = 8,
ChangeUserRoles = 9,
MentionAll = 10,
SetWatchingBroadcast = 11,
}
enum EChatRoomGroupPermissions {
Default = 0,
Valid = 1,
CanInvite = 2,
CanKick = 4,
CanBan = 8,
CanAdminChannel = 16,
}
enum EChatRoomGroupRank {
Default = 0,
Viewer = 10,
Guest = 15,
Member = 20,
Moderator = 30,
Officer = 40,
Owner = 50,
TestInvalid = 99,
}
enum EChatRoomGroupType {
Default = 0,
Unmoderated = 1,
}
enum EChatRoomJoinState {
Default = 0,
None = 1,
Joined = 2,
TestInvalid = 99,
}
enum EChatRoomMemberStateChange {
Invalid = 0,
Joined = 1,
Parted = 2,
Kicked = 3,
Invited = 4,
RankChanged = 7,
InviteDismissed = 8,
Muted = 9,
Banned = 10,
RolesChanged = 12,
}
enum EChatRoomNotificationLevel {
Invalid = 0,
None = 1,
MentionMe = 2,
MentionAll = 3,
AllMessages = 4,
}
enum EChatRoomServerMessage {
Invalid = 0,
RenameChatRoom = 1,
Joined = 2,
Parted = 3,
Kicked = 4,
Invited = 5,
InviteDismissed = 8,
ChatRoomTaglineChanged = 9,
ChatRoomAvatarChanged = 10,
AppCustom = 11,
}
enum EChatRoomServerMsg {
Invalid = 0,
RenameChatRoom = 1,
Joined = 2,
Parted = 3,
Kicked = 4,
Invited = 5,
InviteDismissed = 8,
ChatRoomTaglineChanged = 9,
ChatRoomAvatarChanged = 10,
AppCustom = 11,
}
enum EChatRoomType {
Friend = 1,
MUC = 2,
Lobby = 3,
}
enum EClanPermission {
Nobody = 0,
Owner = 1,
Officer = 2,
OwnerAndOfficer = 3,
Member = 4,
Moderator = 8,
OGGGameOwner = 16,
NonMember = 128,
}
enum EClanRank {
None = 0,
Owner = 1,
Officer = 2,
Member = 3,
Moderator = 4,
}
enum EClanRelationship {
None = 0,
Blocked = 1,
Invited = 2,
Member = 3,
Kicked = 4,
KickAcknowledged = 5,
PendingApproval = 6,
RequestDenied = 7,
}
enum EClientPersonaStateFlag {
Status = 1,
PlayerName = 2,
QueryPort = 4,
SourceID = 8,
Presence = 16,
Metadata = 32,
LastSeen = 64,
ClanInfo = 128,
UserClanRank = 128,
GameExtraInfo = 256,
GameDataBlob = 512,
ClanTag = 1024,
ClanData = 1024,
Facebook = 2048,
RichPresence = 4096,
Broadcast = 8192,
Watching = 16384,
}
enum EClientStat {
P2PConnectionsUDP = 0,
P2PConnectionsRelay = 1,
P2PGameConnections = 2,
P2PVoiceConnections = 3,
BytesDownloaded = 4,
}
enum EClientStatAggregateMethod {
LatestOnly = 0,
Sum = 1,
Event = 2,
Scalar = 3,
}
enum EContentDeltaChunkDataLocation {
InProtobuf = 0,
AfterProtobuf = 1,
}
enum EContentDownloadSourceType {
Invalid = 0,
CS = 1,
CDN = 2,
LCS = 3,
ProxyCache = 4,
LANPeer = 5,
SLS = 6,
SteamCache = 7,
OpenCache = 8,
LANCache = 9,
}
enum EControllerElementType {
None = -1,
Thumb = 0,
ButtonSteam = 1,
JoystickLeft = 2,
ButtonJoystickLeft = 3,
JoystickRight = 4,
ButtonJoystickRight = 5,
DPad = 6,
ButtonA = 7,
ButtonB = 8,
ButtonX = 9,
ButtonY = 10,
ButtonSelect = 11,
ButtonStart = 12,
ButtonTriggerLeft = 13,
ButtonTriggerRight = 14,
ButtonBumperLeft = 15,
ButtonBumperRight = 16,
ButtonMacro0 = 17,
ButtonMacro1 = 18,
ButtonMacro2 = 19,
ButtonMacro3 = 20,
ButtonMacro4 = 21,
ButtonMacro5 = 22,
ButtonMacro6 = 23,
ButtonMacro7 = 24,
TrackpadCenter = 25,
TrackpadLeft = 26,
TrackpadRight = 27,
Keyboard = 28,
MagnifyingGlass = 29,
ButtonMacro1Finger = 30,
ButtonMacro2Finger = 31,
RecordInput = 32,
PlaybackInput = 33,
Paste = 34,
Max = 35,
}
enum EControllerLayoutType {
Phone = 0,
Tablet = 1,
}
enum ECurrencyCode {
Invalid = 0,
USD = 1,
GBP = 2,
EUR = 3,
CHF = 4,
RUB = 5,
PLN = 6,
BRL = 7,
JPY = 8,
NOK = 9,
IDR = 10,
MYR = 11,
PHP = 12,
SGD = 13,
THB = 14,
VND = 15,
KRW = 16,
TRY = 17,
UAH = 18,
MXN = 19,
CAD = 20,
AUD = 21,
NZD = 22,
CNY = 23,
INR = 24,
CLP = 25,
PEN = 26,
COP = 27,
ZAR = 28,
HKD = 29,
TWD = 30,
SAR = 31,
AED = 32,
ARS = 34,
ILS = 35,
BYN = 36,
KZT = 37,
KWD = 38,
QAR = 39,
CRC = 40,
UYU = 41,
}
enum EDenyReason {
InvalidVersion = 1,
Generic = 2,
NotLoggedOn = 3,
NoLicense = 4,
Cheater = 5,
LoggedInElseWhere = 6,
UnknownText = 7,
IncompatibleAnticheat = 8,
MemoryCorruption = 9,
IncompatibleSoftware = 10,
SteamConnectionLost = 11,
SteamConnectionError = 12,
SteamResponseTimedOut = 13,
SteamValidationStalled = 14,
SteamOwnerLeftGuestUser = 15,
}
enum EDepotFileFlag {
UserConfig = 1,
VersionedUserConfig = 2,
Encrypted = 4,
ReadOnly = 8,
Hidden = 16,
Executable = 32,
Directory = 64,
CustomExecutable = 128,
InstallScript = 256,
Symlink = 512,
}
enum EDisplayStatus {
Invalid = 0,
Launching = 1,
Uninstalling = 2,
Installing = 3,
Running = 4,
Validating = 5,
Updating = 6,
Downloading = 7,
Synchronizing = 8,
ReadyToInstall = 9,
ReadyToPreload = 10,
ReadyToLaunch = 11,
RegionRestricted = 12,
PresaleOnly = 13,
InvalidPlatform = 14,
ParentalBlocked = 15,
PreloadOnly = 16,
PreloadComplete = 16,
BorrowerLocked = 17,
UpdatePaused = 18,
UpdateQueued = 19,
UpdateRequired = 20,
UpdateDisabled = 21,
DownloadPaused = 22,
DownloadQueued = 23,
DownloadRequired = 24,
DownloadDisabled = 25,
LicensePending = 26,
LicenseExpired = 27,
AvailForFree = 28,
AvailToBorrow = 29,
AvailGuestPass = 30,
Purchase = 31,
}
enum EDRMBlobDownloadErrorDetail {
None = 0,
DownloadFailed = 1,
TargetLocked = 2,
OpenZip = 3,
ReadZipDirectory = 4,
UnexpectedZipEntry = 5,
UnzipFullFile = 6,
UnknownBlobType = 7,
UnzipStrips = 8,
UnzipMergeGuid = 9,
UnzipSignature = 10,
ApplyStrips = 11,
ApplyMergeGuid = 12,
ApplySignature = 13,
AppIdMismatch = 14,
AppIdUnexpected = 15,
AppliedSignatureCorrupt = 16,
ApplyValveSignatureHeader = 17,
UnzipValveSignatureHeader = 18,
PathManipulationError = 19,
TargetLocked_Base = 65536,
TargetLocked_Max = 131071,
NextBase = 131072,
}
enum EDRMBlobDownloadType {
Error = 0,
File = 1,
Parts = 2,
Compressed = 4,
AllMask = 7,
IsJob = 8,
HighPriority = 16,
AddTimestamp = 32,
LowPriority = 64,
}
enum EEconTradeResponse {
Accepted = 0,
Declined = 1,
TradeBannedInitiator = 2,
TradeBannedTarget = 3,
TargetAlreadyTrading = 4,
Disabled = 5,
NotLoggedIn = 6,
Cancel = 7,
TooSoon = 8,
TooSoonPenalty = 9,
ConnectionFailed = 10,
AlreadyTrading = 11,
AlreadyHasTradeRequest = 12,
NoResponse = 13,
CyberCafeInitiator = 14,
CyberCafeTarget = 15,
SchoolLabInitiator = 16,
SchoolLabTarget = 16,
InitiatorBlockedTarget = 18,
InitiatorNeedsVerifiedEmail = 20,
InitiatorNeedsSteamGuard = 21,
TargetAccountCannotTrade = 22,
InitiatorSteamGuardDuration = 23,
InitiatorPasswordResetProbation = 24,
InitiatorNewDeviceCooldown = 25,
InitiatorSentInvalidCookie = 26,
NeedsEmailConfirmation = 27,
InitiatorRecentEmailChange = 28,
NeedsMobileConfirmation = 29,
TradingHoldForClearedTradeOffersInitiator = 30,
WouldExceedMaxAssetCount = 31,
DisabledInRegion = 32,
DisabledInPartnerRegion = 33,
OKToDeliver = 50,
}
enum EExternalAccountType {
k_EExternalNone = 0,
k_EExternalSteamAccount = 1,
k_EExternalGoogleAccount = 2,
k_EExternalFacebookAccount = 3,
k_EExternalTwitterAccount = 4,
k_EExternalTwitchAccount = 5,
k_EExternalYouTubeChannelAccount = 6,
k_EExternalFacebookPage = 7,
}
enum EFrameAccumulatedStat {
FPS = 0,
CaptureDurationMS = 1,
ConvertDurationMS = 2,
EncodeDurationMS = 3,
SteamDurationMS = 4,
ServerDurationMS = 5,
NetworkDurationMS = 6,
DecodeDurationMS = 7,
DisplayDurationMS = 8,
ClientDurationMS = 9,
FrameDurationMS = 10,
InputLatencyMS = 11,
GameLatencyMS = 12,
RoundTripLatencyMS = 13,
PingTimeMS = 14,
ServerBitrateKbitPerSec = 15,
ClientBitrateKbitPerSec = 16,
LinkBandwidthKbitPerSec = 17,
PacketLossPercentage = 18,
}
enum EFriendFlags {
None = 0,
Blocked = 1,
FriendshipRequested = 2,
Immediate = 4,
ClanMember = 8,
OnGameServer = 16,
RequestingFriendship = 128,
RequestingInfo = 256,
Ignored = 512,
IgnoredFriend = 1024,
Suggested = 2048,
ChatMember = 4096,
FlagAll = 65535,
}
enum EFriendRelationship {
None = 0,
Blocked = 1,
RequestRecipient = 2,
Friend = 3,
RequestInitiator = 4,
Ignored = 5,
IgnoredFriend = 6,
SuggestedFriend = 7,
}
enum EGameSearchAction {
None = 0,
Accept = 1,
Decline = 2,
Cancel = 3,
}
enum EGameSearchResult {
Invalid = 0,
SearchInProgress = 1,
SearchFailedNoHosts = 2,
SearchGameFound = 3,
SearchCompleteAccepted = 4,
SearchCompleteDeclined = 5,
SearchCanceled = 6,
}
enum EHIDDeviceDisconnectMethod {
Unknown = 0,
Bluetooth = 1,
FeatureReport = 2,
OutputReport = 3,
}
enum EHIDDeviceLocation {
Local = 0,
Remote = 2,
Any = 3,
}
enum EInputMode {
Unknown = 0,
Mouse = 1,
Controller = 2,
MouseAndController = 3,
}
enum EInternalAccountType {
k_EInternalSteamAccountType = 1,
k_EInternalClanType = 2,
k_EInternalAppType = 3,
k_EInternalBroadcastChannelType = 4,
}
enum EIntroducerRouting {
FileShare = 0,
P2PVoiceChat = 1,
P2PNetworking = 2,
}
enum EJSRegisterMethodType {
Invalid = 0,
Function = 1,
Callback = 2,
Promise = 3,
}
enum EKeyEscrowUsage {
StreamingDevice = 0,
}
enum ELauncherType {
Default = 0,
PerfectWorld = 1,
Nexon = 2,
CmdLine = 3,
CSGO = 4,
ClientUI = 5,
Headless = 6,
SteamChina = 7,
SingleApp = 8,
}
enum ELeaderboardDataRequest {
Global = 0,
GlobalAroundUser = 1,
Friends = 2,
Users = 3,
}
enum ELeaderboardDisplayType {
None = 0,
Numeric = 1,
TimeSeconds = 2,
TimeMilliSeconds = 3,
}
enum ELeaderboardSortMethod {
None = 0,
Ascending = 1,
Descending = 2,
}
enum ELeaderboardUploadScoreMethod {
None = 0,
KeepBest = 1,
ForceUpdate = 2,
}
enum ELicenseFlags {
None = 0,
Renew = 1,
RenewalFailed = 2,
Pending = 4,
Expired = 8,
CancelledByUser = 16,
CancelledByAdmin = 32,
LowViolenceContent = 64,
ImportedFromSteam2 = 128,
ForceRunRestriction = 256,
RegionRestrictionExpired = 512,
CancelledByFriendlyFraudLock = 1024,
NotActivated = 2048,
}
enum ELicenseType {
NoLicense = 0,
SinglePurchase = 1,
SinglePurchaseLimitedUse = 2,
RecurringCharge = 3,
RecurringChargeLimitedUse = 4,
RecurringChargeLimitedUseWithOverages = 5,
RecurringOption = 6,
LimitedUseDelayedActivation = 7,
}
enum ELobbyComparison {
EqualToOrLessThan = -2,
LessThan = -1,
Equal = 0,
GreaterThan = 1,
EqualToOrGreaterThan = 2,
NotEqual = 3,
}
enum ELobbyFilterType {
String = 0,
Numerical = 1,
SlotsAvailable = 2,
NearValue = 3,
Distance = 4,
}
enum ELobbyStatus {
Invalid = 0,
Exists = 1,
DoesNotExist = 2,
NotAMember = 3,
}
enum ELobbyType {
Private = 0,
FriendsOnly = 1,
Public = 2,
Invisible = 3,
PrivateUnique = 4,
}
enum ELogFileType {
SystemBoot = 0,
SystemReset = 1,
SystemDebug = 2,
}
enum EMarketingMessageFlags {
None = 0,
HighPriority = 1,
PlatformWindows = 2,
PlatformMac = 4,
PlatformLinux = 8,
}
enum EMMSLobbyStatus {
Invalid = 0,
Exists = 1,
DoesNotExist = 2,
NotAMember = 3,
}
enum EMouseMode {
Unknown = 0,
RelativeCursor = 1,
AbsoluteCursor = 2,
Touch = 3,
Relative = 4,
}
enum EMsg {
Invalid = 0,
Multi = 1,
ProtobufWrapped = 2,
BaseGeneral = 100,
GenericReply = 100,
DestJobFailed = 113,
Alert = 115,
SCIDRequest = 120,
SCIDResponse = 121,
JobHeartbeat = 123,
HubConnect = 124,
Subscribe = 126,
RouteMessage = 127,
RemoteSysID = 128,
AMCreateAccountResponse = 129,
WGRequest = 130,
WGResponse = 131,
KeepAlive = 132,
WebAPIJobRequest = 133,
WebAPIJobResponse = 134,
ClientSessionStart = 135,
ClientSessionEnd = 136,
ClientSessionUpdateAuthTicket = 137,
ClientSessionUpdate = 137,
StatsDeprecated = 138,
Ping = 139,
PingResponse = 140,
Stats = 141,
RequestFullStatsBlock = 142,
LoadDBOCacheItem = 143,
LoadDBOCacheItemResponse = 144,
InvalidateDBOCacheItems = 145,
ServiceMethod = 146,
ServiceMethodResponse = 147,
ClientPackageVersions = 148,
TimestampRequest = 149,
TimestampResponse = 150,
ServiceMethodCallFromClient = 151,
ServiceMethodSendToClient = 152,
BaseShell = 200,
AssignSysID = 200,
Exit = 201,
DirRequest = 202,
DirResponse = 203,
ZipRequest = 204,
ZipResponse = 205,
UpdateRecordResponse = 215,
UpdateCreditCardRequest = 221,
UpdateUserBanResponse = 225,
PrepareToExit = 226,
ContentDescriptionUpdate = 227,
TestResetServer = 228,
UniverseChanged = 229,
ShellConfigInfoUpdate = 230,
RequestWindowsEventLogEntries = 233,
ProvideWindowsEventLogEntries = 234,
ShellSearchLogs = 235,
ShellSearchLogsResponse = 236,
ShellCheckWindowsUpdates = 237,
ShellCheckWindowsUpdatesResponse = 238,
ShellFlushUserLicenseCache = 239,
TestFlushDelayedSQL = 240,
TestFlushDelayedSQLResponse = 241,
EnsureExecuteScheduledTask_TEST = 242,
EnsureExecuteScheduledTaskResponse_TEST = 243,
UpdateScheduledTaskEnableState_TEST = 244,
UpdateScheduledTaskEnableStateResponse_TEST = 245,
ContentDescriptionDeltaUpdate = 246,
BaseGM = 300,
Heartbeat = 300,
ShellFailed = 301,
ExitShells = 307,
ExitShell = 308,
GracefulExitShell = 309,
LicenseProcessingComplete = 316,
SetTestFlag = 317,
QueuedEmailsComplete = 318,
GMReportPHPError = 319,
GMDRMSync = 320,
PhysicalBoxInventory = 321,
UpdateConfigFile = 322,
TestInitDB = 323,
GMWriteConfigToSQL = 324,
GMLoadActivationCodes = 325,
GMQueueForFBS = 326,
GMSchemaConversionResults = 327,
GMSchemaConversionResultsResponse = 328,
GMWriteShellFailureToSQL = 329,
GMWriteStatsToSOS = 330,
GMGetServiceMethodRouting = 331,
GMGetServiceMethodRoutingResponse = 332,
GMConvertUserWallets = 333,
GMTestNextBuildSchemaConversion = 334,
GMTestNextBuildSchemaConversionResponse = 335,
ExpectShellRestart = 336,
HotFixProgress = 337,
BaseAIS = 400,
AISRefreshContentDescription = 401,
AISRequestContentDescription = 402,
AISUpdateAppInfo = 403,
AISUpdatePackageCosts = 404,
AISUpdatePackageInfo = 404,
AISGetPackageChangeNumber = 405,
AISGetPackageChangeNumberResponse = 406,
AISAppInfoTableChanged = 407,
AISUpdatePackageCostsResponse = 408,
AISCreateMarketingMessage = 409,
AISCreateMarketingMessageResponse = 410,
AISGetMarketingMessage = 411,
AISGetMarketingMessageResponse = 412,
AISUpdateMarketingMessage = 413,
AISUpdateMarketingMessageResponse = 414,
AISRequestMarketingMessageUpdate = 415,
AISDeleteMarketingMessage = 416,
AISGetMarketingTreatments = 419,
AISGetMarketingTreatmentsResponse = 420,
AISRequestMarketingTreatmentUpdate = 421,
AISTestAddPackage = 422,
AIGetAppGCFlags = 423,
AIGetAppGCFlagsResponse = 424,
AIGetAppList = 425,
AIGetAppListResponse = 426,
AIGetAppInfo = 427,
AIGetAppInfoResponse = 428,
AISGetCouponDefinition = 429,
AISGetCouponDefinitionResponse = 430,
AISUpdateSlaveContentDescription = 431,
AISUpdateSlaveContentDescriptionResponse = 432,
AISTestEnableGC = 433,
BaseAM = 500,
AMUpdateUserBanRequest = 504,
AMAddLicense = 505,
AMBeginProcessingLicenses = 507,
AMSendSystemIMToUser = 508,
AMExtendLicense = 509,
AMAddMinutesToLicense = 510,
AMCancelLicense = 511,
AMInitPurchase = 512,
AMPurchaseResponse = 513,
AMGetFinalPrice = 514,
AMGetFinalPriceResponse = 515,
AMGetLegacyGameKey = 516,
AMGetLegacyGameKeyResponse = 517,
AMFindHungTransactions = 518,
AMSetAccountTrustedRequest = 519,
AMCompletePurchase = 521,
AMCancelPurchase = 522,
AMNewChallenge = 523,
AMLoadOEMTickets = 524,
AMFixPendingPurchase = 525,
AMFixPendingPurchaseResponse = 526,
AMIsUserBanned = 527,
AMRegisterKey = 528,
AMLoadActivationCodes = 529,
AMLoadActivationCodesResponse = 530,
AMLookupKeyResponse = 531,
AMLookupKey = 532,
AMChatCleanup = 533,
AMClanCleanup = 534,
AMFixPendingRefund = 535,
AMReverseChargeback = 536,
AMReverseChargebackResponse = 537,
AMClanCleanupList = 538,
AMGetLicenses = 539,
AMGetLicensesResponse = 540,
AMSendCartRepurchase = 541,
AMSendCartRepurchaseResponse = 542,
AllowUserToPlayQuery = 550,
AllowUserToPlayResponse = 551,
AMVerfiyUser = 552,
AMClientNotPlaying = 553,
ClientRequestFriendship = 554,
AMClientRequestFriendship = 554,
AMRelayPublishStatus = 555,
AMResetCommunityContent = 556,
AMPrimePersonaStateCache = 557,
AMAllowUserContentQuery = 558,
AMAllowUserContentResponse = 559,
AMInitPurchaseResponse = 560,
AMRevokePurchaseResponse = 561,
AMLockProfile = 562,
AMRefreshGuestPasses = 563,
AMInviteUserToClan = 564,
AMAcknowledgeClanInvite = 565,
AMGrantGuestPasses = 566,
AMClanDataUpdated = 567,
AMReloadAccount = 568,
AMClientChatMsgRelay = 569,
AMChatMulti = 570,
AMClientChatInviteRelay = 571,
AMChatInvite = 572,
AMClientJoinChatRelay = 573,
AMClientChatMemberInfoRelay = 574,
AMPublishChatMemberInfo = 575,
AMClientAcceptFriendInvite = 576,
AMChatEnter = 577,
AMClientPublishRemovalFromSource = 578,
AMChatActionResult = 579,
AMFindAccounts = 580,
AMFindAccountsResponse = 581,
AMRequestAccountData = 582,
AMRequestAccountDataResponse = 583,
AMSetAccountFlags = 584,
AMCreateClan = 586,
AMCreateClanResponse = 587,
AMGetClanDetails = 588,
AMGetClanDetailsResponse = 589,
AMSetPersonaName = 590,
AMSetAvatar = 591,
AMAuthenticateUser = 592,
AMAuthenticateUserResponse = 593,
AMGetAccountFriendsCount = 594,
AMGetAccountFriendsCountResponse = 595,
AMP2PIntroducerMessage = 596,
ClientChatAction = 597,
AMClientChatActionRelay = 598,
BaseVS = 600,
ReqChallenge = 600,
VACResponse = 601,
ReqChallengeTest = 602,
VSMarkCheat = 604,
VSAddCheat = 605,
VSPurgeCodeModDB = 606,
VSGetChallengeResults = 607,
VSChallengeResultText = 608,
VSReportLingerer = 609,
VSRequestManagedChallenge = 610,
VSLoadDBFinished = 611,
BaseDRMS = 625,
DRMBuildBlobRequest = 628,
DRMBuildBlobResponse = 629,
DRMResolveGuidRequest = 630,
DRMResolveGuidResponse = 631,
DRMVariabilityReport = 633,
DRMVariabilityReportResponse = 634,
DRMStabilityReport = 635,
DRMStabilityReportResponse = 636,
DRMDetailsReportRequest = 637,
DRMDetailsReportResponse = 638,
DRMProcessFile = 639,
DRMAdminUpdate = 640,
DRMAdminUpdateResponse = 641,
DRMSync = 642,
DRMSyncResponse = 643,
DRMProcessFileResponse = 644,
DRMEmptyGuidCache = 645,
DRMEmptyGuidCacheResponse = 646,
BaseCS = 650,
CSUserContentRequest = 652,
BaseClient = 700,
ClientLogOn_Deprecated = 701,
ClientAnonLogOn_Deprecated = 702,
ClientHeartBeat = 703,
ClientVACResponse = 704,
ClientGamesPlayed_obsolete = 705,
ClientLogOff = 706,
ClientNoUDPConnectivity = 707,
ClientInformOfCreateAccount = 708,
ClientAckVACBan = 709,
ClientConnectionStats = 710,
ClientInitPurchase = 711,
ClientPingResponse = 712,
ClientRemoveFriend = 714,
ClientGamesPlayedNoDataBlob = 715,
ClientChangeStatus = 716,
ClientVacStatusResponse = 717,
ClientFriendMsg = 718,
ClientGameConnect_obsolete = 719,
ClientGamesPlayed2_obsolete = 720,
ClientGameEnded_obsolete = 721,
ClientGetFinalPrice = 722,
ClientSystemIM = 726,
ClientSystemIMAck = 727,
ClientGetLicenses = 728,
ClientCancelLicense = 729,
ClientGetLegacyGameKey = 730,
ClientContentServerLogOn_Deprecated = 731,
ClientAckVACBan2 = 732,
ClientAckMessageByGID = 735,
ClientGetPurchaseReceipts = 736,
ClientAckPurchaseReceipt = 737,
ClientGamesPlayed3_obsolete = 738,
ClientSendGuestPass = 739,
ClientAckGuestPass = 740,
ClientRedeemGuestPass = 741,
ClientGamesPlayed = 742,
ClientRegisterKey = 743,
ClientInviteUserToClan = 744,
ClientAcknowledgeClanInvite = 745,
ClientPurchaseWithMachineID = 746,
ClientAppUsageEvent = 747,
ClientGetGiftTargetList = 748,
ClientGetGiftTargetListResponse = 749,
ClientLogOnResponse = 751,
ClientVACChallenge = 753,
ClientSetHeartbeatRate = 755,
ClientNotLoggedOnDeprecated = 756,
ClientLoggedOff = 757,
GSApprove = 758,
GSDeny = 759,
GSKick = 760,
ClientCreateAcctResponse = 761,
ClientPurchaseResponse = 763,
ClientPing = 764,
ClientNOP = 765,
ClientPersonaState = 766,
ClientFriendsList = 767,
ClientAccountInfo = 768,
ClientVacStatusQuery = 770,
ClientNewsUpdate = 771,
ClientGameConnectDeny = 773,
GSStatusReply = 774,
ClientGetFinalPriceResponse = 775,
ClientGameConnectTokens = 779,
ClientLicenseList = 780,
ClientCancelLicenseResponse = 781,
ClientVACBanStatus = 782,
ClientCMList = 783,
ClientEncryptPct = 784,
ClientGetLegacyGameKeyResponse = 785,
ClientFavoritesList = 786,
CSUserContentApprove = 787,
CSUserContentDeny = 788,
ClientInitPurchaseResponse = 789,
ClientAddFriend = 791,
ClientAddFriendResponse = 792,
ClientInviteFriend = 793,
ClientInviteFriendResponse = 794,
ClientSendGuestPassResponse = 795,
ClientAckGuestPassResponse = 796,
ClientRedeemGuestPassResponse = 797,
ClientUpdateGuestPassesList = 798,
ClientChatMsg = 799,
ClientChatInvite = 800,
ClientJoinChat = 801,
ClientChatMemberInfo = 802,
ClientLogOnWithCredentials_Deprecated = 803,
ClientPasswordChangeResponse = 805,
ClientChatEnter = 807,
ClientFriendRemovedFromSource = 808,
ClientCreateChat = 809,
ClientCreateChatResponse = 810,
ClientUpdateChatMetadata = 811,
ClientP2PIntroducerMessage = 813,
ClientChatActionResult = 814,
ClientRequestFriendData = 815,
ClientGetUserStats = 818,
ClientGetUserStatsResponse = 819,
ClientStoreUserStats = 820,
ClientStoreUserStatsResponse = 821,
ClientClanState = 822,
ClientServiceModule = 830,
ClientServiceCall = 831,
ClientServiceCallResponse = 832,
ClientPackageInfoRequest = 833,
ClientPackageInfoResponse = 834,
ClientNatTraversalStatEvent = 839,
ClientAppInfoRequest = 840,
ClientAppInfoResponse = 841,
ClientSteamUsageEvent = 842,
ClientCheckPassword = 845,
ClientResetPassword = 846,
ClientCheckPasswordResponse = 848,
ClientResetPasswordResponse = 849,
ClientSessionToken = 850,
ClientDRMProblemReport = 851,
ClientSetIgnoreFriend = 855,
ClientSetIgnoreFriendResponse = 856,
ClientGetAppOwnershipTicket = 857,
ClientGetAppOwnershipTicketResponse = 858,
ClientGetLobbyListResponse = 860,
ClientGetLobbyMetadata = 861,
ClientGetLobbyMetadataResponse = 862,
ClientVTTCert = 863,
ClientAppInfoUpdate = 866,
ClientAppInfoChanges = 867,
ClientServerList = 880,
ClientEmailChangeResponse = 891,
ClientSecretQAChangeResponse = 892,
ClientDRMBlobRequest = 896,
ClientDRMBlobResponse = 897,
ClientLookupKey = 898,
ClientLookupKeyResponse = 899,
BaseGameServer = 900,
GSDisconnectNotice = 901,
GSStatus = 903,
GSUserPlaying = 905,
GSStatus2 = 906,
GSStatusUpdate_Unused = 907,
GSServerType = 908,
GSPlayerList = 909,
GSGetUserAchievementStatus = 910,
GSGetUserAchievementStatusResponse = 911,
GSGetPlayStats = 918,
GSGetPlayStatsResponse = 919,
GSGetUserGroupStatus = 920,
AMGetUserGroupStatus = 921,
AMGetUserGroupStatusResponse = 922,
GSGetUserGroupStatusResponse = 923,
GSGetReputation = 936,
GSGetReputationResponse = 937,
GSAssociateWithClan = 938,
GSAssociateWithClanResponse = 939,
GSComputeNewPlayerCompatibility = 940,
GSComputeNewPlayerCompatibilityResponse = 941,
BaseAdmin = 1000,
AdminCmd = 1000,
AdminCmdResponse = 1004,
AdminLogListenRequest = 1005,
AdminLogEvent = 1006,
LogSearchRequest = 1007,
LogSearchResponse = 1008,
LogSearchCancel = 1009,
UniverseData = 1010,
RequestStatHistory = 1014,
StatHistory = 1015,
AdminPwLogon = 1017,
AdminPwLogonResponse = 1018,
AdminSpew = 1019,
AdminConsoleTitle = 1020,
AdminGCSpew = 1023,
AdminGCCommand = 1024,
AdminGCGetCommandList = 1025,
AdminGCGetCommandListResponse = 1026,
FBSConnectionData = 1027,
AdminMsgSpew = 1028,
BaseFBS = 1100,
FBSReqVersion = 1100,
FBSVersionInfo = 1101,
FBSForceRefresh = 1102,
FBSForceBounce = 1103,
FBSDeployPackage = 1104,
FBSDeployResponse = 1105,
FBSUpdateBootstrapper = 1106,
FBSSetState = 1107,
FBSApplyOSUpdates = 1108,
FBSRunCMDScript = 1109,
FBSRebootBox = 1110,
FBSSetBigBrotherMode = 1111,
FBSMinidumpServer = 1112,
FBSSetShellCount_obsolete = 1113,
FBSDeployHotFixPackage = 1114,
FBSDeployHotFixResponse = 1115,
FBSDownloadHotFix = 1116,
FBSDownloadHotFixResponse = 1117,
FBSUpdateTargetConfigFile = 1118,
FBSApplyAccountCred = 1119,
FBSApplyAccountCredResponse = 1120,
FBSSetShellCount = 1121,
FBSTerminateShell = 1122,
FBSQueryGMForRequest = 1123,
FBSQueryGMResponse = 1124,
FBSTerminateZombies = 1125,
FBSInfoFromBootstrapper = 1126,
FBSRebootBoxResponse = 1127,
FBSBootstrapperPackageRequest = 1128,
FBSBootstrapperPackageResponse = 1129,
FBSBootstrapperGetPackageChunk = 1130,
FBSBootstrapperGetPackageChunkResponse = 1131,
FBSBootstrapperPackageTransferProgress = 1132,
FBSRestartBootstrapper = 1133,
FBSPauseFrozenDumps = 1134,
BaseFileXfer = 1200,
FileXferRequest = 1200,
FileXferResponse = 1201,
FileXferData = 1202,
FileXferEnd = 1203,
FileXferDataAck = 1204,
BaseChannelAuth = 1300,
ChannelAuthChallenge = 1300,
ChannelAuthResponse = 1301,
ChannelAuthResult = 1302,
ChannelEncryptRequest = 1303,
ChannelEncryptResponse = 1304,
ChannelEncryptResult = 1305,
BaseBS = 1400,
BSPurchaseStart = 1401,
BSPurchaseResponse = 1402,
BSAuthenticateCCTrans = 1403,
BSSettleNOVA = 1404,
BSAuthenticateCCTransResponse = 1404,
BSSettleComplete = 1406,
BSBannedRequest = 1407,
BSInitPayPalTxn = 1408,
BSInitPayPalTxnResponse = 1409,
BSGetPayPalUserInfo = 1410,
BSGetPayPalUserInfoResponse = 1411,
BSRefundTxn = 1413,
BSRefundTxnResponse = 1414,
BSGetEvents = 1415,
BSChaseRFRRequest = 1416,
BSPaymentInstrBan = 1417,
BSPaymentInstrBanResponse = 1418,
BSProcessGCReports = 1419,
BSProcessPPReports = 1420,
BSInitGCBankXferTxn = 1421,
BSInitGCBankXferTxnResponse = 1422,
BSQueryGCBankXferTxn = 1423,
BSQueryGCBankXferTxnResponse = 1424,
BSCommitGCTxn = 1425,
BSQueryTransactionStatus = 1426,
BSQueryTransactionStatusResponse = 1427,
BSQueryCBOrderStatus = 1428,
BSQueryCBOrderStatusResponse = 1429,
BSRunRedFlagReport = 1430,
BSQueryPaymentInstUsage = 1431,
BSQueryPaymentInstResponse = 1432,
BSQueryTxnExtendedInfo = 1433,
BSQueryTxnExtendedInfoResponse = 1434,
BSUpdateConversionRates = 1435,
BSProcessUSBankReports = 1436,
BSPurchaseRunFraudChecks = 1437,
BSPurchaseRunFraudChecksResponse = 1438,
BSStartShippingJobs = 1439,
BSQueryBankInformation = 1440,
BSQueryBankInformationResponse = 1441,
BSValidateXsollaSignature = 1445,
BSValidateXsollaSignatureResponse = 1446,
BSQiwiWalletInvoice = 1448,
BSQiwiWalletInvoiceResponse = 1449,
BSUpdateInventoryFromProPack = 1450,
BSUpdateInventoryFromProPackResponse = 1451,
BSSendShippingRequest = 1452,
BSSendShippingRequestResponse = 1453,
BSGetProPackOrderStatus = 1454,
BSGetProPackOrderStatusResponse = 1455,
BSCheckJobRunning = 1456,
BSCheckJobRunningResponse = 1457,
BSResetPackagePurchaseRateLimit = 1458,
BSResetPackagePurchaseRateLimitResponse = 1459,
BSUpdatePaymentData = 1460,
BSUpdatePaymentDataResponse = 1461,
BSGetBillingAddress = 1462,
BSGetBillingAddressResponse = 1463,
BSGetCreditCardInfo = 1464,
BSGetCreditCardInfoResponse = 1465,
BSRemoveExpiredPaymentData = 1468,
BSRemoveExpiredPaymentDataResponse = 1469,
BSConvertToCurrentKeys = 1470,
BSConvertToCurrentKeysResponse = 1471,
BSInitPurchase = 1472,
BSInitPurchaseResponse = 1473,
BSCompletePurchase = 1474,
BSCompletePurchaseResponse = 1475,
BSPruneCardUsageStats = 1476,
BSPruneCardUsageStatsResponse = 1477,
BSStoreBankInformation = 1478,
BSStoreBankInformationResponse = 1479,
BSVerifyPOSAKey = 1480,
BSVerifyPOSAKeyResponse = 1481,
BSReverseRedeemPOSAKey = 1482,
BSReverseRedeemPOSAKeyResponse = 1483,
BSQueryFindCreditCard = 1484,
BSQueryFindCreditCardResponse = 1485,
BSStatusInquiryPOSAKey = 1486,
BSStatusInquiryPOSAKeyResponse = 1487,
BSValidateMoPaySignature = 1488,
BSValidateMoPaySignatureResponse = 1489,
BSMoPayConfirmProductDelivery = 1490,
BSMoPayConfirmProductDeliveryResponse = 1491,
BSGenerateMoPayMD5 = 1492,
BSGenerateMoPayMD5Response = 1493,
BSBoaCompraConfirmProductDelivery = 1494,
BSBoaCompraConfirmProductDeliveryResponse = 1495,
BSGenerateBoaCompraMD5 = 1496,
BSGenerateBoaCompraMD5Response = 1497,
BSCommitWPTxn = 1498,
BSCommitAdyenTxn = 1499,
BaseATS = 1500,
ATSStartStressTest = 1501,
ATSStopStressTest = 1502,
ATSRunFailServerTest = 1503,
ATSUFSPerfTestTask = 1504,
ATSUFSPerfTestResponse = 1505,
ATSCycleTCM = 1506,
ATSInitDRMSStressTest = 1507,
ATSCallTest = 1508,
ATSCallTestReply = 1509,
ATSStartExternalStress = 1510,
ATSExternalStressJobStart = 1511,
ATSExternalStressJobQueued = 1512,
ATSExternalStressJobRunning = 1513,
ATSExternalStressJobStopped = 1514,
ATSExternalStressJobStopAll = 1515,
ATSExternalStressActionResult = 1516,
ATSStarted = 1517,
ATSCSPerfTestTask = 1518,
ATSCSPerfTestResponse = 1519,
BaseDP = 1600,
DPSetPublishingState = 1601,
DPGamePlayedStats = 1602,
DPUniquePlayersStat = 1603,
DPStreamingUniquePlayersStat = 1604,
DPVacInfractionStats = 1605,
DPVacBanStats = 1606,
DPBlockingStats = 1607,
DPNatTraversalStats = 1608,
DPSteamUsageEvent = 1609,
DPVacCertBanStats = 1610,
DPVacCafeBanStats = 1611,
DPCloudStats = 1612,
DPAchievementStats = 1613,
DPAccountCreationStats = 1614,
DPGetPlayerCount = 1615,
DPGetPlayerCountResponse = 1616,
DPGameServersPlayersStats = 1617,
DPDownloadRateStatistics = 1618,
DPFacebookStatistics = 1619,
ClientDPCheckSpecialSurvey = 1620,
ClientDPCheckSpecialSurveyResponse = 1621,
ClientDPSendSpecialSurveyResponse = 1622,
ClientDPSendSpecialSurveyResponseReply = 1623,
DPStoreSaleStatistics = 1624,
ClientDPUpdateAppJobReport = 1625,
DPUpdateContentEvent = 1626,
ClientDPSteam2AppStarted = 1627,
ClientDPUnsignedInstallScript = 1627,
DPPartnerMicroTxns = 1628,
DPPartnerMicroTxnsResponse = 1629,
ClientDPContentStatsReport = 1630,
DPVRUniquePlayersStat = 1631,
BaseCM = 1700,
CMSetAllowState = 1701,
CMSpewAllowState = 1702,
CMAppInfoResponseDeprecated = 1703,
CMSessionRejected = 1703,
CMSetSecrets = 1704,
CMGetSecrets = 1705,
BaseDSS = 1800,
DSSNewFile = 1801,
DSSCurrentFileList = 1802,
DSSSynchList = 1803,
DSSSynchListResponse = 1804,
DSSSynchSubscribe = 1805,
DSSSynchUnsubscribe = 1806,
BaseEPM = 1900,
EPMStartProcess = 1901,
EPMStopProcess = 1902,
EPMRestartProcess = 1903,
GCSendClient = 2200,
BaseGC = 2200,
AMRelayToGC = 2201,
GCUpdatePlayedState = 2202,
GCCmdRevive = 2203,
GCCmdBounce = 2204,
GCCmdForceBounce = 2205,
GCCmdDown = 2206,
GCCmdDeploy = 2207,
GCCmdDeployResponse = 2208,
GCCmdSwitch = 2209,
AMRefreshSessions = 2210,
GCUpdateGSState = 2211,
GCAchievementAwarded = 2212,
GCSystemMessage = 2213,
GCValidateSession = 2214,
GCValidateSessionResponse = 2215,
GCCmdStatus = 2216,
GCRegisterWebInterfaces = 2217,
GCRegisterWebInterfaces_Deprecated = 2217,
GCGetAccountDetails = 2218,
GCGetAccountDetails_DEPRECATED = 2218,
GCInterAppMessage = 2219,
GCGetEmailTemplate = 2220,
GCGetEmailTemplateResponse = 2221,
ISRelayToGCH = 2222,
GCHRelay = 2222,
GCHRelayClientToIS = 2223,
GCHRelayToClient = 2223,
GCHUpdateSession = 2224,
GCHRequestUpdateSession = 2225,
GCHRequestStatus = 2226,
GCHRequestStatusResponse = 2227,
GCHAccountVacStatusChange = 2228,
GCHSpawnGC = 2229,
GCHSpawnGCResponse = 2230,
GCHKillGC = 2231,
GCHKillGCResponse = 2232,
GCHAccountTradeBanStatusChange = 2233,
GCHAccountLockStatusChange = 2234,
GCHVacVerificationChange = 2235,
GCHAccountPhoneNumberChange = 2236,
GCHAccountTwoFactorChange = 2237,
GCHInviteUserToLobby = 2238,
BaseP2P = 2500,
P2PIntroducerMessage = 2502,
BaseSM = 2900,
SMExpensiveReport = 2902,
SMHourlyReport = 2903,
SMFishingReport = 2904,
SMPartitionRenames = 2905,
SMMonitorSpace = 2906,
SMGetSchemaConversionResults = 2907,
SMTestNextBuildSchemaConversion = 2907,
SMGetSchemaConversionResultsResponse = 2908,
SMTestNextBuildSchemaConversionResponse = 2908,
BaseTest = 3000,
FailServer = 3000,
JobHeartbeatTest = 3001,
JobHeartbeatTestResponse = 3002,
BaseFTSRange = 3100,
FTSGetBrowseCounts = 3101,
FTSGetBrowseCountsResponse = 3102,
FTSBrowseClans = 3103,
FTSBrowseClansResponse = 3104,
FTSSearchClansByLocation = 3105,
FTSSearchClansByLocationResponse = 3106,
FTSSearchPlayersByLocation = 3107,
FTSSearchPlayersByLocationResponse = 3108,
FTSClanDeleted = 3109,
FTSSearch = 3110,
FTSSearchResponse = 3111,
FTSSearchStatus = 3112,
FTSSearchStatusResponse = 3113,
FTSGetGSPlayStats = 3114,
FTSGetGSPlayStatsResponse = 3115,
FTSGetGSPlayStatsForServer = 3116,
FTSGetGSPlayStatsForServerResponse = 3117,
FTSReportIPUpdates = 3118,
BaseCCSRange = 3150,
CCSGetComments = 3151,
CCSGetCommentsResponse = 3152,
CCSAddComment = 3153,
CCSAddCommentResponse = 3154,
CCSDeleteComment = 3155,
CCSDeleteCommentResponse = 3156,
CCSPreloadComments = 3157,
CCSNotifyCommentCount = 3158,
CCSGetCommentsForNews = 3159,
CCSGetCommentsForNewsResponse = 3160,
CCSDeleteAllCommentsByAuthor = 3161,
CCSDeleteAllCommentsByAuthorResponse = 3162,
BaseLBSRange = 3200,
LBSSetScore = 3201,
LBSSetScoreResponse = 3202,
LBSFindOrCreateLB = 3203,
LBSFindOrCreateLBResponse = 3204,
LBSGetLBEntries = 3205,
LBSGetLBEntriesResponse = 3206,
LBSGetLBList = 3207,
LBSGetLBListResponse = 3208,
LBSSetLBDetails = 3209,
LBSDeleteLB = 3210,
LBSDeleteLBEntry = 3211,
LBSResetLB = 3212,
LBSResetLBResponse = 3213,
LBSDeleteLBResponse = 3214,
BaseOGS = 3400,
OGSBeginSession = 3401,
OGSBeginSessionResponse = 3402,
OGSEndSession = 3403,
OGSEndSessionResponse = 3404,
OGSWriteAppSessionRow = 3406,
BaseBRP = 3600,
BRPStartShippingJobs = 3601,
BRPProcessUSBankReports = 3602,
BRPProcessGCReports = 3603,
BRPProcessPPReports = 3604,
BRPSettleNOVA = 3605,
BRPSettleCB = 3606,
BRPCommitGC = 3607,
BRPCommitGCResponse = 3608,
BRPFindHungTransactions = 3609,
BRPCheckFinanceCloseOutDate = 3610,
BRPProcessLicenses = 3611,
BRPProcessLicensesResponse = 3612,
BRPRemoveExpiredPaymentData = 3613,
BRPRemoveExpiredPaymentDataResponse = 3614,
BRPConvertToCurrentKeys = 3615,
BRPConvertToCurrentKeysResponse = 3616,
BRPPruneCardUsageStats = 3617,
BRPPruneCardUsageStatsResponse = 3618,
BRPCheckActivationCodes = 3619,
BRPCheckActivationCodesResponse = 3620,
BRPCommitWP = 3621,
BRPCommitWPResponse = 3622,
BRPProcessWPReports = 3623,
BRPProcessPaymentRules = 3624,
BRPProcessPartnerPayments = 3625,
BRPCheckSettlementReports = 3626,
BRPPostTaxToAvalara = 3628,
BRPPostTransactionTax = 3629,
BRPPostTransactionTaxResponse = 3630,
BRPProcessIMReports = 3631,
BaseAMRange2 = 4000,
AMCreateChat = 4001,
AMCreateChatResponse = 4002,
AMUpdateChatMetadata = 4003,
AMPublishChatMetadata = 4004,
AMSetProfileURL = 4005,
AMGetAccountEmailAddress = 4006,
AMGetAccountEmailAddressResponse = 4007,
AMRequestClanData = 4008,
AMRouteToClients = 4009,
AMLeaveClan = 4010,
AMClanPermissions = 4011,
AMClanPermissionsResponse = 4012,
AMCreateClanEvent = 4013,
AMCreateClanEventDummyForRateLimiting = 4013,
AMCreateClanEventResponse = 4014,
AMUpdateClanEvent = 4015,
AMUpdateClanEventDummyForRateLimiting = 4015,
AMUpdateClanEventResponse = 4016,
AMGetClanEvents = 4017,
AMGetClanEventsResponse = 4018,
AMDeleteClanEvent = 4019,
AMDeleteClanEventResponse = 4020,
AMSetClanPermissionSettings = 4021,
AMSetClanPermissionSettingsResponse = 4022,
AMGetClanPermissionSettings = 4023,
AMGetClanPermissionSettingsResponse = 4024,
AMPublishChatRoomInfo = 4025,
ClientChatRoomInfo = 4026,
AMCreateClanAnnouncement = 4027,
AMCreateClanAnnouncementResponse = 4028,
AMUpdateClanAnnouncement = 4029,
AMUpdateClanAnnouncementResponse = 4030,
AMGetClanAnnouncementsCount = 4031,
AMGetClanAnnouncementsCountResponse = 4032,
AMGetClanAnnouncements = 4033,
AMGetClanAnnouncementsResponse = 4034,
AMDeleteClanAnnouncement = 4035,
AMDeleteClanAnnouncementResponse = 4036,
AMGetSingleClanAnnouncement = 4037,
AMGetSingleClanAnnouncementResponse = 4038,
AMGetClanHistory = 4039,
AMGetClanHistoryResponse = 4040,
AMGetClanPermissionBits = 4041,
AMGetClanPermissionBitsResponse = 4042,
AMSetClanPermissionBits = 4043,
AMSetClanPermissionBitsResponse = 4044,
AMSessionInfoRequest = 4045,
AMSessionInfoResponse = 4046,
AMValidateWGToken = 4047,
AMGetSingleClanEvent = 4048,
AMGetSingleClanEventResponse = 4049,
AMGetClanRank = 4050,
AMGetClanRankResponse = 4051,
AMSetClanRank = 4052,
AMSetClanRankResponse = 4053,
AMGetClanPOTW = 4054,
AMGetClanPOTWResponse = 4055,
AMSetClanPOTW = 4056,
AMSetClanPOTWResponse = 4057,
AMRequestChatMetadata = 4058,
AMDumpUser = 4059,
AMKickUserFromClan = 4060,
AMAddFounderToClan = 4061,
AMValidateWGTokenResponse = 4062,
AMSetCommunityState = 4063,
AMSetAccountDetails = 4064,
AMGetChatBanList = 4065,
AMGetChatBanListResponse = 4066,
AMUnBanFromChat = 4067,
AMSetClanDetails = 4068,
AMGetAccountLinks = 4069,
AMGetAccountLinksResponse = 4070,
AMSetAccountLinks = 4071,
AMSetAccountLinksResponse = 4072,
AMGetUserGameStats = 4073,
UGSGetUserGameStats = 4073,
AMGetUserGameStatsResponse = 4074,
UGSGetUserGameStatsResponse = 4074,
AMCheckClanMembership = 4075,
AMGetClanMembers = 4076,
AMGetClanMembersResponse = 4077,
AMJoinPublicClan = 4078,
AMNotifyChatOfClanChange = 4079,
AMResubmitPurchase = 4080,
AMAddFriend = 4081,
AMAddFriendResponse = 4082,
AMRemoveFriend = 4083,
AMDumpClan = 4084,
AMChangeClanOwner = 4085,
AMCancelEasyCollect = 4086,
AMCancelEasyCollectResponse = 4087,
AMGetClanMembershipList = 4088,
AMGetClanMembershipListResponse = 4089,
AMClansInCommon = 4090,
AMClansInCommonResponse = 4091,
AMIsValidAccountID = 4092,
AMConvertClan = 4093,
AMGetGiftTargetListRelay = 4094,
AMWipeFriendsList = 4095,
AMSetIgnored = 4096,
AMClansInCommonCountResponse = 4097,
AMFriendsList = 4098,
AMFriendsListResponse = 4099,
AMFriendsInCommon = 4100,
AMFriendsInCommonResponse = 4101,
AMFriendsInCommonCountResponse = 4102,
AMClansInCommonCount = 4103,
AMChallengeVerdict = 4104,
AMChallengeNotification = 4105,
AMFindGSByIP = 4106,
AMFoundGSByIP = 4107,
AMGiftRevoked = 4108,
AMCreateAccountRecord = 4109,
AMUserClanList = 4110,
AMUserClanListResponse = 4111,
AMGetAccountDetails2 = 4112,
AMGetAccountDetailsResponse2 = 4113,
AMSetCommunityProfileSettings = 4114,
AMSetCommunityProfileSettingsResponse = 4115,
AMGetCommunityPrivacyState = 4116,
AMGetCommunityPrivacyStateResponse = 4117,
AMCheckClanInviteRateLimiting = 4118,
AMGetUserAchievementStatus = 4119,
UGSGetUserAchievementStatus = 4119,
AMGetIgnored = 4120,
AMGetIgnoredResponse = 4121,
AMSetIgnoredResponse = 4122,
AMSetFriendRelationshipNone = 4123,
AMGetFriendRelationship = 4124,
AMGetFriendRelationshipResponse = 4125,
AMServiceModulesCache = 4126,
AMServiceModulesCall = 4127,
AMServiceModulesCallResponse = 4128,
AMGetCaptchaDataForIP = 4129,
AMGetCaptchaDataForIPResponse = 4130,
AMValidateCaptchaDataForIP = 4131,
AMValidateCaptchaDataForIPResponse = 4132,
AMTrackFailedAuthByIP = 4133,
AMGetCaptchaDataByGID = 4134,
AMGetCaptchaDataByGIDResponse = 4135,
AMGetLobbyList = 4136,
AMGetLobbyListResponse = 4137,
AMGetLobbyMetadata = 4138,
AMGetLobbyMetadataResponse = 4139,
CommunityAddFriendNews = 4140,
AMAddClanNews = 4141,
AMWriteNews = 4142,
AMFindClanUser = 4143,
AMFindClanUserResponse = 4144,
AMBanFromChat = 4145,
AMGetUserHistoryResponse = 4146,
AMGetUserNewsSubscriptions = 4147,
AMGetUserNewsSubscriptionsResponse = 4148,
AMSetUserNewsSubscriptions = 4149,
AMGetUserNews = 4150,
AMGetUserNewsResponse = 4151,
AMSendQueuedEmails = 4152,
AMSetLicenseFlags = 4153,
AMGetUserHistory = 4154,
CommunityDeleteUserNews = 4155,
AMAllowUserFilesRequest = 4156,
AMAllowUserFilesResponse = 4157,
AMGetAccountStatus = 4158,
AMGetAccountStatusResponse = 4159,
AMEditBanReason = 4160,
AMCheckClanMembershipResponse = 4161,
AMProbeClanMembershipList = 4162,
AMProbeClanMembershipListResponse = 4163,
UGSGetUserAchievementStatusResponse = 4164,
AMGetFriendsLobbies = 4165,
AMGetFriendsLobbiesResponse = 4166,
AMGetUserFriendNewsResponse = 4172,
CommunityGetUserFriendNews = 4173,
AMGetUserClansNewsResponse = 4174,
AMGetUserClansNews = 4175,
AMStoreInitPurchase = 4176,
AMStoreInitPurchaseResponse = 4177,
AMStoreGetFinalPrice = 4178,
AMStoreGetFinalPriceResponse = 4179,
AMStoreCompletePurchase = 4180,
AMStoreCancelPurchase = 4181,
AMStorePurchaseResponse = 4182,
AMCreateAccountRecordInSteam3 = 4183,
AMGetPreviousCBAccount = 4184,
AMGetPreviousCBAccountResponse = 4185,
AMUpdateBillingAddress = 4186,
AMUpdateBillingAddressResponse = 4187,
AMGetBillingAddress = 4188,
AMGetBillingAddressResponse = 4189,
AMGetUserLicenseHistory = 4190,
AMGetUserLicenseHistoryResponse = 4191,
AMSupportChangePassword = 4194,
AMSupportChangeEmail = 4195,
AMSupportChangeSecretQA = 4196,
AMResetUserVerificationGSByIP = 4197,
AMUpdateGSPlayStats = 4198,
AMSupportEnableOrDisable = 4199,
AMGetComments = 4200,
AMGetCommentsResponse = 4201,
AMAddComment = 4202,
AMAddCommentResponse = 4203,
AMDeleteComment = 4204,
AMDeleteCommentResponse = 4205,
AMGetPurchaseStatus = 4206,
AMSupportIsAccountEnabled = 4209,
AMSupportIsAccountEnabledResponse = 4210,
AMGetUserStats = 4211,
UGSGetUserStats = 4211,
AMSupportKickSession = 4212,
AMGSSearch = 4213,
MarketingMessageUpdate = 4216,
AMRouteFriendMsg = 4219,
ChatServerRouteFriendMsg = 4219,
AMTicketAuthRequestOrResponse = 4220,
AMVerifyDepotManagementRights = 4222,
AMVerifyDepotManagementRightsResponse = 4223,
AMAddFreeLicense = 4224,
AMGetUserFriendsMinutesPlayed = 4225,
AMGetUserFriendsMinutesPlayedResponse = 4226,
AMGetUserMinutesPlayed = 4227,
AMGetUserMinutesPlayedResponse = 4228,
AMValidateEmailLink = 4231,
AMValidateEmailLinkResponse = 4232,
AMAddUsersToMarketingTreatment = 4234,
AMStoreUserStats = 4236,
UGSStoreUserStats = 4236,
AMGetUserGameplayInfo = 4237,
AMGetUserGameplayInfoResponse = 4238,
AMGetCardList = 4239,
AMGetCardListResponse = 4240,
AMDeleteStoredCard = 4241,
AMRevokeLegacyGameKeys = 4242,
AMGetWalletDetails = 4244,
AMGetWalletDetailsResponse = 4245,
AMDeleteStoredPaymentInfo = 4246,
AMGetStoredPaymentSummary = 4247,
AMGetStoredPaymentSummaryResponse = 4248,
AMGetWalletConversionRate = 4249,
AMGetWalletConversionRateResponse = 4250,
AMConvertWallet = 4251,
AMConvertWalletResponse = 4252,
AMRelayGetFriendsWhoPlayGame = 4253,
AMRelayGetFriendsWhoPlayGameResponse = 4254,
AMSetPreApproval = 4255,
AMSetPreApprovalResponse = 4256,
AMMarketingTreatmentUpdate = 4257,
AMCreateRefund = 4258,
AMCreateRefundResponse = 4259,
AMCreateChargeback = 4260,
AMCreateChargebackResponse = 4261,
AMCreateDispute = 4262,
AMCreateDisputeResponse = 4263,
AMClearDispute = 4264,
AMClearDisputeResponse = 4265,
AMCreateFinancialAdjustment = 4265,
AMPlayerNicknameList = 4266,
AMPlayerNicknameListResponse = 4267,
AMSetDRMTestConfig = 4268,
AMGetUserCurrentGameInfo = 4269,
AMGetUserCurrentGameInfoResponse = 4270,
AMGetGSPlayerList = 4271,
AMGetGSPlayerListResponse = 4272,
AMUpdatePersonaStateCache = 4275,
AMGetGameMembers = 4276,
AMGetGameMembersResponse = 4277,
AMGetSteamIDForMicroTxn = 4278,
AMGetSteamIDForMicroTxnResponse = 4279,
AMAddPublisherUser = 4280,
AMSetPartnerMember = 4280,
AMRemovePublisherUser = 4281,
AMGetUserLicenseList = 4282,
AMGetUserLicenseListResponse = 4283,
AMReloadGameGroupPolicy = 4284,
AMAddFreeLicenseResponse = 4285,
AMVACStatusUpdate = 4286,
AMGetAccountDetails = 4287,
AMGetAccountDetailsResponse = 4288,
AMGetPlayerLinkDetails = 4289,
AMGetPlayerLinkDetailsResponse = 4290,
AMSubscribeToPersonaFeed = 4291,
AMGetUserVacBanList = 4292,
AMGetUserVacBanListResponse = 4293,
AMGetAccountFlagsForWGSpoofing = 4294,
AMGetAccountFlagsForWGSpoofingResponse = 4295,
AMGetFriendsWishlistInfo = 4296,
AMGetFriendsWishlistInfoResponse = 4297,
AMGetClanOfficers = 4298,
AMGetClanOfficersResponse = 4299,
AMNameChange = 4300,
AMGetNameHistory = 4301,
AMGetNameHistoryResponse = 4302,
AMUpdateProviderStatus = 4305,
AMClearPersonaMetadataBlob = 4306,
AMSupportRemoveAccountSecurity = 4307,
AMIsAccountInCaptchaGracePeriod = 4308,
AMIsAccountInCaptchaGracePeriodResponse = 4309,
AMAccountPS3Unlink = 4310,
AMAccountPS3UnlinkResponse = 4311,
AMStoreUserStatsResponse = 4312,
UGSStoreUserStatsResponse = 4312,
AMGetAccountPSNInfo = 4313,
AMGetAccountPSNInfoResponse = 4314,
AMAuthenticatedPlayerList = 4315,
AMGetUserGifts = 4316,
AMGetUserGiftsResponse = 4317,
AMTransferLockedGifts = 4320,
AMTransferLockedGiftsResponse = 4321,
AMPlayerHostedOnGameServer = 4322,
AMGetAccountBanInfo = 4323,
AMGetAccountBanInfoResponse = 4324,
AMRecordBanEnforcement = 4325,
AMRollbackGiftTransfer = 4326,
AMRollbackGiftTransferResponse = 4327,
AMHandlePendingTransaction = 4328,
AMRequestClanDetails = 4329,
AMDeleteStoredPaypalAgreement = 4330,
AMGameServerUpdate = 4331,
AMGameServerRemove = 4332,
AMGetPaypalAgreements = 4333,
AMGetPaypalAgreementsResponse = 4334,
AMGameServerPlayerCompatibilityCheck = 4335,
AMGameServerPlayerCompatibilityCheckResponse = 4336,
AMRenewLicense = 4337,
AMGetAccountCommunityBanInfo = 4338,
AMGetAccountCommunityBanInfoResponse = 4339,
AMGameServerAccountChangePassword = 4340,
AMGameServerAccountDeleteAccount = 4341,
AMRenewAgreement = 4342,
AMSendEmail = 4343,
AMXsollaPayment = 4344,
AMXsollaPaymentResponse = 4345,
AMAcctAllowedToPurchase = 4346,
AMAcctAllowedToPurchaseResponse = 4347,
AMSwapKioskDeposit = 4348,
AMSwapKioskDepositResponse = 4349,
AMSetUserGiftUnowned = 4350,
AMSetUserGiftUnownedResponse = 4351,
AMClaimUnownedUserGift = 4352,
AMClaimUnownedUserGiftResponse = 4353,
AMSetClanName = 4354,
AMSetClanNameResponse = 4355,
AMGrantCoupon = 4356,
AMGrantCouponResponse = 4357,
AMIsPackageRestrictedInUserCountry = 4358,
AMIsPackageRestrictedInUserCountryResponse = 4359,
AMHandlePendingTransactionResponse = 4360,
AMGrantGuestPasses2 = 4361,
AMGrantGuestPasses2Response = 4362,
AMSessionQuery = 4363,
AMSessionQueryResponse = 4364,
AMGetPlayerBanDetails = 4365,
AMGetPlayerBanDetailsResponse = 4366,
AMFinalizePurchase = 4367,
AMFinalizePurchaseResponse = 4368,
AMPersonaChangeResponse = 4372,
AMGetClanDetailsForForumCreation = 4373,
AMGetClanDetailsForForumCreationResponse = 4374,
AMGetPendingNotificationCount = 4375,
AMGetPendingNotificationCountResponse = 4376,
AMPasswordHashUpgrade = 4377,
AMMoPayPayment = 4378,
AMMoPayPaymentResponse = 4379,
AMBoaCompraPayment = 4380,
AMBoaCompraPaymentResponse = 4381,
AMExpireCaptchaByGID = 4382,
AMCompleteExternalPurchase = 4383,
AMCompleteExternalPurchaseResponse = 4384,
AMResolveNegativeWalletCredits = 4385,
AMResolveNegativeWalletCreditsResponse = 4386,
AMPayelpPayment = 4387,
AMPayelpPaymentResponse = 4388,
AMPlayerGetClanBasicDetails = 4389,
AMPlayerGetClanBasicDetailsResponse = 4390,
AMMOLPayment = 4391,
AMMOLPaymentResponse = 4392,
GetUserIPCountry = 4393,
GetUserIPCountryResponse = 4394,
NotificationOfSuspiciousActivity = 4395,
AMDegicaPayment = 4396,
AMDegicaPaymentResponse = 4397,
AMEClubPayment = 4398,
AMEClubPaymentResponse = 4399,
AMPayPalPaymentsHubPayment = 4400,
AMPayPalPaymentsHubPaymentResponse = 4401,
AMTwoFactorRecoverAuthenticatorRequest = 4402,
AMTwoFactorRecoverAuthenticatorResponse = 4403,
AMSmart2PayPayment = 4404,
AMSmart2PayPaymentResponse = 4405,
AMValidatePasswordResetCodeAndSendSmsRequest = 4406,
AMValidatePasswordResetCodeAndSendSmsResponse = 4407,
AMGetAccountResetDetailsRequest = 4408,
AMGetAccountResetDetailsResponse = 4409,
AMBitPayPayment = 4410,
AMBitPayPaymentResponse = 4411,
AMSendAccountInfoUpdate = 4412,
AMSendScheduledGift = 4413,
AMNodwinPayment = 4414,
AMNodwinPaymentResponse = 4415,
AMResolveWalletRevoke = 4416,
AMResolveWalletReverseRevoke = 4417,
AMFundedPayment = 4418,
AMFundedPaymentResponse = 4419,
AMRequestPersonaUpdateForChatServer = 4420,
AMPerfectWorldPayment = 4421,
AMPerfectWorldPaymentResponse = 4422,
BasePSRange = 5000,
PSCreateShoppingCart = 5001,
PSCreateShoppingCartResponse = 5002,
PSIsValidShoppingCart = 5003,
PSIsValidShoppingCartResponse = 5004,
PSAddPackageToShoppingCart = 5005,
PSAddPackageToShoppingCartResponse = 5006,
PSRemoveLineItemFromShoppingCart = 5007,
PSRemoveLineItemFromShoppingCartResponse = 5008,
PSGetShoppingCartContents = 5009,
PSGetShoppingCartContentsResponse = 5010,
PSAddWalletCreditToShoppingCart = 5011,
PSAddWalletCreditToShoppingCartResponse = 5012,
BaseUFSRange = 5200,
ClientUFSUploadFileRequest = 5202,
ClientUFSUploadFileResponse = 5203,
ClientUFSUploadFileChunk = 5204,
ClientUFSUploadFileFinished = 5205,
ClientUFSGetFileListForApp = 5206,
ClientUFSGetFileListForAppResponse = 5207,
ClientUFSDownloadRequest = 5210,
ClientUFSDownloadResponse = 5211,
ClientUFSDownloadChunk = 5212,
ClientUFSLoginRequest = 5213,
ClientUFSLoginResponse = 5214,
UFSReloadPartitionInfo = 5215,
ClientUFSTransferHeartbeat = 5216,
UFSSynchronizeFile = 5217,
UFSSynchronizeFileResponse = 5218,
ClientUFSDeleteFileRequest = 5219,
ClientUFSDeleteFileResponse = 5220,
UFSDownloadRequest = 5221,
UFSDownloadResponse = 5222,
UFSDownloadChunk = 5223,
ClientUFSGetUGCDetails = 5226,
ClientUFSGetUGCDetailsResponse = 5227,
UFSUpdateFileFlags = 5228,
UFSUpdateFileFlagsResponse = 5229,
ClientUFSGetSingleFileInfo = 5230,
ClientUFSGetSingleFileInfoResponse = 5231,
ClientUFSShareFile = 5232,
ClientUFSShareFileResponse = 5233,
UFSReloadAccount = 5234,
UFSReloadAccountResponse = 5235,
UFSUpdateRecordBatched = 5236,
UFSUpdateRecordBatchedResponse = 5237,
UFSMigrateFile = 5238,
UFSMigrateFileResponse = 5239,
UFSGetUGCURLs = 5240,
UFSGetUGCURLsResponse = 5241,
UFSHttpUploadFileFinishRequest = 5242,
UFSHttpUploadFileFinishResponse = 5243,
UFSDownloadStartRequest = 5244,
UFSDownloadStartResponse = 5245,
UFSDownloadChunkRequest = 5246,
UFSDownloadChunkResponse = 5247,
UFSDownloadFinishRequest = 5248,
UFSDownloadFinishResponse = 5249,
UFSFlushURLCache = 5250,
UFSUploadCommit = 5251,
ClientUFSUploadCommit = 5251,
UFSUploadCommitResponse = 5252,
ClientUFSUploadCommitResponse = 5252,
UFSMigrateFileAppID = 5253,
UFSMigrateFileAppIDResponse = 5254,
BaseClient2 = 5400,
ClientRequestForgottenPasswordEmail = 5401,
ClientRequestForgottenPasswordEmailResponse = 5402,
ClientCreateAccountResponse = 5403,
ClientResetForgottenPassword = 5404,
ClientResetForgottenPasswordResponse = 5405,
ClientCreateAccount2 = 5406,
ClientInformOfResetForgottenPassword = 5407,
ClientInformOfResetForgottenPasswordResponse = 5408,
ClientAnonUserLogOn_Deprecated = 5409,
ClientGamesPlayedWithDataBlob = 5410,
ClientUpdateUserGameInfo = 5411,
ClientFileToDownload = 5412,
ClientFileToDownloadResponse = 5413,
ClientLBSSetScore = 5414,
ClientLBSSetScoreResponse = 5415,
ClientLBSFindOrCreateLB = 5416,
ClientLBSFindOrCreateLBResponse = 5417,
ClientLBSGetLBEntries = 5418,
ClientLBSGetLBEntriesResponse = 5419,
ClientMarketingMessageUpdate = 5420,
ClientChatDeclined = 5426,
ClientFriendMsgIncoming = 5427,
ClientAuthList_Deprecated = 5428,
ClientTicketAuthComplete = 5429,
ClientIsLimitedAccount = 5430,
ClientRequestAuthList = 5431,
ClientAuthList = 5432,
ClientStat = 5433,
ClientP2PConnectionInfo = 5434,
ClientP2PConnectionFailInfo = 5435,
ClientGetNumberOfCurrentPlayers = 5436,
ClientGetNumberOfCurrentPlayersResponse = 5437,
ClientGetDepotDecryptionKey = 5438,
ClientGetDepotDecryptionKeyResponse = 5439,
GSPerformHardwareSurvey = 5440,
ClientGetAppBetaPasswords = 5441,
ClientGetAppBetaPasswordsResponse = 5442,
ClientEnableTestLicense = 5443,
ClientEnableTestLicenseResponse = 5444,
ClientDisableTestLicense = 5445,
ClientDisableTestLicenseResponse = 5446,
ClientRequestValidationMail = 5448,
ClientRequestValidationMailResponse = 5449,
ClientCheckAppBetaPassword = 5450,
ClientCheckAppBetaPasswordResponse = 5451,
ClientToGC = 5452,
ClientFromGC = 5453,
ClientRequestChangeMail = 5454,
ClientRequestChangeMailResponse = 5455,
ClientEmailAddrInfo = 5456,
ClientPasswordChange3 = 5457,
ClientEmailChange3 = 5458,
ClientPersonalQAChange3 = 5459,
ClientResetForgottenPassword3 = 5460,
ClientRequestForgottenPasswordEmail3 = 5461,
ClientCreateAccount3 = 5462,
ClientNewLoginKey = 5463,
ClientNewLoginKeyAccepted = 5464,
ClientLogOnWithHash_Deprecated = 5465,
ClientStoreUserStats2 = 5466,
ClientStatsUpdated = 5467,
ClientActivateOEMLicense = 5468,
ClientRegisterOEMMachine = 5469,
ClientRegisterOEMMachineResponse = 5470,
ClientRequestedClientStats = 5480,
ClientStat2Int32 = 5481,
ClientStat2 = 5482,
ClientVerifyPassword = 5483,
ClientVerifyPasswordResponse = 5484,
ClientDRMDownloadRequest = 5485,
ClientDRMDownloadResponse = 5486,
ClientDRMFinalResult = 5487,
ClientGetFriendsWhoPlayGame = 5488,
ClientGetFriendsWhoPlayGameResponse = 5489,
ClientOGSBeginSession = 5490,
ClientOGSBeginSessionResponse = 5491,
ClientOGSEndSession = 5492,
ClientOGSEndSessionResponse = 5493,
ClientOGSWriteRow = 5494,
ClientDRMTest = 5495,
ClientDRMTestResult = 5496,
ClientServerUnavailable = 5500,
ClientServersAvailable = 5501,
ClientRegisterAuthTicketWithCM = 5502,
ClientGCMsgFailed = 5503,
ClientMicroTxnAuthRequest = 5504,
ClientMicroTxnAuthorize = 5505,
ClientMicroTxnAuthorizeResponse = 5506,
ClientAppMinutesPlayedData = 5507,
ClientGetMicroTxnInfo = 5508,
ClientGetMicroTxnInfoResponse = 5509,
ClientMarketingMessageUpdate2 = 5510,
ClientDeregisterWithServer = 5511,
ClientSubscribeToPersonaFeed = 5512,
ClientLogon = 5514,
ClientGetClientDetails = 5515,
ClientGetClientDetailsResponse = 5516,
ClientReportOverlayDetourFailure = 5517,
ClientGetClientAppList = 5518,
ClientGetClientAppListResponse = 5519,
ClientInstallClientApp = 5520,
ClientInstallClientAppResponse = 5521,
ClientUninstallClientApp = 5522,
ClientUninstallClientAppResponse = 5523,
ClientSetClientAppUpdateState = 5524,
ClientSetClientAppUpdateStateResponse = 5525,
ClientRequestEncryptedAppTicket = 5526,
ClientRequestEncryptedAppTicketResponse = 5527,
ClientWalletInfoUpdate = 5528,
ClientLBSSetUGC = 5529,
ClientLBSSetUGCResponse = 5530,
ClientAMGetClanOfficers = 5531,
ClientAMGetClanOfficersResponse = 5532,
ClientCheckFileSignature = 5533,
ClientCheckFileSignatureResponse = 5534,
ClientFriendProfileInfo = 5535,
ClientFriendProfileInfoResponse = 5536,
ClientUpdateMachineAuth = 5537,
ClientUpdateMachineAuthResponse = 5538,
ClientReadMachineAuth = 5539,
ClientReadMachineAuthResponse = 5540,
ClientRequestMachineAuth = 5541,
ClientRequestMachineAuthResponse = 5542,
ClientScreenshotsChanged = 5543,
ClientEmailChange4 = 5544,
ClientEmailChangeResponse4 = 5545,
ClientGetCDNAuthToken = 5546,
ClientGetCDNAuthTokenResponse = 5547,
ClientDownloadRateStatistics = 5548,
ClientRequestAccountData = 5549,
ClientRequestAccountDataResponse = 5550,
ClientResetForgottenPassword4 = 5551,
ClientHideFriend = 5552,
ClientFriendsGroupsList = 5553,
ClientGetClanActivityCounts = 5554,
ClientGetClanActivityCountsResponse = 5555,
ClientOGSReportString = 5556,
ClientOGSReportBug = 5557,
ClientSentLogs = 5558,
ClientLogonGameServer = 5559,
AMClientCreateFriendsGroup = 5560,
AMClientCreateFriendsGroupResponse = 5561,
AMClientDeleteFriendsGroup = 5562,
AMClientDeleteFriendsGroupResponse = 5563,
AMClientRenameFriendsGroup = 5564,
AMClientManageFriendsGroup = 5564,
AMClientRenameFriendsGroupResponse = 5565,
AMClientManageFriendsGroupResponse = 5565,
AMClientAddFriendToGroup = 5566,
AMClientAddFriendToGroupResponse = 5567,
AMClientRemoveFriendFromGroup = 5568,
AMClientRemoveFriendFromGroupResponse = 5569,
ClientAMGetPersonaNameHistory = 5570,
ClientAMGetPersonaNameHistoryResponse = 5571,
ClientRequestFreeLicense = 5572,
ClientRequestFreeLicenseResponse = 5573,
ClientDRMDownloadRequestWithCrashData = 5574,
ClientAuthListAck = 5575,
ClientItemAnnouncements = 5576,
ClientRequestItemAnnouncements = 5577,
ClientFriendMsgEchoToSender = 5578,
ClientChangeSteamGuardOptions = 5579,
ClientChangeSteamGuardOptionsResponse = 5580,
ClientOGSGameServerPingSample = 5581,
ClientCommentNotifications = 5582,
ClientRequestCommentNotifications = 5583,
ClientPersonaChangeResponse = 5584,
ClientRequestWebAPIAuthenticateUserNonce = 5585,
ClientRequestWebAPIAuthenticateUserNonceResponse = 5586,
ClientPlayerNicknameList = 5587,
AMClientSetPlayerNickname = 5588,
AMClientSetPlayerNicknameResponse = 5589,
ClientCreateAccountProto = 5590,
ClientRequestOAuthTokenForApp = 5590,
ClientCreateAccountProtoResponse = 5591,
ClientRequestOAuthTokenForAppResponse = 5591,
ClientGetNumberOfCurrentPlayersDP = 5592,
ClientGetNumberOfCurrentPlayersDPResponse = 5593,
ClientServiceMethod = 5594,
ClientServiceMethodLegacy = 5594,
ClientServiceMethodResponse = 5595,
ClientServiceMethodLegacyResponse = 5595,
ClientFriendUserStatusPublished = 5596,
ClientCurrentUIMode = 5597,
ClientVanityURLChangedNotification = 5598,
ClientUserNotifications = 5599,
BaseDFS = 5600,
DFSGetFile = 5601,
DFSInstallLocalFile = 5602,
DFSConnection = 5603,
DFSConnectionReply = 5604,
ClientDFSAuthenticateRequest = 5605,
ClientDFSAuthenticateResponse = 5606,
ClientDFSEndSession = 5607,
DFSPurgeFile = 5608,
DFSRouteFile = 5609,
DFSGetFileFromServer = 5610,
DFSAcceptedResponse = 5611,
DFSRequestPingback = 5612,
DFSRecvTransmitFile = 5613,
DFSSendTransmitFile = 5614,
DFSRequestPingback2 = 5615,
DFSResponsePingback2 = 5616,
ClientDFSDownloadStatus = 5617,
DFSStartTransfer = 5618,
DFSTransferComplete = 5619,
DFSRouteFileResponse = 5620,
ClientNetworkingCertRequest = 5621,
ClientNetworkingCertRequestResponse = 5622,
ClientChallengeRequest = 5623,
ClientChallengeResponse = 5624,
BadgeCraftedNotification = 5625,
ClientNetworkingMobileCertRequest = 5626,
ClientNetworkingMobileCertRequestResponse = 5627,
BaseMDS = 5800,
ClientMDSLoginRequest = 5801,
ClientMDSLoginResponse = 5802,
ClientMDSUploadManifestRequest = 5803,
ClientMDSUploadManifestResponse = 5804,
ClientMDSTransmitManifestDataChunk = 5805,
ClientMDSHeartbeat = 5806,
ClientMDSUploadDepotChunks = 5807,
ClientMDSUploadDepotChunksResponse = 5808,
ClientMDSInitDepotBuildRequest = 5809,
ClientMDSInitDepotBuildResponse = 5810,
AMToMDSGetDepotDecryptionKey = 5812,
MDSToAMGetDepotDecryptionKeyResponse = 5813,
MDSGetVersionsForDepot = 5814,
MDSGetVersionsForDepotResponse = 5815,
ClientMDSInitWorkshopBuildRequest = 5816,
MDSSetPublicVersionForDepot = 5816,
ClientMDSInitWorkshopBuildResponse = 5817,
MDSSetPublicVersionForDepotResponse = 5817,
ClientMDSGetDepotManifest = 5818,
ClientMDSGetDepotManifestResponse = 5819,
ClientMDSGetDepotManifestChunk = 5820,
ClientMDSUploadRateTest = 5823,
ClientMDSUploadRateTestResponse = 5824,
MDSDownloadDepotChunksAck = 5825,
MDSContentServerStatsBroadcast = 5826,
MDSContentServerConfigRequest = 5827,
MDSContentServerConfig = 5828,
MDSGetDepotManifest = 5829,
MDSGetDepotManifestResponse = 5830,
MDSGetDepotManifestChunk = 5831,
MDSGetDepotChunk = 5832,
MDSGetDepotChunkResponse = 5833,
MDSGetDepotChunkChunk = 5834,
MDSUpdateContentServerConfig = 5835,
MDSGetServerListForUser = 5836,
MDSGetServerListForUserResponse = 5837,
ClientMDSRegisterAppBuild = 5838,
ClientMDSRegisterAppBuildResponse = 5839,
ClientMDSSetAppBuildLive = 5840,
ClientMDSSetAppBuildLiveResponse = 5841,
ClientMDSGetPrevDepotBuild = 5842,
ClientMDSGetPrevDepotBuildResponse = 5843,
MDSToCSFlushChunk = 5844,
ClientMDSSignInstallScript = 5845,
ClientMDSSignInstallScriptResponse = 5846,
MDSMigrateChunk = 5847,
MDSMigrateChunkResponse = 5848,
MDSToCSFlushManifest = 5849,
CSBase = 6200,
CSPing = 6201,
CSPingResponse = 6202,
GMSBase = 6400,
GMSGameServerReplicate = 6401,
ClientGMSServerQuery = 6403,
GMSClientServerQueryResponse = 6404,
AMGMSGameServerUpdate = 6405,
AMGMSGameServerRemove = 6406,
GameServerOutOfDate = 6407,
DeviceAuthorizationBase = 6500,
ClientAuthorizeLocalDeviceRequest = 6501,
ClientAuthorizeLocalDevice = 6502,
ClientAuthorizeLocalDeviceResponse = 6502,
ClientDeauthorizeDeviceRequest = 6503,
ClientDeauthorizeDevice = 6504,
ClientUseLocalDeviceAuthorizations = 6505,
ClientGetAuthorizedDevices = 6506,
ClientGetAuthorizedDevicesResponse = 6507,
AMNotifySessionDeviceAuthorized = 6508,
ClientAuthorizeLocalDeviceNotification = 6509,
MMSBase = 6600,
ClientMMSCreateLobby = 6601,
ClientMMSCreateLobbyResponse = 6602,
ClientMMSJoinLobby = 6603,
ClientMMSJoinLobbyResponse = 6604,
ClientMMSLeaveLobby = 6605,
ClientMMSLeaveLobbyResponse = 6606,
ClientMMSGetLobbyList = 6607,
ClientMMSGetLobbyListResponse = 6608,
ClientMMSSetLobbyData = 6609,
ClientMMSSetLobbyDataResponse = 6610,
ClientMMSGetLobbyData = 6611,
ClientMMSLobbyData = 6612,
ClientMMSSendLobbyChatMsg = 6613,
ClientMMSLobbyChatMsg = 6614,
ClientMMSSetLobbyOwner = 6615,
ClientMMSSetLobbyOwnerResponse = 6616,
ClientMMSSetLobbyGameServer = 6617,
ClientMMSLobbyGameServerSet = 6618,
ClientMMSUserJoinedLobby = 6619,
ClientMMSUserLeftLobby = 6620,
ClientMMSInviteToLobby = 6621,
ClientMMSFlushFrenemyListCache = 6622,
ClientMMSFlushFrenemyListCacheResponse = 6623,
ClientMMSSetLobbyLinked = 6624,
ClientMMSSetRatelimitPolicyOnClient = 6625,
ClientMMSGetLobbyStatus = 6626,
ClientMMSGetLobbyStatusResponse = 6627,
MMSGetLobbyList = 6628,
MMSGetLobbyListResponse = 6629,
NonStdMsgBase = 6800,
NonStdMsgMemcached = 6801,
NonStdMsgHTTPServer = 6802,
NonStdMsgHTTPClient = 6803,
NonStdMsgWGResponse = 6804,
NonStdMsgPHPSimulator = 6805,
NonStdMsgChase = 6806,
NonStdMsgDFSTransfer = 6807,
NonStdMsgTests = 6808,
NonStdMsgUMQpipeAAPL = 6809,
NonStdMsgSyslog = 6810,
NonStdMsgLogsink = 6811,
NonStdMsgSteam2Emulator = 6812,
NonStdMsgRTMPServer = 6813,
NonStdMsgWebSocket = 6814,
NonStdMsgRedis = 6815,
UDSBase = 7000,
ClientUDSP2PSessionStarted = 7001,
ClientUDSP2PSessionEnded = 7002,
UDSRenderUserAuth = 7003,
UDSRenderUserAuthResponse = 7004,
ClientUDSInviteToGame = 7005,
ClientInviteToGame = 7005,
UDSFindSession = 7006,
UDSHasSession = 7006,
UDSFindSessionResponse = 7007,
UDSHasSessionResponse = 7007,
MPASBase = 7100,
MPASVacBanReset = 7101,
KGSBase = 7200,
KGSAllocateKeyRange = 7201,
KGSAllocateKeyRangeResponse = 7202,
KGSGenerateKeys = 7203,
KGSGenerateKeysResponse = 7204,
KGSRemapKeys = 7205,
KGSRemapKeysResponse = 7206,
KGSGenerateGameStopWCKeys = 7207,
KGSGenerateGameStopWCKeysResponse = 7208,
UCMBase = 7300,
ClientUCMAddScreenshot = 7301,
ClientUCMAddScreenshotResponse = 7302,
UCMValidateObjectExists = 7303,
UCMValidateObjectExistsResponse = 7304,
UCMResetCommunityContent = 7307,
UCMResetCommunityContentResponse = 7308,
ClientUCMDeleteScreenshot = 7309,
ClientUCMDeleteScreenshotResponse = 7310,
ClientUCMPublishFile = 7311,
ClientUCMPublishFileResponse = 7312,
ClientUCMGetPublishedFileDetails = 7313,
ClientUCMGetPublishedFileDetailsResponse = 7314,
ClientUCMDeletePublishedFile = 7315,
ClientUCMDeletePublishedFileResponse = 7316,
ClientUCMEnumerateUserPublishedFiles = 7317,
ClientUCMEnumerateUserPublishedFilesResponse = 7318,
ClientUCMSubscribePublishedFile = 7319,
ClientUCMSubscribePublishedFileResponse = 7320,
ClientUCMEnumerateUserSubscribedFiles = 7321,
ClientUCMEnumerateUserSubscribedFilesResponse = 7322,
ClientUCMUnsubscribePublishedFile = 7323,
ClientUCMUnsubscribePublishedFileResponse = 7324,
ClientUCMUpdatePublishedFile = 7325,
ClientUCMUpdatePublishedFileResponse = 7326,
UCMUpdatePublishedFile = 7327,
UCMUpdatePublishedFileResponse = 7328,
UCMDeletePublishedFile = 7329,
UCMDeletePublishedFileResponse = 7330,
UCMUpdatePublishedFileStat = 7331,
UCMUpdatePublishedFileBan = 7332,
UCMUpdatePublishedFileBanResponse = 7333,
UCMUpdateTaggedScreenshot = 7334,
UCMAddTaggedScreenshot = 7335,
UCMRemoveTaggedScreenshot = 7336,
UCMReloadPublishedFile = 7337,
UCMReloadUserFileListCaches = 7338,
UCMPublishedFileReported = 7339,
UCMUpdatePublishedFileIncompatibleStatus = 7340,
UCMPublishedFilePreviewAdd = 7341,
UCMPublishedFilePreviewAddResponse = 7342,
UCMPublishedFilePreviewRemove = 7343,
UCMPublishedFilePreviewRemoveResponse = 7344,
UCMPublishedFilePreviewChangeSortOrder = 7345,
UCMPublishedFilePreviewChangeSortOrderResponse = 7346,
ClientUCMPublishedFileSubscribed = 7347,
ClientUCMPublishedFileUnsubscribed = 7348,
UCMPublishedFileSubscribed = 7349,
UCMPublishedFileUnsubscribed = 7350,
UCMPublishFile = 7351,
UCMPublishFileResponse = 7352,
UCMPublishedFileChildAdd = 7353,
UCMPublishedFileChildAddResponse = 7354,
UCMPublishedFileChildRemove = 7355,
UCMPublishedFileChildRemoveResponse = 7356,
UCMPublishedFileChildChangeSortOrder = 7357,
UCMPublishedFileChildChangeSortOrderResponse = 7358,
UCMPublishedFileParentChanged = 7359,
ClientUCMGetPublishedFilesForUser = 7360,
ClientUCMGetPublishedFilesForUserResponse = 7361,
UCMGetPublishedFilesForUser = 7362,
UCMGetPublishedFilesForUserResponse = 7363,
ClientUCMSetUserPublishedFileAction = 7364,
ClientUCMSetUserPublishedFileActionResponse = 7365,
ClientUCMEnumeratePublishedFilesByUserAction = 7366,
ClientUCMEnumeratePublishedFilesByUserActionResponse = 7367,
ClientUCMPublishedFileDeleted = 7368,
UCMGetUserSubscribedFiles = 7369,
UCMGetUserSubscribedFilesResponse = 7370,
UCMFixStatsPublishedFile = 7371,
UCMDeleteOldScreenshot = 7372,
UCMDeleteOldScreenshotResponse = 7373,
UCMDeleteOldVideo = 7374,
UCMDeleteOldVideoResponse = 7375,
UCMUpdateOldScreenshotPrivacy = 7376,
UCMUpdateOldScreenshotPrivacyResponse = 7377,
ClientUCMEnumerateUserSubscribedFilesWithUpdates = 7378,
ClientUCMEnumerateUserSubscribedFilesWithUpdatesResponse = 7379,
UCMPublishedFileContentUpdated = 7380,
UCMPublishedFileUpdated = 7381,
ClientUCMPublishedFileUpdated = 7381,
ClientWorkshopItemChangesRequest = 7382,
ClientWorkshopItemChangesResponse = 7383,
ClientWorkshopItemInfoRequest = 7384,
ClientWorkshopItemInfoResponse = 7385,
FSBase = 7500,
ClientRichPresenceUpload = 7501,
ClientRichPresenceRequest = 7502,
ClientRichPresenceInfo = 7503,
FSRichPresenceRequest = 7504,
FSRichPresenceResponse = 7505,
FSComputeFrenematrix = 7506,
FSComputeFrenematrixResponse = 7507,
FSPlayStatusNotification = 7508,
FSPublishPersonaStatus = 7509,
FSAddOrRemoveFollower = 7510,
FSAddOrRemoveFollowerResponse = 7511,
FSUpdateFollowingList = 7512,
FSCommentNotification = 7513,
FSCommentNotificationViewed = 7514,
ClientFSGetFollowerCount = 7515,
ClientFSGetFollowerCountResponse = 7516,
ClientFSGetIsFollowing = 7517,
ClientFSGetIsFollowingResponse = 7518,
ClientFSEnumerateFollowingList = 7519,
ClientFSEnumerateFollowingListResponse = 7520,
FSGetPendingNotificationCount = 7521,
FSGetPendingNotificationCountResponse = 7522,
ClientFSOfflineMessageNotification = 7523,
ClientChatOfflineMessageNotification = 7523,
ClientFSRequestOfflineMessageCount = 7524,
ClientChatRequestOfflineMessageCount = 7524,
ClientFSGetFriendMessageHistory = 7525,
ClientChatGetFriendMessageHistory = 7525,
ClientFSGetFriendMessageHistoryResponse = 7526,
ClientChatGetFriendMessageHistoryResponse = 7526,
ClientFSGetFriendMessageHistoryForOfflineMessages = 7527,
ClientChatGetFriendMessageHistoryForOfflineMessages = 7527,
ClientFSGetFriendsSteamLevels = 7528,
ClientFSGetFriendsSteamLevelsResponse = 7529,
FSRequestFriendData = 7530,
AMRequestFriendData = 7530,
CEGVersionSetEnableDisableRequest = 7600,
DRMRange2 = 7600,
CEGVersionSetEnableDisableResponse = 7601,
CEGPropStatusDRMSRequest = 7602,
CEGPropStatusDRMSResponse = 7603,
CEGWhackFailureReportRequest = 7604,
CEGWhackFailureReportResponse = 7605,
DRMSFetchVersionSet = 7606,
DRMSFetchVersionSetResponse = 7607,
EconBase = 7700,
EconTrading_InitiateTradeRequest = 7701,
EconTrading_InitiateTradeProposed = 7702,
EconTrading_InitiateTradeResponse = 7703,
EconTrading_InitiateTradeResult = 7704,
EconTrading_StartSession = 7705,
EconTrading_CancelTradeRequest = 7706,
EconFlushInventoryCache = 7707,
EconFlushInventoryCacheResponse = 7708,
EconCDKeyProcessTransaction = 7711,
EconCDKeyProcessTransactionResponse = 7712,
EconGetErrorLogs = 7713,
EconGetErrorLogsResponse = 7714,
RMRange = 7800,
RMTestVerisignOTP = 7800,
RMTestVerisignOTPResponse = 7801,
RMDeleteMemcachedKeys = 7803,
RMRemoteInvoke = 7804,
BadLoginIPList = 7805,
RMMsgTraceAddTrigger = 7806,
RMMsgTraceRemoveTrigger = 7807,
RMMsgTraceEvent = 7808,
UGSBase = 7900,
UGSUpdateGlobalStats = 7900,
ClientUGSGetGlobalStats = 7901,
ClientUGSGetGlobalStatsResponse = 7902,
StoreUpdateRecommendationCount = 8000,
StoreBase = 8000,
UMQBase = 8100,
UMQLogonRequest = 8100,
UMQLogonResponse = 8101,
UMQLogoffRequest = 8102,
UMQLogoffResponse = 8103,
UMQSendChatMessage = 8104,
UMQIncomingChatMessage = 8105,
UMQPoll = 8106,
UMQPollResults = 8107,
UMQ2AM_ClientMsgBatch = 8108,
UMQEnqueueMobileSalePromotions = 8109,
UMQEnqueueMobileAnnouncements = 8110,
WorkshopAcceptTOSRequest = 8200,
WorkshopBase = 8200,
WorkshopAcceptTOSResponse = 8201,
WebAPIBase = 8300,
WebAPIValidateOAuth2Token = 8300,
WebAPIValidateOAuth2TokenResponse = 8301,
WebAPIInvalidateTokensForAccount = 8302,
WebAPIRegisterGCInterfaces = 8303,
WebAPIInvalidateOAuthClientCache = 8304,
WebAPIInvalidateOAuthTokenCache = 8305,
WebAPISetSecrets = 8306,
BackpackBase = 8400,
BackpackAddToCurrency = 8401,
BackpackAddToCurrencyResponse = 8402,
CREBase = 8500,
CRERankByTrend = 8501,
CRERankByTrendResponse = 8502,
CREItemVoteSummary = 8503,
CREItemVoteSummaryResponse = 8504,
CRERankByVote = 8505,
CRERankByVoteResponse = 8506,
CREUpdateUserPublishedItemVote = 8507,
CREUpdateUserPublishedItemVoteResponse = 8508,
CREGetUserPublishedItemVoteDetails = 8509,
CREGetUserPublishedItemVoteDetailsResponse = 8510,
CREEnumeratePublishedFiles = 8511,
CREEnumeratePublishedFilesResponse = 8512,
CREPublishedFileVoteAdded = 8513,
SecretsBase = 8600,
SecretsRequestCredentialPair = 8600,
SecretsCredentialPairResponse = 8601,
SecretsRequestServerIdentity = 8602,
SecretsServerIdentityResponse = 8603,
SecretsUpdateServerIdentities = 8604,
BoxMonitorBase = 8700,
BoxMonitorReportRequest = 8700,
BoxMonitorReportResponse = 8701,
LogsinkBase = 8800,
LogsinkWriteReport = 8800,
PICSBase = 8900,
ClientPICSChangesSinceRequest = 8901,
ClientPICSChangesSinceResponse = 8902,
ClientPICSProductInfoRequest = 8903,
ClientPICSProductInfoResponse = 8904,
ClientPICSAccessTokenRequest = 8905,
ClientPICSAccessTokenResponse = 8906,
WorkerProcess = 9000,
WorkerProcessPingRequest = 9000,
WorkerProcessPingResponse = 9001,
WorkerProcessShutdown = 9002,
DRMWorkerProcess = 9100,
DRMWorkerProcessDRMAndSign = 9100,
DRMWorkerProcessDRMAndSignResponse = 9101,
DRMWorkerProcessSteamworksInfoRequest = 9102,
DRMWorkerProcessSteamworksInfoResponse = 9103,
DRMWorkerProcessInstallDRMDLLRequest = 9104,
DRMWorkerProcessInstallDRMDLLResponse = 9105,
DRMWorkerProcessSecretIdStringRequest = 9106,
DRMWorkerProcessSecretIdStringResponse = 9107,
DRMWorkerProcessGetDRMGuidsFromFileRequest = 9108,
DRMWorkerProcessGetDRMGuidsFromFileResponse = 9109,
DRMWorkerProcessInstallProcessedFilesRequest = 9110,
DRMWorkerProcessInstallProcessedFilesResponse = 9111,
DRMWorkerProcessExamineBlobRequest = 9112,
DRMWorkerProcessExamineBlobResponse = 9113,
DRMWorkerProcessDescribeSecretRequest = 9114,
DRMWorkerProcessDescribeSecretResponse = 9115,
DRMWorkerProcessBackfillOriginalRequest = 9116,
DRMWorkerProcessBackfillOriginalResponse = 9117,
DRMWorkerProcessValidateDRMDLLRequest = 9118,
DRMWorkerProcessValidateDRMDLLResponse = 9119,
DRMWorkerProcessValidateFileRequest = 9120,
DRMWorkerProcessValidateFileResponse = 9121,
DRMWorkerProcessSplitAndInstallRequest = 9122,
DRMWorkerProcessSplitAndInstallResponse = 9123,
DRMWorkerProcessGetBlobRequest = 9124,
DRMWorkerProcessGetBlobResponse = 9125,
DRMWorkerProcessEvaluateCrashRequest = 9126,
DRMWorkerProcessEvaluateCrashResponse = 9127,
DRMWorkerProcessAnalyzeFileRequest = 9128,
DRMWorkerProcessAnalyzeFileResponse = 9129,
DRMWorkerProcessUnpackBlobRequest = 9130,
DRMWorkerProcessUnpackBlobResponse = 9131,
DRMWorkerProcessInstallAllRequest = 9132,
DRMWorkerProcessInstallAllResponse = 9133,
TestWorkerProcess = 9200,
TestWorkerProcessLoadUnloadModuleRequest = 9200,
TestWorkerProcessLoadUnloadModuleResponse = 9201,
TestWorkerProcessServiceModuleCallRequest = 9202,
TestWorkerProcessServiceModuleCallResponse = 9203,
QuestServerBase = 9300,
ClientGetEmoticonList = 9330,
ClientEmoticonList = 9331,
ClientSharedLibraryBase = 9400,
SLCBase = 9400,
SLCUserSessionStatus = 9400,
SLCRequestUserSessionStatus = 9401,
SLCSharedLicensesLockStatus = 9402,
ClientSharedLicensesLockStatus = 9403,
ClientSharedLicensesStopPlaying = 9404,
ClientSharedLibraryLockStatus = 9405,
ClientSharedLibraryStopPlaying = 9406,
SLCOwnerLibraryChanged = 9407,
SLCSharedLibraryChanged = 9408,
RemoteClientAuth = 9500,
RemoteClientBase = 9500,
RemoteClientAuthResponse = 9501,
RemoteClientAppStatus = 9502,
RemoteClientStartStream = 9503,
RemoteClientStartStreamResponse = 9504,
RemoteClientPing = 9505,
RemoteClientPingResponse = 9506,
ClientUnlockStreaming = 9507,
ClientUnlockStreamingResponse = 9508,
RemoteClientAcceptEULA = 9509,
RemoteClientGetControllerConfig = 9510,
RemoteClientGetControllerConfigResposne = 9511,
RemoteClientGetControllerConfigResponse = 9511,
RemoteClientStreamingEnabled = 9512,
ClientUnlockHEVC = 9513,
ClientUnlockHEVCResponse = 9514,
RemoteClientStatusRequest = 9515,
RemoteClientStatusResponse = 9516,
ClientConcurrentSessionsBase = 9600,
ClientPlayingSessionState = 9600,
ClientKickPlayingSession = 9601,
ClientBroadcastBase = 9700,
ClientBroadcastInit = 9700,
ClientBroadcastFrames = 9701,
ClientBroadcastDisconnect = 9702,
ClientBroadcastScreenshot = 9703,
ClientBroadcastUploadConfig = 9704,
BaseClient3 = 9800,
ClientVoiceCallPreAuthorize = 9800,
ClientVoiceCallPreAuthorizeResponse = 9801,
ClientServerTimestampRequest = 9802,
ClientServerTimestampResponse = 9803,
ClientLANP2PBase = 9900,
ClientLANP2PRequestChunk = 9900,
ClientLANP2PRequestChunkResponse = 9901,
ClientLANP2PMax = 9999,
BaseWatchdogServer = 10000,
NotifyWatchdog = 10000,
ClientSiteLicenseBase = 10100,
ClientSiteLicenseSiteInfoNotification = 10100,
ClientSiteLicenseCheckout = 10101,
ClientSiteLicenseCheckoutResponse = 10102,
ClientSiteLicenseGetAvailableSeats = 10103,
ClientSiteLicenseGetAvailableSeatsResponse = 10104,
ClientSiteLicenseGetContentCacheInfo = 10105,
ClientSiteLicenseGetContentCacheInfoResponse = 10106,
BaseChatServer = 12000,
ChatServerGetPendingNotificationCount = 12000,
ChatServerGetPendingNotificationCountResponse = 12001,
BaseSecretServer = 12100,
ServerSecretChanged = 12100,
}
enum EMsgClanAccountFlags {
k_EMsgClanAccountFlagPublic = 1,
k_EMsgClanAccountFlagLarge = 2,
k_EMsgClanAccountFlagLocked = 4,
k_EMsgClanAccountFlagDisabled = 8,
k_EMsgClanAccountFlagOGG = 16,
}
enum ENewsUpdateType {
AppNews = 0,
SteamAds = 1,
SteamNews = 2,
CDDBUpdate = 3,
ClientUpdate = 4,
}
enum ENotificationSetting {
NotifyUseDefault = 0,
Always = 1,
Never = 2,
}
enum EOSType {
Unknown = -1,
Web = -700,
IOSUnknown = -600,
IOS1 = -599,
IOS2 = -598,
IOS3 = -597,
IOS4 = -596,
IOS5 = -595,
IOS6 = -594,
IOS6_1 = -593,
IOS7 = -592,
IOS7_1 = -591,
IOS8 = -590,
IOS8_1 = -589,
IOS8_2 = -588,
IOS8_3 = -587,
IOS8_4 = -586,
IOS9 = -585,
IOS9_1 = -584,
IOS9_2 = -583,
IOS9_3 = -582,
IOS10 = -581,
IOS10_1 = -580,
IOS10_2 = -579,
IOS10_3 = -578,
IOS11 = -577,
IOS11_1 = -576,
IOS11_2 = -575,
IOS11_3 = -574,
IOS11_4 = -573,
IOS12 = -572,
IOS12_1 = -571,
AndroidUnknown = -500,
Android6 = -499,
Android7 = -498,
Android8 = -497,
Android9 = -496,
UMQ = -400,
PS3 = -300,
MacOSUnknown = -102,
MacOS104 = -101,
MacOS105 = -100,
MacOS1058 = -99,
MacOS106 = -95,
MacOS1063 = -94,
MacOS1064_slgu = -93,
MacOS1067 = -92,
MacOS107 = -90,
MacOS108 = -89,
MacOS109 = -88,
MacOS1010 = -87,
MacOS1011 = -86,
MacOS1012 = -85,
Macos1013 = -84,
Macos1014 = -83,
Macos1015 = -82,
MacOS1016 = -81,
MacOS11 = -80,
MacOSMax = -1,
LinuxUnknown = -203,
Linux22 = -202,
Linux24 = -201,
Linux26 = -200,
Linux32 = -199,
Linux35 = -198,
Linux36 = -197,
Linux310 = -196,
Linux316 = -195,
Linux318 = -194,
Linux3x = -193,
Linux4x = -192,
Linux41 = -191,
Linux44 = -190,
Linux49 = -189,
Linux414 = -188,
Linux419 = -187,
Linux5x = -186,
Linux54 = -185,
Linux6x = -184,
Linux7x = -183,
LinuxMax = -101,
WinUnknown = 0,
Win311 = 1,
Win95 = 2,
Win98 = 3,
WinME = 4,
WinNT = 5,
Win200 = 6,
Win2000 = 6,
WinXP = 7,
Win2003 = 8,
WinVista = 9,
Win7 = 10,
Windows7 = 10,
Win2008 = 11,
Win2012 = 12,
Win8 = 13,
Windows8 = 13,
Win81 = 14,
Windows81 = 14,
Win2012R2 = 15,
Win10 = 16,
Windows10 = 16,
Win2016 = 17,
Win2019 = 18,
WinMAX = 19,
}
enum EPackageStatus {
Available = 0,
Preorder = 1,
Unavailable = 2,
Invalid = 3,
}
enum EPaymentMethod {
None = 0,
ActivationCode = 1,
CreditCard = 2,
Giropay = 3,
PayPal = 4,
Ideal = 5,
PaySafeCard = 6,
Sofort = 7,
GuestPass = 8,
WebMoney = 9,
MoneyBookers = 10,
AliPay = 11,
Yandex = 12,
Kiosk = 13,
Qiwi = 14,
GameStop = 15,
HardwarePromo = 16,
MoPay = 17,
BoletoBancario = 18,
BoaCompraGold = 19,
BancoDoBrasilOnline = 20,
ItauOnline = 21,
BradescoOnline = 22,
Pagseguro = 23,
VisaBrazil = 24,
AmexBrazil = 25,
Aura = 26,
Hipercard = 27,
MastercardBrazil = 28,
DinersCardBrazil = 29,
AuthorizedDevice = 30,
MOLPoints = 31,
ClickAndBuy = 32,
Beeline = 33,
Konbini = 34,
EClubPoints = 35,
CreditCardJapan = 36,
BankTransferJapan = 37,
PayEasyJapan = 38,
PayEasy = 38,
Zong = 39,
CultureVoucher = 40,
BookVoucher = 41,
HappymoneyVoucher = 42,
ConvenientStoreVoucher = 43,
GameVoucher = 44,
Multibanco = 45,
Payshop = 46,
Maestro = 47,
MaestroBoaCompra = 47,
OXXO = 48,
ToditoCash = 49,
Carnet = 50,
SPEI = 51,
ThreePay = 52,
IsBank = 53,
Garanti = 54,
Akbank = 55,
YapiKredi = 56,
Halkbank = 57,
BankAsya = 58,
Finansbank = 59,
DenizBank = 60,
PTT = 61,
CashU = 62,
AutoGrant = 64,
WebMoneyJapan = 65,
OneCard = 66,
PSE = 67,
Exito = 68,
Efecty = 69,
Paloto = 70,
PinValidda = 71,
MangirKart = 72,
BancoCreditoDePeru = 73,
BBVAContinental = 74,
SafetyPay = 75,
PagoEfectivo = 76,
Trustly = 77,
UnionPay = 78,
BitCoin = 79,
Wallet = 128,
Valve = 129,
SteamPressMaster = 130,
MasterComp = 130,
StorePromotion = 131,
Promotional = 131,
MasterSubscription = 134,
Payco = 135,
MobileWalletJapan = 136,
OEMTicket = 256,
Split = 512,
Complimentary = 1024,
}
enum EPersonaState {
Offline = 0,
Online = 1,
Busy = 2,
Away = 3,
Snooze = 4,
LookingToTrade = 5,
LookingToPlay = 6,
Invisible = 7,
}
enum EPersonaStateFlag {
HasRichPresence = 1,
InJoinableGame = 2,
Golden = 4,
RemotePlayTogether = 8,
OnlineUsingWeb = 256,
ClientTypeWeb = 256,
OnlineUsingMobile = 512,
ClientTypeMobile = 512,
OnlineUsingBigPicture = 1024,
ClientTypeTenfoot = 1024,
OnlineUsingVR = 2048,
ClientTypeVR = 2048,
LaunchTypeGamepad = 4096,
LaunchTypeCompatTool = 8192,
}
enum EPlatformType {
Unknown = 0,
Win32 = 1,
Win64 = 2,
Linux = 3,
Linux64 = 3,
OSX = 4,
PS3 = 5,
Linux32 = 6,
}
enum EProtoAppType {
k_EAppTypeDepotOnly = -2147483648,
k_EAppTypeInvalid = 0,
k_EAppTypeGame = 1,
k_EAppTypeApplication = 2,
k_EAppTypeTool = 4,
k_EAppTypeDemo = 8,
k_EAppTypeDeprected = 16,
k_EAppTypeDLC = 32,
k_EAppTypeGuide = 64,
k_EAppTypeDriver = 128,
k_EAppTypeConfig = 256,
k_EAppTypeHardware = 512,
k_EAppTypeFranchise = 1024,
k_EAppTypeVideo = 2048,
k_EAppTypePlugin = 4096,
k_EAppTypeMusicAlbum = 8192,
k_EAppTypeSeries = 16384,
k_EAppTypeComic = 32768,
k_EAppTypeBeta = 65536,
k_EAppTypeShortcut = 1073741824,
}
enum EProtoClanEventType {
k_EClanOtherEvent = 1,
k_EClanGameEvent = 2,
k_EClanPartyEvent = 3,
k_EClanMeetingEvent = 4,
k_EClanSpecialCauseEvent = 5,
k_EClanMusicAndArtsEvent = 6,
k_EClanSportsEvent = 7,
k_EClanTripEvent = 8,
k_EClanChatEvent = 9,
k_EClanGameReleaseEvent = 10,
k_EClanBroadcastEvent = 11,
k_EClanSmallUpdateEvent = 12,
k_EClanPreAnnounceMajorUpdateEvent = 13,
k_EClanMajorUpdateEvent = 14,
k_EClanDLCReleaseEvent = 15,
k_EClanFutureReleaseEvent = 16,
k_EClanESportTournamentStreamEvent = 17,
k_EClanDevStreamEvent = 18,
k_EClanFamousStreamEvent = 19,
k_EClanGameSalesEvent = 20,
k_EClanGameItemSalesEvent = 21,
k_EClanInGameBonusXPEvent = 22,
k_EClanInGameLootEvent = 23,
k_EClanInGamePerksEvent = 24,
k_EClanInGameChallengeEvent = 25,
k_EClanInGameContestEvent = 26,
k_EClanIRLEvent = 27,
k_EClanNewsEvent = 28,
k_EClanBetaReleaseEvent = 29,
k_EClanInGameContentReleaseEvent = 30,
k_EClanFreeTrial = 31,
k_EClanSeasonRelease = 32,
k_EClanSeasonUpdate = 33,
k_EClanCrosspostEvent = 34,
k_EClanInGameEventGeneral = 35,
}
enum EProtoExecutionSite {
Unknown = 0,
SteamClient = 2,
}
enum EPublishedFileForSaleStatus {
NotForSale = 0,
PendingApproval = 1,
ApprovedForSale = 2,
RejectedForSale = 3,
NoLongerForSale = 4,
TentativeApproval = 5,
}
enum EPublishedFileInappropriateProvider {
Invalid = 0,
Google = 1,
Amazon = 2,
}
enum EPublishedFileInappropriateResult {
NotScanned = 0,
VeryUnlikely = 1,
Unlikely = 30,
Possible = 50,
Likely = 75,
VeryLikely = 100,
}
enum EPublishedFileQueryType {
RankedByVote = 0,
RankedByPublicationDate = 1,
AcceptedForGameRankedByAcceptanceDate = 2,
RankedByTrend = 3,
FavoritedByFriendsRankedByPublicationDate = 4,
CreatedByFriendsRankedByPublicationDate = 5,
RankedByNumTimesReported = 6,
CreatedByFollowedUsersRankedByPublicationDate = 7,
NotYetRated = 8,
RankedByTotalUniqueSubscriptions = 9,
RankedByTotalVotesAsc = 10,
RankedByVotesUp = 11,
RankedByTextSearch = 12,
RankedByPlaytimeTrend = 13,
RankedByTotalPlaytime = 14,
RankedByAveragePlaytimeTrend = 15,
RankedByLifetimeAveragePlaytime = 16,
RankedByPlaytimeSessionsTrend = 17,
RankedByLifetimePlaytimeSessions = 18,
RankedByInappropriateContentRating = 19,
}
enum EPublishedFileRevision {
Default = 0,
Latest = 1,
ApprovedSnapshot = 2,
ApprovedSnapshot_China = 3,
RejectedSnapshot = 4,
RejectedSnapshot_China = 5,
}
enum EPublishedFileVisibility {
Public = 0,
FriendsOnly = 1,
Private = 2,
}
enum EPurchaseResultDetail {
NoDetail = 0,
AVSFailure = 1,
InsufficientFunds = 2,
ContactSupport = 3,
Timeout = 4,
InvalidPackage = 5,
InvalidPaymentMethod = 6,
InvalidData = 7,
OthersInProgress = 8,
AlreadyPurchased = 9,
WrongPrice = 10,
FraudCheckFailed = 11,
CancelledByUser = 12,
RestrictedCountry = 13,
BadActivationCode = 14,
DuplicateActivationCode = 15,
UseOtherPaymentMethod = 16,
UseOtherFunctionSource = 17,
InvalidShippingAddress = 18,
RegionNotSupported = 19,
AcctIsBlocked = 20,
AcctNotVerified = 21,
InvalidAccount = 22,
StoreBillingCountryMismatch = 23,
DoesNotOwnRequiredApp = 24,
CanceledByNewTransaction = 25,
ForceCanceledPending = 26,
FailCurrencyTransProvider = 27,
FailedCyberCafe = 28,
NeedsPreApproval = 29,
PreApprovalDenied = 30,
WalletCurrencyMismatch = 31,
EmailNotValidated = 32,
ExpiredCard = 33,
TransactionExpired = 34,
WouldExceedMaxWallet = 35,
MustLoginPS3AppForPurchase = 36,
CannotShipToPOBox = 37,
InsufficientInventory = 38,
CannotGiftShippedGoods = 39,
CannotShipInternationally = 40,
BillingAgreementCancelled = 41,
InvalidCoupon = 42,
ExpiredCoupon = 43,
AccountLocked = 44,
OtherAbortableInProgress = 45,
ExceededSteamLimit = 46,
OverlappingPackagesInCart = 47,
NoWallet = 48,
NoCachedPaymentMethod = 49,
CannotRedeemCodeFromClient = 50,
PurchaseAmountNoSupportedByProvider = 51,
OverlappingPackagesInPendingTransaction = 52,
RateLimited = 53,
OwnsExcludedApp = 54,
CreditCardBinMismatchesType = 55,
CartValueTooHigh = 56,
BillingAgreementAlreadyExists = 57,
POSACodeNotActivated = 58,
CannotShipToCountry = 59,
HungTransactionCancelled = 60,
PaypalInternalError = 61,
UnknownGlobalCollectError = 62,
InvalidTaxAddress = 63,
PhysicalProductLimitExceeded = 64,
PurchaseCannotBeReplayed = 65,
DelayedCompletion = 66,
BundleTypeCannotBeGifted = 67,
BlockedByUSGov = 68,
ItemsReservedForCommercialUse = 69,
GiftAlreadyOwned = 70,
GiftInvalidForRecipientRegion = 71,
GiftPricingImbalance = 72,
GiftRecipientNotSpecified = 73,
ItemsNotAllowedForCommercialUse = 74,
BusinessStoreCountryCodeMismatch = 75,
UserAssociatedWithManyCafes = 76,
UserNotAssociatedWithCafe = 77,
AddressInvalid = 78,
CreditCardNumberInvalid = 79,
CannotShipToMilitaryPostOffice = 80,
BillingNameInvalidResemblesCreditCard = 81,
PaymentMethodTemporarilyUnavailable = 82,
PaymentMethodNotSupportedForProduct = 83,
}
enum ERegionCode {
USEast = 0,
USWest = 1,
SouthAmerica = 2,
Europe = 3,
Asia = 4,
Australia = 5,
MiddleEast = 6,
Africa = 7,
World = 255,
}
enum ERemoteClientBroadcastMsg {
Discovery = 0,
Status = 1,
Offline = 2,
AuthorizationRequest = 3,
AuthorizationResponse = 4,
StreamingRequest = 5,
StreamingResponse = 6,
ProofRequest = 7,
ProofResponse = 8,
AuthorizationCancelRequest = 9,
StreamingCancelRequest = 10,
ClientIDDeconflict = 11,
StreamTransportSignal = 12,
StreamingProgress = 13,
}
enum ERemoteClientService {
None = 0,
RemoteControl = 1,
GameStreaming = 2,
SiteLicense = 4,
ContentCache = 8,
}
enum ERemoteDeviceAuthorizationResult {
Success = 0,
Denied = 1,
NotLoggedIn = 2,
Offline = 3,
Busy = 4,
InProgress = 5,
TimedOut = 6,
Failed = 7,
Canceled = 8,
}
enum ERemoteDeviceStreamingResult {
Success = 0,
Unauthorized = 1,
ScreenLocked = 2,
Failed = 3,
Busy = 4,
InProgress = 5,
Canceled = 6,
DriversNotInstalled = 7,
Disabled = 8,
BroadcastingActive = 9,
VRActive = 10,
PINRequired = 11,
TransportUnavailable = 12,
Invisible = 13,
GameLaunchFailed = 14,
}
enum ERemoteStoragePlatform {
None = 0,
Windows = 1,
OSX = 2,
PS3 = 4,
Linux = 8,
Switch = 16,
Android = 32,
IPhoneOS = 64,
All = -1,
}
enum EResult {
Invalid = 0,
OK = 1,
Fail = 2,
NoConnection = 3,
InvalidPassword = 5,
LoggedInElsewhere = 6,
InvalidProtocolVer = 7,
InvalidParam = 8,
FileNotFound = 9,
Busy = 10,
InvalidState = 11,
InvalidName = 12,
InvalidEmail = 13,
DuplicateName = 14,
AccessDenied = 15,
Timeout = 16,
Banned = 17,
AccountNotFound = 18,
InvalidSteamID = 19,
ServiceUnavailable = 20,
NotLoggedOn = 21,
Pending = 22,
EncryptionFailure = 23,
InsufficientPrivilege = 24,
LimitExceeded = 25,
Revoked = 26,
Expired = 27,
AlreadyRedeemed = 28,
DuplicateRequest = 29,
AlreadyOwned = 30,
IPNotFound = 31,
PersistFailed = 32,
LockingFailed = 33,
LogonSessionReplaced = 34,
ConnectFailed = 35,
HandshakeFailed = 36,
IOFailure = 37,
RemoteDisconnect = 38,
ShoppingCartNotFound = 39,
Blocked = 40,
Ignored = 41,
NoMatch = 42,
AccountDisabled = 43,
ServiceReadOnly = 44,
AccountNotFeatured = 45,
AdministratorOK = 46,
ContentVersion = 47,
TryAnotherCM = 48,
PasswordRequiredToKickSession = 49,
AlreadyLoggedInElsewhere = 50,
Suspended = 51,
Cancelled = 52,
DataCorruption = 53,
DiskFull = 54,
RemoteCallFailed = 55,
PasswordNotSet = 56,
PasswordUnset = 56,
ExternalAccountUnlinked = 57,
PSNTicketInvalid = 58,
ExternalAccountAlreadyLinked = 59,
RemoteFileConflict = 60,
IllegalPassword = 61,
SameAsPreviousValue = 62,
AccountLogonDenied = 63,
CannotUseOldPassword = 64,
InvalidLoginAuthCode = 65,
AccountLogonDeniedNoMailSent = 66,
AccountLogonDeniedNoMail = 66,
HardwareNotCapableOfIPT = 67,
IPTInitError = 68,
ParentalControlRestricted = 69,
FacebookQueryError = 70,
ExpiredLoginAuthCode = 71,
IPLoginRestrictionFailed = 72,
AccountLocked = 73,
AccountLockedDown = 73,
AccountLogonDeniedVerifiedEmailRequired = 74,
NoMatchingURL = 75,
BadResponse = 76,
RequirePasswordReEntry = 77,
ValueOutOfRange = 78,
UnexpectedError = 79,
Disabled = 80,
InvalidCEGSubmission = 81,
RestrictedDevice = 82,
RegionLocked = 83,
RateLimitExceeded = 84,
AccountLogonDeniedNeedTwoFactorCode = 85,
AccountLoginDeniedNeedTwoFactor = 85,
ItemOrEntryHasBeenDeleted = 86,
ItemDeleted = 86,
AccountLoginDeniedThrottle = 87,
TwoFactorCodeMismatch = 88,
TwoFactorActivationCodeMismatch = 89,
AccountAssociatedToMultiplePlayers = 90,
AccountAssociatedToMultiplePartners = 90,
NotModified = 91,
NoMobileDeviceAvailable = 92,
NoMobileDevice = 92,
TimeIsOutOfSync = 93,
TimeNotSynced = 93,
SMSCodeFailed = 94,
TooManyAccountsAccessThisResource = 95,
AccountLimitExceeded = 95,
AccountActivityLimitExceeded = 96,
PhoneActivityLimitExceeded = 97,
RefundToWallet = 98,
EmailSendFailure = 99,
NotSettled = 100,
NeedCaptcha = 101,
GSLTDenied = 102,
GSOwnerDenied = 103,
InvalidItemType = 104,
IPBanned = 105,
GSLTExpired = 106,
InsufficientFunds = 107,
TooManyPending = 108,
NoSiteLicensesFound = 109,
WGNetworkSendExceeded = 110,
AccountNotFriends = 111,
LimitedUserAccount = 112,
CantRemoveItem = 113,
AccountHasBeenDeleted = 114,
AccountHasAnExistingUserCancelledLicense = 115,
DeniedDueToCommunityCooldown = 116,
NoLauncherSpecified = 117,
MustAgreeToSSA = 118,
ClientNoLongerSupported = 119,
LauncherMigrated = 119,
}
enum EServerFlags {
None = 0,
Active = 1,
Secure = 2,
Dedicated = 4,
Linux = 8,
Passworded = 16,
Private = 32,
}
enum EServerType {
CEconBase = -5,
CServer = -4,
Client = -3,
Util = -2,
Invalid = -1,
First = 0,
Shell = 0,
GM = 1,
BUM = 2,
BUMOBOSOLETE = 2,
AM = 3,
BS = 4,
VS = 5,
ATS = 6,
CM = 7,
FBS = 8,
FG = 9,
BoxMonitor = 9,
SS = 10,
DRMS = 11,
HubOBSOLETE = 12,
Console = 13,
ASBOBSOLETE = 14,
PICS = 14,
BootstrapOBSOLETE = 16,
ContentStats = 16,
DP = 17,
WG = 18,
SM = 19,
SLC = 20,
UFS = 21,
DSS = 24,
Community = 24,
P2PRelayOBSOLETE = 25,
AppInformation = 26,
Spare = 27,
FTS = 28,
EPM = 29,
EPMOBSOLETE = 29,
SiteLicense = 29,
PS = 30,
IS = 31,
CCS = 32,
DFS = 33,
LBS = 34,
MDS = 35,
CS = 36,
GC = 37,
NS = 38,
OGS = 39,
WebAPI = 40,
UDS = 41,
MMS = 42,
GMS = 43,
KGS = 44,
UCM = 45,
RM = 46,
FS = 47,
Econ = 48,
Backpack = 49,
UGS = 50,
Store = 51,
StoreFeature = 51,
MoneyStats = 52,
CRE = 53,
UMQ = 54,
Workshop = 55,
BRP = 56,
GCH = 57,
MPAS = 58,
Trade = 59,
Secrets = 60,
Logsink = 61,
Market = 62,
Quest = 63,
WDS = 64,
ACS = 65,
PNP = 66,
TaxForm = 67,
ExternalMonitor = 68,
Parental = 69,
PartnerUpload = 70,
Partner = 71,
ES = 72,
DepotWebContent = 73,
ExternalConfig = 74,
GameNotifications = 75,
MarketRepl = 76,
MarketSearch = 77,
Localization = 78,
Steam2Emulator = 79,
PublicTest = 80,
SolrMgr = 81,
BroadcastRelay = 82,
BroadcastDirectory = 83,
VideoManager = 84,
TradeOffer = 85,
BroadcastChat = 86,
Phone = 87,
AccountScore = 88,
Support = 89,
LogRequest = 90,
LogWorker = 91,
EmailDelivery = 92,
InventoryManagement = 93,
Auth = 94,
StoreCatalog = 95,
HLTVRelay = 96,
IDLS = 97,
Perf = 98,
ItemInventory = 99,
Watchdog = 100,
AccountHistory = 101,
Chat = 102,
Shader = 103,
AccountHardware = 104,
WebRTC = 105,
Giveaway = 106,
ChatRoom = 107,
VoiceChat = 108,
QMS = 109,
Trust = 110,
TimeMachine = 111,
VACDBMaster = 112,
ContentServerConfig = 113,
Minigame = 114,
MLTrain = 115,
VACTest = 116,
TaxService = 117,
MLInference = 118,
UGSAggregate = 119,
TURN = 120,
RemoteClient = 121,
BroadcastOrigin = 122,
BroadcastChannel = 123,
SteamAR = 124,
China = 125,
CrashDump = 126,
}
enum ESteamDatagramMsgID {
Invalid = 0,
RouterPingRequest = 1,
RouterPingReply = 2,
GameserverPingRequest = 3,
LegacyGameserverPingReply = 4,
GameserverSessionRequest = 5,
GameserverSessionEstablished = 6,
NoSession = 7,
Diagnostic = 8,
DataClientToRouter = 9,
DataRouterToServer = 10,
DataServerToRouter = 11,
DataRouterToClient = 12,
Stats = 13,
ClientPingSampleRequest = 14,
ClientPingSampleReply = 15,
ClientToRouterSwitchedPrimary = 16,
RelayHealth = 17,
ConnectRequest = 18,
ConnectOK = 19,
ConnectionClosed = 20,
NoConnection = 21,
RelayToRelayPingRequest = 22,
RelayToRelayPingReply = 23,
P2PSessionRequest = 24,
P2PSessionEstablished = 25,
P2PStatsClient = 26,
P2PStatsRelay = 27,
P2PBadRoute = 28,
GameserverPingReply = 29,
GameserverRegistration = 30,
}
enum ESteamNetworkingSocketsCipher {
INVALID = 0,
NULL = 1,
AES_256_GCM = 2,
}
enum ESteamNetworkingUDPMsgID {
ChallengeRequest = 32,
ChallengeReply = 33,
ConnectRequest = 34,
ConnectOK = 35,
ConnectionClosed = 36,
NoConnection = 37,
}
enum ESteamPipeOperationType {
Invalid = 0,
DecryptCPU = 1,
DiskRead = 2,
DiskWrite = 3,
}
enum ESteamPipeWorkType {
Invalid = 0,
StageFromChunkStores = 1,
}
enum ESteamReviewScore {
None = 0,
OverwhelminglyNegative = 1,
VeryNegative = 2,
Negative = 3,
MostlyNegative = 4,
Mixed = 5,
MostlyPositive = 6,
Positive = 7,
VeryPositive = 8,
OverwhelminglyPositive = 9,
}
enum EStreamActivity {
Idle = 1,
Game = 2,
Desktop = 3,
SecureDesktop = 4,
}
enum EStreamAudioCodec {
None = 0,
Raw = 1,
Vorbis = 2,
Opus = 3,
MP3 = 4,
AAC = 5,
}
enum EStreamBitrate {
Autodetect = -1,
Unlimited = 0,
}
enum EStreamChannel {
Invalid = -1,
Discovery = 0,
Control = 1,
Stats = 2,
DataChannelStart = 3,
}
enum EStreamControlMessage {
AuthenticationRequest = 1,
AuthenticationResponse = 2,
NegotiationInit = 3,
NegotiationSetConfig = 4,
NegotiationComplete = 5,
ClientHandshake = 6,
ServerHandshake = 7,
StartNetworkTest = 8,
KeepAlive = 9,
LAST_SETUP_MESSAGE = 15,
StartAudioData = 50,
StopAudioData = 51,
StartVideoData = 52,
StopVideoData = 53,
InputMouseMotion = 54,
InputMouseWheel = 55,
InputMouseDown = 56,
InputMouseUp = 57,
InputKeyDown = 58,
InputKeyUp = 59,
ShowCursor = 63,
HideCursor = 64,
SetCursor = 65,
GetCursorImage = 66,
SetCursorImage = 67,
DeleteCursor = 68,
SetTargetFramerate = 69,
InputLatencyTest = 70,
OverlayEnabled = 74,
VideoDecoderInfo = 80,
SetTitle = 81,
SetIcon = 82,
QuitRequest = 83,
SetQoS = 87,
SetGammaRamp = 89,
VideoEncoderInfo = 90,
SetTargetBitrate = 94,
SetActivity = 98,
SetStreamingClientConfig = 99,
SystemSuspend = 100,
VirtualHereRequest = 102,
VirtualHereReady = 103,
VirtualHereShareDevice = 104,
SetSpectatorMode = 105,
RemoteHID = 106,
StartMicrophoneData = 107,
StopMicrophoneData = 108,
InputText = 109,
TouchConfigActive = 110,
GetTouchConfigData = 111,
SetTouchConfigData = 112,
SaveTouchConfigLayout = 113,
TouchActionSetActive = 114,
GetTouchIconData = 115,
SetTouchIconData = 116,
InputTouchFingerDown = 117,
InputTouchFingerMotion = 118,
InputTouchFingerUp = 119,
SetCaptureSize = 120,
SetFlashState = 121,
Pause = 122,
Resume = 123,
EnableHighResCapture = 124,
DisableHighResCapture = 125,
ToggleMagnification = 126,
SetCapslock = 127,
SetKeymap = 128,
StopRequest = 129,
TouchActionSetLayerAdded = 130,
TouchActionSetLayerRemoved = 131,
}
enum EStreamDataMessage {
DataPacket = 1,
DataLost = 2,
}
enum EStreamDeviceFormFactor {
Unknown = 0,
Phone = 1,
Tablet = 2,
Computer = 3,
TV = 4,
}
enum EStreamDiscoveryMessage {
PingRequest = 1,
PingResponse = 2,
}
enum EStreamFrameEvent {
InputEventStart = 0,
InputEventSend = 1,
InputEventRecv = 2,
InputEventQueued = 3,
InputEventHandled = 4,
Start = 5,
CaptureBegin = 6,
CaptureEnd = 7,
ConvertBegin = 8,
ConvertEnd = 9,
EncodeBegin = 10,
EncodeEnd = 11,
Send = 12,
Recv = 13,
DecodeBegin = 14,
DecodeEnd = 15,
UploadBegin = 16,
UploadEnd = 17,
Complete = 18,
}
enum EStreamFramerateLimiter {
SlowCapture = 1,
SlowConvert = 2,
SlowEncode = 4,
SlowNetwork = 8,
SlowDecode = 16,
SlowGame = 32,
SlowDisplay = 64,
}
enum EStreamFrameResult {
Pending = 0,
Displayed = 1,
DroppedNetworkSlow = 2,
DroppedNetworkLost = 3,
DroppedDecodeSlow = 4,
DroppedDecodeCorrupt = 5,
DroppedLate = 6,
DroppedReset = 7,
}
enum EStreamGamepadInputType {
Invalid = 0,
DPadUp = 1,
DPadDown = 2,
DPadLeft = 4,
DPadRight = 8,
Start = 16,
Back = 32,
LeftThumb = 64,
RightThumb = 128,
LeftShoulder = 256,
RightShoulder = 512,
Guide = 1024,
A = 4096,
B = 8192,
X = 16384,
Y = 32768,
LeftThumbX = 65536,
LeftThumbY = 131072,
RightThumbX = 262144,
RightThumbY = 524288,
LeftTrigger = 1048576,
RightTrigger = 2097152,
}
enum EStreamHostPlayAudioPreference {
k_EStreamHostPlayAudioDefault = 0,
k_EStreamHostPlayAudioAlways = 1,
}
enum EStreamingDataType {
AudioData = 0,
VideoData = 1,
MicrophoneData = 2,
}
enum EStreamInterface {
Default = 0,
RecentGames = 1,
BigPicture = 2,
Desktop = 3,
}
enum EStreamMouseButton {
Left = 1,
Right = 2,
Middle = 16,
X1 = 32,
X2 = 64,
Unknown = 4096,
}
enum EStreamMouseWheelDirection {
Down = -120,
Left = 3,
Right = 4,
Up = 120,
}
enum EStreamP2PScope {
Unknown = 0,
Disabled = 1,
OnlyMe = 2,
Friends = 3,
Everyone = 4,
}
enum EStreamQualityPreference {
Fast = 1,
Balanced = 2,
Beautiful = 3,
}
enum EStreamStatsMessage {
FrameEvents = 1,
DebugDump = 2,
LogMessage = 3,
LogUploadBegin = 4,
LogUploadData = 5,
LogUploadComplete = 6,
}
enum EStreamTransport {
None = 0,
UDP = 1,
UDPRelay = 2,
WebRTC = 3,
SDR = 4,
UDP_SNS = 5,
SNS = 6,
UDPRelay_SNS = 6,
}
enum EStreamVersion {
None = 0,
Current = 1,
}
enum EStreamVideoCodec {
None = 0,
Raw = 1,
VP8 = 2,
VP9 = 3,
H264 = 4,
HEVC = 5,
ORBX1 = 6,
ORBX2 = 7,
}
enum ESystemIMType {
RawText = 0,
InvalidCard = 1,
RecurringPurchaseFailed = 2,
CardWillExpire = 3,
SubscriptionExpired = 4,
GuestPassReceived = 5,
GuestPassGranted = 6,
GiftRevoked = 7,
SupportMessage = 8,
SupportMessageClearAlert = 9,
}
enum ETradeOfferConfirmationMethod {
Invalid = 0,
Email = 1,
MobileApp = 2,
}
enum ETradeOfferState {
Invalid = 1,
Active = 2,
Accepted = 3,
Countered = 4,
Expired = 5,
Canceled = 6,
Declined = 7,
InvalidItems = 8,
CreatedNeedsConfirmation = 9,
CanceledBySecondFactor = 10,
InEscrow = 11,
}
enum EUCMFilePrivacyState {
Invalid = -1,
Private = 2,
FriendsOnly = 4,
Public = 8,
}
enum EUdpPacketType {
Invalid = 0,
ChallengeReq = 1,
Challenge = 2,
Connect = 3,
Accept = 4,
Disconnect = 5,
Data = 6,
Datagram = 7,
Max = 8,
}
enum EUniverse {
Invalid = 0,
Public = 1,
Beta = 2,
Internal = 3,
Dev = 4,
}
enum EUserReviewScorePreference {
Unset = 0,
IncludeAll = 1,
ExcludeBombs = 2,
}
enum EValveIndexComponent {
Unknown = 0,
HMD = 1,
LeftKnuckle = 2,
RightKnuckle = 3,
}
enum EVideoFormat {
None = 0,
YV12 = 1,
Accel = 2,
}
enum EVoiceCallState {
None = 0,
ScheduledInitiate = 1,
RequestedMicAccess = 2,
LocalMicOnly = 3,
CreatePeerConnection = 4,
InitatedWebRTCSession = 5,
WebRTCConnectedWaitingOnIceConnected = 6,
RequestedPermission = 7,
NotifyingVoiceChatOfWebRTCSession = 8,
Connected = 9,
}
enum EWorkshopEnumerationType {
RankedByVote = 0,
Recent = 1,
Trending = 2,
FavoriteOfFriends = 3,
VotedByFriends = 4,
ContentByFriends = 5,
RecentFromFollowedUsers = 6,
}
enum EWorkshopFileAction {
Played = 0,
Completed = 1,
}
enum EWorkshopFileType {
First = 0,
SteamworksAccessInvite = 13,
SteamVideo = 14,
GameManagedItem = 15,
}
enum E_STAR_GlyphWriteResult {
Success = 0,
InvalidMessage = 1,
InvalidJSON = 2,
SQLError = 3,
}
enum EClientUIMode {
None = 0,
BigPicture = 1,
Mobile = 2,
Web = 3,
}
enum EConnectionProtocol {
Auto = 0,
TCP = 1,
WebSocket = 2,
}
enum EMachineIDType {
None = 1,
AlwaysRandom = 2,
AccountNameGenerated = 3,
PersistentRandom = 4,
}
enum EPrivacyState {
Private = 1,
FriendsOnly = 2,
Public = 3,
}
enum EPurchaseResult {
Unknown = -1,
OK = 0,
AlreadyOwned = 9,
RegionLockedKey = 13,
InvalidKey = 14,
DuplicatedKey = 15,
BaseGameRequired = 24,
OnCooldown = 53,
}
//#endregion "ENUMS"
} | the_stack |
"use strict";
import * as tl from "azure-pipelines-task-lib/task";
import * as fs from 'fs';
import ContainerConnection from "azure-pipelines-tasks-docker-common-v2/containerconnection";
import * as dockerCommandUtils from "azure-pipelines-tasks-docker-common-v2/dockercommandutils";
import * as utils from "./utils";
import { findDockerFile } from "azure-pipelines-tasks-docker-common-v2/fileutils";
import { WebRequest, WebResponse, sendRequest } from 'utility-common-v2/restutilities';
import { getBaseImageName, getResourceName, getBaseImageNameFromDockerFile } from "azure-pipelines-tasks-docker-common-v2/containerimageutils";
import * as pipelineUtils from "azure-pipelines-tasks-docker-common-v2/pipelineutils";
import Q = require('q');
const matchPatternForDigestAndSize = new RegExp(/sha256\:([\w]+)(\s+)size\:\s([\w]+)/);
let publishMetadataResourceIds: string[] = [];
function pushMultipleImages(connection: ContainerConnection, imageNames: string[], tags: string[], commandArguments: string, onCommandOut: (image, output) => any): any {
let promise: Q.Promise<void>;
// create chained promise of push commands
if (imageNames && imageNames.length > 0) {
imageNames.forEach(imageName => {
if (tags && tags.length > 0) {
tags.forEach(tag => {
if (tag) {
let imageNameWithTag = imageName + ":" + tag;
tl.debug("Pushing ImageNameWithTag: " + imageNameWithTag);
if (promise) {
promise = promise.then(() => {
return dockerCommandUtils.push(connection, imageNameWithTag, commandArguments, onCommandOut)
});
}
else {
promise = dockerCommandUtils.push(connection, imageNameWithTag, commandArguments, onCommandOut);
}
}
});
}
else {
tl.debug("Pushing ImageName: " + imageName);
if (promise) {
promise = promise.then(() => {
return dockerCommandUtils.push(connection, imageName, commandArguments, onCommandOut)
});
}
else {
promise = dockerCommandUtils.push(connection, imageName, commandArguments, onCommandOut);
}
}
});
}
// will return undefined promise in case imageNames is null or empty list
return promise;
}
export function run(connection: ContainerConnection, outputUpdate: (data: string) => any, isBuildAndPushCommand?: boolean): any {
try {
var imageLsCommand = connection.createCommand();
imageLsCommand.arg("images");
connection.execCommand(imageLsCommand);
} catch (ex) {
}
// ignore the arguments input if the command is buildAndPush, as it is ambiguous
let commandArguments = isBuildAndPushCommand ? "" : dockerCommandUtils.getCommandArguments(tl.getInput("arguments", false));
// get tags input
let tagsInput = tl.getInput("tags");
let tags = tagsInput ? tagsInput.split(/[\n,]+/) : [];
// get repository input
let repositoryName = tl.getInput("repository");
if (!repositoryName) {
tl.warning("No repository is specified. Nothing will be pushed.");
}
let imageNames: string[] = [];
// if container registry is provided, use that
// else, use the currently logged in registries
if (tl.getInput("containerRegistry")) {
let imageName = connection.getQualifiedImageName(repositoryName, true);
if (imageName) {
imageNames.push(imageName);
}
}
else {
imageNames = connection.getQualifiedImageNamesFromConfig(repositoryName, true);
}
const dockerfilepath = tl.getInput("dockerFile", true);
let dockerFile = "";
if (isBuildAndPushCommand) {
// For buildAndPush command, to find out the base image name, we can use the
// Dockerfile returned by findDockerfile as we are sure that this is used
// for building.
dockerFile = findDockerFile(dockerfilepath);
if (!tl.exist(dockerFile)) {
throw new Error(tl.loc('ContainerDockerFileNotFound', dockerfilepath));
}
}
// push all tags
let output = "";
let outputImageName = "";
let digest = "";
let imageSize = "";
let promise = pushMultipleImages(connection, imageNames, tags, commandArguments, (image, commandOutput) => {
output += commandOutput;
outputImageName = image;
let digest = extractDigestFromOutput(commandOutput, matchPatternForDigestAndSize);
tl.debug("outputImageName: " + outputImageName + "\n" + "commandOutput: " + commandOutput + "\n" + "digest:" + digest + "imageSize:" + imageSize);
publishToImageMetadataStore(connection, outputImageName, tags, digest, dockerFile).then((result) => {
tl.debug("ImageDetailsApiResponse: " + JSON.stringify(result));
}, (error) => {
tl.warning("publishToImageMetadataStore failed with error: " + error);
});
});
if (promise) {
promise = promise.then(() => {
let taskOutputPath = utils.writeTaskOutput("push", output);
outputUpdate(taskOutputPath);
});
}
else {
tl.debug(tl.loc('NotPushingAsNoLoginFound'));
promise = Q.resolve(null);
}
return promise;
}
async function publishToImageMetadataStore(connection: ContainerConnection, imageName: string, tags: string[], digest: string, dockerFilePath: string): Promise<any> {
// Getting imageDetails
const imageUri = getResourceName(imageName, digest);
const baseImageName = dockerFilePath ? getBaseImageNameFromDockerFile(dockerFilePath) : "NA";
const history = await dockerCommandUtils.getHistory(connection, imageName);
if (!history) {
return null;
}
const layers = dockerCommandUtils.getLayers(history);
const imageSize = dockerCommandUtils.getImageSize(layers);
// Get data for ImageFingerPrint
// v1Name is the layerID for the final layer in the image
// v2Blobs are ordered list of layers that represent the given image, obtained from docker inspect output
const v1Name = dockerCommandUtils.getImageFingerPrintV1Name(history);
const imageRootfsLayers = await dockerCommandUtils.getImageRootfsLayers(connection, v1Name);
let imageFingerPrint: { [key: string]: string | string[] } = {};
if (imageRootfsLayers && imageRootfsLayers.length > 0) {
imageFingerPrint = dockerCommandUtils.getImageFingerPrint(imageRootfsLayers, v1Name);
}
// Getting pipeline variables
const build = "build";
const hostType = tl.getVariable("System.HostType").toLowerCase();
const runId = hostType === build ? parseInt(tl.getVariable("Build.BuildId")) : parseInt(tl.getVariable("Release.ReleaseId"));
const pipelineVersion = hostType === build ? tl.getVariable("Build.BuildNumber") : tl.getVariable("Release.ReleaseName");
const pipelineName = tl.getVariable("System.DefinitionName");
const pipelineId = tl.getVariable("System.DefinitionId");
const jobName = tl.getVariable("System.PhaseDisplayName");
const creator = dockerCommandUtils.getCreatorEmail();
const logsUri = dockerCommandUtils.getPipelineLogsUrl();
const artifactStorageSourceUri = dockerCommandUtils.getPipelineUrl();
const contextUrl = tl.getVariable("Build.Repository.Uri") || "";
const revisionId = tl.getVariable("Build.SourceVersion") || "";
const addPipelineData = tl.getBoolInput("addPipelineData");
const labelArguments = pipelineUtils.getDefaultLabels(addPipelineData);
const buildOptions = dockerCommandUtils.getBuildAndPushArguments(dockerFilePath, labelArguments, tags);
// Capture Repository data for Artifact traceability
const repositoryTypeName = tl.getVariable("Build.Repository.Provider");
const repositoryId = tl.getVariable("Build.Repository.ID");
const repositoryName = tl.getVariable("Build.Repository.Name");
const branch = tl.getVariable("Build.SourceBranchName");
const requestUrl = tl.getVariable("System.TeamFoundationCollectionUri") + tl.getVariable("System.TeamProject") + "/_apis/deployment/imagedetails?api-version=5.0-preview.1";
const requestBody: string = JSON.stringify(
{
"imageName": imageUri,
"imageUri": imageUri,
"hash": digest,
"baseImageName": baseImageName,
"distance": layers.length,
"imageType": "",
"mediaType": "",
"tags": tags,
"layerInfo": layers,
"runId": runId,
"pipelineVersion": pipelineVersion,
"pipelineName": pipelineName,
"pipelineId": pipelineId,
"jobName": jobName,
"imageSize": imageSize,
"creator": creator,
"logsUri": logsUri,
"artifactStorageSourceUri": artifactStorageSourceUri,
"contextUrl": contextUrl,
"revisionId": revisionId,
"buildOptions": buildOptions,
"repositoryTypeName": repositoryTypeName,
"repositoryId": repositoryId,
"repositoryName": repositoryName,
"branch": branch,
"imageFingerPrint": imageFingerPrint
}
);
if (publishMetadataResourceIds.indexOf(imageUri) < 0) {
publishMetadataResourceIds.push(imageUri);
}
if (publishMetadataResourceIds.length > 0) {
tl.setVariable("RESOURCE_URIS", publishMetadataResourceIds.join(","));
}
return sendRequestToImageStore(requestBody, requestUrl);
}
function extractDigestFromOutput(dockerPushCommandOutput: string, matchPattern: RegExp): string {
// SampleCommandOutput : The push refers to repository [xyz.azurecr.io/acr-helloworld]
// 3b7670606102: Pushed
// e2af85e4b310: Pushed ce8609e9fdad: Layer already exists
// f2b18e6d6636: Layer already exists
// 62: digest: sha256:5e3c9cf1692e129744fe7db8315f05485c6bb2f3b9f6c5096ebaae5d5bfbbe60 size: 5718
// Below regex will extract part after sha256, so expected return value will be 5e3c9cf1692e129744fe7db8315f05485c6bb2f3b9f6c5096ebaae5d5bfbbe60
const imageMatch = dockerPushCommandOutput.match(matchPattern);
let digest = "";
if (imageMatch && imageMatch.length >= 1) {
digest = imageMatch[1];
}
return digest;
}
async function sendRequestToImageStore(requestBody: string, requestUrl: string): Promise<any> {
const request = new WebRequest();
const accessToken: string = tl.getEndpointAuthorizationParameter('SYSTEMVSSCONNECTION', 'ACCESSTOKEN', false);
request.uri = requestUrl;
request.method = 'POST';
request.body = requestBody;
request.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + accessToken
};
tl.debug("requestUrl: " + requestUrl);
tl.debug("requestBody: " + requestBody);
tl.debug("accessToken: " + accessToken);
try {
tl.debug("Sending request for pushing image to Image meta data store");
const response = await sendRequest(request);
return response;
}
catch (error) {
tl.debug("Unable to push to Image Details Artifact Store, Error: " + error);
}
return Promise.resolve();
} | the_stack |
import React from "react";
import { useEffect } from "react";
import styled from "styled-components";
import { useDispatch, useSelector } from "react-redux";
import { closeAllPanels, setCurrentCodeError } from "@codestream/webview/store/context/actions";
import { useDidMount, usePrevious } from "@codestream/webview/utilities/hooks";
import {
addCodeErrors,
updateCodeError,
api,
fetchCodeError,
fetchErrorGroup,
PENDING_CODE_ERROR_ID_PREFIX,
resolveStackTrace,
setErrorGroup
} from "@codestream/webview/store/codeErrors/actions";
import { CodeStreamState } from "../store";
import { getCodeError, getErrorGroup } from "../store/codeErrors/reducer";
import { Meta, BigTitle, Header } from "./Codemark/BaseCodemark";
import { closePanel, markItemRead } from "./actions";
import { Dispatch } from "../store/common";
import { CodeError, BaseCodeErrorHeader, ExpandedAuthor, Description, Message } from "./CodeError";
import ScrollBox from "./ScrollBox";
import KeystrokeDispatcher from "../utilities/keystroke-dispatcher";
import { isFeatureEnabled } from "../store/apiVersioning/reducer";
import Icon from "./Icon";
import { isConnected } from "../store/providers/reducer";
import { ConfigureNewRelic } from "./ConfigureNewRelic";
import Dismissable from "./Dismissable";
import { bootstrapCodeErrors } from "@codestream/webview/store/codeErrors/actions";
import { DelayedRender } from "../Container/DelayedRender";
import { LoadingMessage } from "../src/components/LoadingMessage";
import {
GetNewRelicErrorGroupRequestType,
ResolveStackTraceResponse,
MatchReposRequestType,
MatchReposResponse,
NewRelicErrorGroup,
NormalizeUrlRequestType,
NormalizeUrlResponse,
WarningOrError,
GetNewRelicErrorGroupResponse
} from "@codestream/protocols/agent";
import { HostApi } from "..";
import { CSCodeError } from "@codestream/protocols/api";
import { RepositoryAssociator } from "./CodeError/RepositoryAssociator";
import { logWarning } from "../logger";
import { Link } from "./Link";
const NavHeader = styled.div`
// flex-grow: 0;
// flex-shrink: 0;
// display: flex;
// align-items: flex-start;
padding: 15px 10px 10px 15px;
// justify-content: center;
width: 100%;
${Header} {
margin-bottom: 0;
}
${BigTitle} {
font-size: 16px;
}
`;
const Root = styled.div`
max-height: 100%;
display: flex;
flex-direction: column;
&.tour-on {
${Meta},
${Description},
${ExpandedAuthor},
${Header},
.replies-to-review {
opacity: 0.25;
}
}
#changed-files {
transition: opacity 0.2s;
}
.pulse #changed-files {
opacity: 1;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
background: var(--app-background-color-hover);
}
.scroll-container {
flex-grow: 1;
width: 100%;
overflow: auto;
zindex: 1;
}
// prefer icons to text
@media only screen and (max-width: 430px) {
.btn-group {
button {
.narrow-icon {
display: block;
margin: 0;
}
padding: 3px 5px;
line-height: 1em;
}
}
.wide-text {
display: none;
}
}
`;
export const CodeErrorErrorBox = styled.div`
margin: 10px 10px 20px 0;
border: 1px solid rgba(249, 197, 19, 0.6);
background: rgba(255, 223, 0, 0.1);
border-radius: 5px;
padding: 10px;
display: flex;
align-items: center;
.icon.alert {
display: inline-block;
transform: scale(1.5);
margin: 0 10px;
}
.message {
margin-left: 10px;
}
`;
export const StyledCodeError = styled.div``;
export type Props = React.PropsWithChildren<{ codeErrorId: string; composeOpen: boolean }>;
/**
* Called from InlineCodemarks it is what allows the commenting on lines of code
*
* @export
* @param {Props} props
* @return {*}
*/
export function CodeErrorNav(props: Props) {
const dispatch = useDispatch<Dispatch | any>();
const derivedState = useSelector((state: CodeStreamState) => {
const codeError = state.context.currentCodeErrorId
? (getCodeError(state.codeErrors, state.context.currentCodeErrorId) as CSCodeError)
: undefined;
const errorGroup = getErrorGroup(state.codeErrors, codeError) as NewRelicErrorGroup;
const result = {
demoMode: state.preferences.demoMode,
codeErrorStateBootstrapped: state.codeErrors.bootstrapped,
currentCodeErrorId: state.context.currentCodeErrorId,
currentCodeErrorData: state.context.currentCodeErrorData,
sessionStart: state.context.sessionStart,
codeError: codeError,
currentCodemarkId: state.context.currentCodemarkId,
isConnectedToNewRelic: isConnected(state, { id: "newrelic*com" }),
errorGroup: errorGroup,
repos: state.repos
};
return result;
});
const [requiresConnection, setRequiresConnection] = React.useState<boolean | undefined>(
undefined
);
const [isEditing, setIsEditing] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(true);
const [error, setError] = React.useState<
{ title?: string; description: string; details?: any } | undefined
>(undefined);
const [repoAssociationError, setRepoAssociationError] = React.useState<
{ title: string; description: string } | undefined
>(undefined);
const [repoWarning, setRepoWarning] = React.useState<WarningOrError | undefined>(undefined);
const [repoError, setRepoError] = React.useState<string | undefined>(undefined);
const { errorGroup } = derivedState;
const [isResolved, setIsResolved] = React.useState(false);
const [parsedStack, setParsedStack] = React.useState<ResolveStackTraceResponse | undefined>(
undefined
);
// TODO rename these "pending" properties -- they might _always_ be pending creation
const pendingErrorGroupGuid = derivedState.currentCodeErrorData?.pendingErrorGroupGuid;
const pendingEntityId = derivedState.currentCodeErrorData?.pendingEntityId;
const occurrenceId = derivedState.currentCodeErrorData?.occurrenceId;
const remote = derivedState.currentCodeErrorData?.remote;
const commit = derivedState.currentCodeErrorData?.commit;
const previousCurrentCodeErrorId = usePrevious(derivedState.currentCodeErrorId);
const pendingRequiresConnection = derivedState.currentCodeErrorData?.pendingRequiresConnection;
const exit = async () => {
// clear out the current code error (set to blank) in the webview
await dispatch(setCurrentCodeError(undefined, undefined));
dispatch(closePanel());
};
const unreadEnabled = useSelector((state: CodeStreamState) =>
isFeatureEnabled(state, "readItem")
);
const markRead = () => {
// @ts-ignore
if (derivedState.codeError && unreadEnabled)
dispatch(markItemRead(derivedState.codeError.id, derivedState.codeError.numReplies || 0));
};
useEffect(() => {
if (
derivedState.sessionStart &&
derivedState.currentCodeErrorData?.sessionStart &&
derivedState.currentCodeErrorData?.sessionStart !== derivedState.sessionStart
) {
logWarning("preventing reload from creating a codeError, sessionStart mismatch", {
currentCodeErrorDataSessionStart: derivedState.currentCodeErrorData?.sessionStart,
sessionStart: derivedState.sessionStart
});
dispatch(setCurrentCodeError(undefined, undefined));
dispatch(closeAllPanels());
return;
}
if (pendingRequiresConnection) {
setRequiresConnection(pendingRequiresConnection);
} else if (pendingErrorGroupGuid) {
onConnected(undefined);
} else {
const onDidMount = () => {
if (derivedState.codeError) {
onConnected(derivedState.codeError);
markRead();
} else {
dispatch(fetchCodeError(derivedState.currentCodeErrorId!))
.then(_ => {
if (!_ || !_.payload.length) {
setError({
title: "Cannot open Code Error",
description:
"This code error was not found. Perhaps it was deleted by the author, or you don't have permission to view it."
});
} else {
onConnected(_.payload[0]);
markRead();
}
})
.catch(ex => {
setError({
title: "Error",
description: ex.message ? ex.message : ex.toString()
});
})
.finally(() => {
setIsLoading(false);
});
}
};
if (!derivedState.codeErrorStateBootstrapped) {
dispatch(bootstrapCodeErrors()).then(() => {
onDidMount();
});
} else {
onDidMount();
}
}
}, [derivedState.currentCodeErrorId]);
useEffect(() => {
if (
!derivedState.codeError ||
!derivedState.codeError.objectId ||
!derivedState.isConnectedToNewRelic ||
errorGroup
) {
return;
}
setIsLoading(true);
dispatch(fetchErrorGroup(derivedState.codeError));
setTimeout(() => {
setIsLoading(false);
}, 1);
}, [derivedState.codeError, derivedState.isConnectedToNewRelic, errorGroup]);
useEffect(() => {
if (
previousCurrentCodeErrorId &&
derivedState.currentCodeErrorId &&
previousCurrentCodeErrorId !== derivedState.currentCodeErrorId
) {
// if the panel is still open... re-trigger an update
onConnected(undefined);
}
}, [derivedState.currentCodeErrorId]);
const onConnected = async (
codeErrorArg: CSCodeError | undefined,
newRemote?: string,
isConnected?: boolean
) => {
console.log("onConnected starting...");
// don't always have the codeError from the state
// sometimes we have to load it here (happens when you load the IDE with an existing codeError open)
const codeError = codeErrorArg || derivedState.codeError;
let isExistingCodeError;
let errorGroupGuidToUse: string | undefined;
let occurrenceIdToUse: string | undefined;
let commitToUse: string | undefined;
let entityIdToUse: string | undefined;
if (pendingErrorGroupGuid) {
errorGroupGuidToUse = pendingErrorGroupGuid;
occurrenceIdToUse = occurrenceId;
commitToUse = commit;
entityIdToUse = pendingEntityId;
} else if (codeError) {
isExistingCodeError = true;
errorGroupGuidToUse = codeError?.objectId;
const existingStackTrace =
codeError.stackTraces && codeError.stackTraces[0] ? codeError.stackTraces[0] : undefined;
if (existingStackTrace) {
occurrenceIdToUse = existingStackTrace.occurrenceId;
commitToUse = existingStackTrace.sha;
}
entityIdToUse = codeError?.objectInfo?.entityId;
}
if (!errorGroupGuidToUse) {
console.error("missing error group guid");
return;
}
console.log(`onConnected started isExistingCodeError=${isExistingCodeError}`);
setIsLoading(true);
setRepoAssociationError(undefined);
setError(undefined);
try {
let errorGroupResult: GetNewRelicErrorGroupResponse | undefined = undefined;
if (isConnected || derivedState.isConnectedToNewRelic) {
errorGroupResult = await HostApi.instance.send(GetNewRelicErrorGroupRequestType, {
errorGroupGuid: errorGroupGuidToUse,
occurrenceId: occurrenceIdToUse,
entityGuid: entityIdToUse
});
if (!errorGroupResult || errorGroupResult?.error?.message) {
setError({
title: "Unexpected Error",
description: errorGroupResult?.error?.message || "unknown error",
details: errorGroupResult?.error?.details
});
return;
}
}
let repoId: string | undefined = undefined;
let stackInfo: ResolveStackTraceResponse | undefined = undefined;
let targetRemote;
if (
errorGroupResult &&
errorGroupResult.errorGroup &&
!errorGroupResult.errorGroup.hasStackTrace
) {
setIsResolved(true);
setRepoWarning({ message: "There is no stack trace associated with this error." });
} else {
if (errorGroupResult?.errorGroup?.entity?.relationship?.error?.message != null) {
setError({
title: "Repository Relationship Error",
// @ts-ignore
description: errorGroupResult.errorGroup.entity.relationship.error.message!
});
return;
}
targetRemote = newRemote || remote;
if (errorGroupResult?.errorGroup?.entity?.repo?.urls != null) {
targetRemote = errorGroupResult?.errorGroup?.entity?.repo?.urls[0]!;
} else if (codeError?.objectInfo?.remote) {
targetRemote = codeError?.objectInfo?.remote;
}
if (!targetRemote) {
if (derivedState.isConnectedToNewRelic) {
setRepoAssociationError({
title: "Missing Repository Info",
description: `In order to view this stack trace, please select a repository to associate with ${
errorGroup ? errorGroup.entityName + " " : ""
}on New Relic. If the repo that was used to build this service doesn't appear in the dropdown, open it in your IDE.`
});
return;
}
}
if (targetRemote) {
// we have a remote, try to find a repo.
const normalizationResponse = (await HostApi.instance.send(NormalizeUrlRequestType, {
url: targetRemote
})) as NormalizeUrlResponse;
if (!normalizationResponse || !normalizationResponse.normalizedUrl) {
setError({
title: "Error",
description: `Could not find a matching repo for the remote ${targetRemote}`
});
return;
}
const reposResponse = (await HostApi.instance.send(MatchReposRequestType, {
repos: [
{
remotes: [normalizationResponse.normalizedUrl],
knownCommitHashes: commitToUse ? [commitToUse] : []
}
]
})) as MatchReposResponse;
if (reposResponse?.repos?.length === 0) {
setError({
title: "Repo Not Found",
description: `Please open the following repository: ${targetRemote}`
});
return;
}
repoId = reposResponse.repos[0].id!;
}
if (!repoId) {
// no targetRemote, try to get a repo from existing stackTrace
repoId =
codeError?.stackTraces && codeError?.stackTraces.length > 0
? codeError.stackTraces[0].repoId
: "";
}
// YUCK
const stack =
errorGroupResult?.errorGroup?.errorTrace?.stackTrace?.map(_ => _.formatted) ||
(codeError?.stackTraces && codeError.stackTraces.length > 0
? codeError.stackTraces[0].text?.split("\n")
: []);
if (stack) {
stackInfo = (await resolveStackTrace(
errorGroupGuidToUse!,
repoId!,
commitToUse!,
occurrenceIdToUse!,
stack!
)) as ResolveStackTraceResponse;
}
}
if (errorGroupResult && errorGroupResult.errorGroup != null) {
dispatch(setErrorGroup(errorGroupGuidToUse, errorGroupResult.errorGroup!));
}
const actualStackInfo = stackInfo
? stackInfo.error
? [{ ...stackInfo, lines: [] }]
: [stackInfo.parsedStackInfo!]
: [];
if (errorGroupResult) {
if (
derivedState.currentCodeErrorId &&
derivedState.currentCodeErrorId?.indexOf(PENDING_CODE_ERROR_ID_PREFIX) === 0
) {
await dispatch(
addCodeErrors([
{
accountId: errorGroupResult.accountId,
id: derivedState.currentCodeErrorId!,
createdAt: new Date().getTime(),
modifiedAt: new Date().getTime(),
// these don't matter
assignees: [],
teamId: "",
streamId: "",
postId: "",
fileStreamIds: [],
status: "open",
numReplies: 0,
lastActivityAt: 0,
creatorId: "",
objectId: errorGroupGuidToUse,
objectType: "errorGroup",
title: errorGroupResult.errorGroup?.title || "",
text: errorGroupResult.errorGroup?.message || undefined,
// storing the permanently parsed stack info
stackTraces: actualStackInfo,
objectInfo: {
repoId: repoId!,
remote: targetRemote,
accountId: errorGroupResult.accountId.toString(),
entityId: errorGroupResult?.errorGroup?.entityGuid || "",
entityName: errorGroupResult?.errorGroup?.entityName || ""
}
}
])
);
} else if (derivedState.codeError && !derivedState.codeError.objectInfo) {
// codeError has an currentCodeErrorId, but isn't pending... it also doesn't have an objectInfo,
// so update it with one
await dispatch(
updateCodeError({
...derivedState.codeError,
accountId: errorGroupResult.accountId,
title: errorGroupResult.errorGroup?.title || "",
text: errorGroupResult.errorGroup?.message || undefined,
// storing the permanently parsed stack info
stackTraces: actualStackInfo,
objectInfo: {
repoId: repoId,
remote: targetRemote,
accountId: errorGroupResult.accountId.toString(),
entityId: errorGroupResult?.errorGroup?.entityGuid || "",
entityName: errorGroupResult?.errorGroup?.entityName || ""
}
})
);
}
}
if (stackInfo) {
setParsedStack(stackInfo);
setRepoError(stackInfo.error);
setRepoWarning(stackInfo.warning);
}
setIsResolved(true);
let trackingData = {
"Error Group ID": errorGroupResult?.errorGroup?.guid || codeError?.objectInfo?.entityId,
"NR Account ID": errorGroupResult?.accountId || codeError?.objectInfo?.accountId || "0",
"Entry Point": derivedState.currentCodeErrorData?.openType || "Open in IDE Flow",
"Stack Trace": !!(stackInfo && !stackInfo.error)
};
if (trackingData["Stack Trace"]) {
trackingData["Build SHA"] = !commitToUse
? "Missing"
: stackInfo?.warning
? "Warning"
: "Populated";
}
HostApi.instance.track("Error Opened", trackingData);
} catch (ex) {
console.warn(ex);
setError({
title: "Unexpected Error",
description: ex.message ? ex.message : ex.toString()
});
} finally {
setRequiresConnection(false);
setIsLoading(false);
}
};
const tryBuildWarningsOrErrors = () => {
if (derivedState.demoMode) return null;
const items: WarningOrError[] = [];
if (repoError) {
items.push({ message: repoError });
}
if (repoWarning) {
items.push(repoWarning);
}
if (!items.length) return null;
return (
<CodeErrorErrorBox>
<Icon name="alert" className="alert" />
<div className="message">
{items.map(_ => {
const split = _.message.split("\n");
return split.map((item, index) => {
return (
<div key={"warningOrError_" + index}>
{item}
{_.helpUrl && split.length - 1 === index && (
<>
{" "}
<Link href={_.helpUrl!}>Learn more</Link>
</>
)}
<br />
</div>
);
});
})}
</div>
</CodeErrorErrorBox>
);
};
useDidMount(() => {
// Kind of a HACK leaving this here, BUT...
// since <CancelButton /> uses the OLD version of Button.js
// and not Button.tsx (below), there's no way to keep the style.
// if Buttons can be consolidated, this could go away
const disposable = KeystrokeDispatcher.onKeyDown(
"Escape",
event => {
if (event.key === "Escape" && event.target.id !== "input-div") exit();
},
{ source: "CodeErrorNav.tsx", level: -1 }
);
return () => {
disposable && disposable.dispose();
};
});
// if for some reason we have a codemark, don't render anything
if (derivedState.currentCodemarkId) return null;
if (error) {
// essentially a roadblock
return (
<Dismissable
title={error.title || "Error"}
buttons={[
{
text: "Dismiss",
onClick: e => {
e.preventDefault();
exit();
}
}
]}
>
<p>{error.description}</p>
{error?.details?.settings && (
<div>
<b>Internal Debugging Variables</b>
<dl style={{ overflow: "auto" }}>
{Object.keys(error.details.settings).map(_ => {
return (
<>
<dt>{_}</dt>
<dd>{error.details.settings[_]}</dd>
</>
);
})}
</dl>
</div>
)}
</Dismissable>
);
}
if (repoAssociationError) {
// essentially a roadblock
return (
<RepositoryAssociator
error={repoAssociationError}
onCancelled={e => {
exit();
}}
onSubmit={r => {
return new Promise((resolve, reject) => {
const payload = {
url: r.remote,
name: r.name,
entityId: pendingEntityId,
errorGroupGuid: derivedState.codeError?.objectId || pendingErrorGroupGuid!,
parseableAccountId: derivedState.codeError?.objectId || pendingErrorGroupGuid!
};
dispatch(api("assignRepository", payload)).then(_ => {
setIsLoading(true);
if (_?.directives) {
console.log("assignRepository", {
directives: _?.directives
});
setRepoAssociationError(undefined);
resolve(true);
HostApi.instance.track("NR Repo Association", {
"Error Group ID": payload.errorGroupGuid
});
onConnected(
undefined,
_.directives.find(_ => _.type === "assignRepository").data.repo.urls[0]
);
} else {
console.log("Could not find directive", {
payload: payload
});
resolve(true);
setError({
title: "Failed to associate repository",
description: _?.error
});
}
});
});
}}
/>
);
}
if (requiresConnection) {
return (
<Root>
<div
style={{
display: "flex",
alignItems: "center",
width: "100%"
}}
>
<div
style={{ marginLeft: "auto", marginRight: "13px", whiteSpace: "nowrap", flexGrow: 0 }}
>
<Icon
className="clickable"
name="x"
onClick={exit}
title="Close View"
placement="bottomRight"
delay={1}
/>
</div>
</div>
<div className="embedded-panel">
<ConfigureNewRelic
headerChildren={
<>
<div className="panel-header" style={{ background: "none" }}>
<span className="panel-title">Connect to New Relic</span>
</div>
<div style={{ textAlign: "center" }}>
Working with errors requires a connection to your New Relic account.
</div>
</>
}
disablePostConnectOnboarding={true}
showSignupUrl={false}
providerId={"newrelic*com"}
onClose={e => {
dispatch(closeAllPanels());
}}
onSubmited={async e => {
onConnected(undefined, undefined, true);
}}
originLocation={"Open in IDE Flow"}
/>
</div>
</Root>
);
}
if (isLoading) {
return (
<DelayedRender>
<div style={{ display: "flex", height: "100vh", alignItems: "center" }}>
<LoadingMessage>Loading Error Group...</LoadingMessage>
</div>
</DelayedRender>
);
}
if (derivedState.codeError == null) return null;
return (
<Root>
<div
style={{
display: "flex",
alignItems: "center",
width: "100%"
}}
>
{/* <div
style={{
width: "1px",
height: "16px",
background: "var(--base-border-color)",
display: "inline-block",
margin: "0 10px 0 0",
flexGrow: 0
}}
/> */}
<div style={{ marginLeft: "auto", marginRight: "13px", whiteSpace: "nowrap", flexGrow: 0 }}>
<Icon
className="clickable"
name="x"
onClick={exit}
title="Close View"
placement="bottomRight"
delay={1}
/>
</div>
</div>
<>
<NavHeader id="nav-header">
<BaseCodeErrorHeader
codeError={derivedState.codeError!}
errorGroup={errorGroup}
collapsed={false}
setIsEditing={setIsEditing}
></BaseCodeErrorHeader>
</NavHeader>
{props.composeOpen ? null : (
<div className="scroll-container">
<ScrollBox>
<div
className="vscroll"
id="code-error-container"
style={{
padding: "0 20px 60px 40px",
width: "100%"
}}
>
{/* TODO perhaps consolidate these? */}
{tryBuildWarningsOrErrors()}
<StyledCodeError className="pulse">
<CodeError
parsedStack={parsedStack}
codeError={derivedState.codeError!}
errorGroup={errorGroup}
stackFrameClickDisabled={!!repoError}
/>
</StyledCodeError>
</div>
</ScrollBox>
</div>
)}
</>
</Root>
);
} | the_stack |
import { Injectable } from '@angular/core';
import { createModuleTest } from './tests/createModuleTest';
import { createComponentTest } from './tests/createComponentTest';
import { createBootstrapTest } from './tests/bootstrapTest';
import { DiffFilesResolver } from '../libs/utils/src/lib/differ/diffFilesResolver';
declare const require;
const preloadedFiles = {
'app.component.ts': require(`!raw-loader!./app.component.ts`),
'app.module.ts': require('!raw-loader!./app.module.ts'),
'app.html': require('!raw-loader!./app.html'),
'main.ts': require('!raw-loader!./main.ts'),
'style.css': require('!raw-loader!./style.css'),
'video/video-item.ts': require('!raw-loader!./video/video-item.ts'),
'api.service.ts': require('!raw-loader!./api.service.ts'),
'material.css': require('!!raw-loader!@angular/material/prebuilt-themes/indigo-pink.css'),
'search/search.component.html': require('!raw-loader!./search/search.component.html'),
'search/search.component.ts': require('!raw-loader!./search/search.component.ts'),
'upload/upload.component.html': require('!raw-loader!./upload/upload.component.html'),
'upload/upload.component.ts': require('!raw-loader!./upload/upload.component.ts'),
'video/video.service.ts': require('!raw-loader!./video/video.service.ts'),
'video/video.component.html': require('!raw-loader!./video/video.component.html'),
'video/video-materialized.component.html': require('!raw-loader!./video/video-materialized.component.html'),
'video/video.index.html': require('!raw-loader!./video/video.index.html'),
'video/video-wrapper.component.ts': require('!raw-loader!./video/video-wrapper.component.ts'),
'video/video.component.ts': require('!raw-loader!./video/video.component.ts'),
'thumbs/thumbs.component.ts': require('!raw-loader!./thumbs/thumbs.component.ts'),
'thumbs/thumbs.html': require('!raw-loader!./thumbs/thumbs.html'),
'toggle-panel/toggle-panel.html': require('!raw-loader!./toggle-panel/toggle-panel.html'),
'toggle-panel/toggle-panel.component.ts': require('!raw-loader!./toggle-panel/toggle-panel.component.ts'),
'wrapper.component.ts': require('!raw-loader!./wrapper.component.ts'),
'context/context.component.ts': require('!raw-loader!./context/context.component.ts'),
'context/context.service.ts': require('!raw-loader!./context/context.service.ts'),
'context/context.html': require('!raw-loader!./context/context.html'),
'typescript-intro/Codelab.ts': require('!raw-loader!./typescript-intro/Codelab.ts'),
'typescript-intro/Main.ts': require('!raw-loader!./typescript-intro/Main.ts'),
'typescript-intro/Guest.ts': require('!raw-loader!./typescript-intro/Guest.ts'),
'fuzzy-pipe/fuzzy.pipe.ts': require('!raw-loader!./fuzzy-pipe/fuzzy.pipe.ts'),
'tests/codelabTest.ts': require('!raw-loader!./tests/codelabTest.ts'),
'tests/createComponentTest.ts': require('!raw-loader!./tests/createComponentTest.ts'),
'tests/createModuleTest.ts': require('!raw-loader!./tests/createModuleTest.ts'),
'tests/bootstrapTest.ts': require('!raw-loader!./tests/bootstrapTest.ts'),
'tests/templatePageSetupTest.ts': require('!raw-loader!./tests/templatePageSetupTest.ts'),
'tests/routerTest.ts': require('!raw-loader!./tests/routerTest.ts'),
'tests/formsTest.ts': require('!raw-loader!./tests/formsTest.ts'),
'tests/materialTest.ts': require('!raw-loader!./tests/materialTest.ts'),
'tests/templateAddActionTest.ts': require('!raw-loader!./tests/templateAddActionTest.ts'),
'tests/templateAllVideosTest.ts': require('!raw-loader!./tests/templateAllVideosTest.ts'),
'tests/diInjectServiceTest.ts': require('!raw-loader!./tests/diInjectServiceTest.ts'),
'tests/videoComponentCreateTest.ts': require('!raw-loader!./tests/videoComponentCreateTest.ts'),
'tests/videoComponentUseTest.ts': require('!raw-loader!./tests/videoComponentUseTest.ts'),
'tests/ThumbsComponentCreateTest.ts': require('!raw-loader!./tests/ThumbsComponentCreateTest.ts'),
'tests/ThumbsComponentUseTest.ts': require('!raw-loader!./tests/ThumbsComponentUseTest.ts'),
'tests/togglePanelComponentCreateTest.ts': require('!raw-loader!./tests/togglePanelComponentCreateTest.ts'),
'tests/togglePanelComponentUseTest.ts': require('!raw-loader!./tests/togglePanelComponentUseTest.ts'),
'tests/contextComponentUseTest.ts': require('!raw-loader!./tests/contextComponentUseTest.ts'),
'tests/fuzzyPipeCreateTest.ts': require('!raw-loader!./tests/fuzzyPipeCreateTest.ts'),
'tests/fuzzyPipeUseTest.ts': require('!raw-loader!./tests/fuzzyPipeUseTest.ts'),
'thumbs.app.module.ts': require('!raw-loader!./thumbs.app.module.ts'),
'video.app.module.ts': require('!raw-loader!./video.app.module.ts'),
'toggle-panel.app.module.ts': require('!raw-loader!./toggle-panel.app.module.ts'),
'index.html': '<base href="/assets/runner/"><my-app></my-app><div class="error"></div>'
// 'index.html': '<my-thumbs></my-thumbs><my-wrapper></my-wrapper>'
};
const files = {
appComponent: 'app.component.ts',
appModule: 'app.module.ts',
appHtml: 'app.html',
main: 'main.ts',
video_videoItem: 'video/video-item.ts',
apiService: 'api.service.ts',
search_search_component_html: 'search/search.component.html',
search_search_component: 'search/search.component.ts',
upload_upload_component_html: 'upload/upload.component.html',
upload_upload_component: 'upload/upload.component.ts',
video_videoService: 'video/video.service.ts',
video_video_component_html: 'video/video.component.html',
video_video_component: 'video/video.component.ts',
video_video_wrapper_component: 'video/video-wrapper.component.ts',
video_video_index_html: 'video/video.index.html',
thumbs_thumbs_component: 'thumbs/thumbs.component.ts',
thumbs_thumbs_html: 'thumbs/thumbs.html',
toggle_panel_toggle_panel_html: 'toggle-panel/toggle-panel.html',
toggle_panel_toggle_panel: 'toggle-panel/toggle-panel.component.ts',
wrapperComponent: 'wrapper.component.ts',
contextComponent: 'context/context.component.ts',
context_context_html: 'context/context.html',
contextService: 'context/context.service.ts',
typescript_intro_Codelab_ts: 'typescript-intro/Codelab.ts',
typescript_intro_Main_ts: 'typescript-intro/Main.ts',
typescript_intro_Guest_ts: 'typescript-intro/Guest.ts',
fuzzyPipe_fuzzyPipe: 'fuzzy-pipe/fuzzy.pipe.ts',
test: 'tests/test.ts',
indexHtml: 'index.html',
style_css: 'style.css',
material_css: 'material.css'
};
const fileOverrides = {
'index.html': {
videoComponentCreate: 'video/video.index.html'
},
'app.module.ts': {
videoComponentCreate: 'video.app.module.ts',
thumbsComponentCreate: 'thumbs.app.module.ts',
togglePanelComponentCreate: 'toggle-panel.app.module.ts'
},
'tests/test.ts': {
codelab: 'tests/codelabTest.ts',
createComponent: 'tests/createComponentTest.ts',
createModule: 'tests/createModuleTest.ts',
bootstrap: 'tests/bootstrapTest.ts',
templatePageSetup: 'tests/templatePageSetupTest.ts',
templateAddAction: 'tests/templateAddActionTest.ts',
templateAllVideos: 'tests/templateAllVideosTest.ts',
diInjectService: 'tests/diInjectServiceTest.ts',
videoComponentCreate: 'tests/videoComponentCreateTest.ts',
videoComponentUse: 'tests/videoComponentUseTest.ts',
thumbsComponentCreate: 'tests/ThumbsComponentCreateTest.ts',
thumbsComponentUse: 'tests/ThumbsComponentUseTest.ts',
togglePanelComponentCreate: 'tests/togglePanelComponentCreateTest.ts',
togglePanelComponentUse: 'tests/togglePanelComponentUseTest.ts',
contextComponentUse: 'tests/contextComponentUseTest.ts',
fuzzyPipeCreate: 'tests/fuzzyPipeCreateTest.ts',
fuzzyPipeUse: 'tests/fuzzyPipeUseTest.ts',
router: 'tests/routerTest.ts',
material: 'tests/materialTest.ts',
forms: 'tests/formsTest.ts'
},
'video/video.component.html': {
material: 'video/video-materialized.component.html',
forms: 'video/video-materialized.component.html'
}
};
const stageOverrides = {
'main.ts': {
createComponent: 'bootstrapSolved',
createModule: 'bootstrapSolved',
},
'app.module.ts': {
createComponent: 'bootstrapSolved'
}
};
const stages: string[] = [
'codelab',
'createComponent',
'createModule',
'bootstrap',
'templatePageSetup',
'templateAddAction',
'templateAllVideos',
'diInjectService',
'dataBinding',
'videoComponentCreate',
'videoComponentUse',
'router',
'material',
'forms',
'thumbsComponentCreate',
'thumbsComponentUse',
'togglePanelComponentCreate',
'togglePanelComponentUse',
'contextComponentUse',
'fuzzyPipeCreate',
'fuzzyPipeUse',
'neverShow'
];
const diffFilesResolver = new DiffFilesResolver(preloadedFiles, stages, {
file: fileOverrides,
stage: stageOverrides
});
export interface CodelabConfigTemplate {
name: string;
id: string;
defaultRunner: string;
milestones: MilestoneConfigTemplate[];
}
export interface SlideTemplate {
slide: true;
name: string;
}
export interface ExerciseConfigTemplate {
slide?: false;
name: string;
skipTests?: boolean;
runner?: string;
files: {
exercise?: string[];
reference?: string[];
hidden?: string[];
bootstrap?: string[];
test?: string[];
};
}
export interface MilestoneConfigTemplate {
name: string;
exercises: Array<ExerciseConfigTemplate | SlideTemplate>;
}
function patchATestWithAFunctionINAHackyWay(exercisesFiles, path, callback) {
return exercisesFiles.map(file => {
if (file.path === path) {
file.execute = callback;
}
return file;
});
}
export function convertExerciseToMap(exercise) {
const convertFilesToMap = (prop = 'template') => (result, file) => {
if (file[prop]) {
result[file.path] = file[prop];
if (file.execute) {
result[file.path + '.execute'] = file.execute;
}
}
return result;
};
const testBootstrap = exercise.files.find(({bootstrap, excludeFromTesting, template}) => template && bootstrap && !excludeFromTesting);
const bootstrapFiles = exercise.files.find(({bootstrap, excludeFromTesting, template}) => template && bootstrap && excludeFromTesting);
return {
highlights: exercise.files.filter(({highlight}) => highlight).reduce((result, {highlight, path}) => (result[path] = highlight, result), {}),
code: exercise.files.reduce(convertFilesToMap(), {}),
codeSolutions: exercise.files.map(file => ((file.solution = file.solution || file.template), file)).reduce(convertFilesToMap('solution'), {}),
test: exercise.files.filter(file => !file.excludeFromTesting).reduce(convertFilesToMap(), {}),
bootstrap: bootstrapFiles && bootstrapFiles.moduleName,
bootstrapTest: testBootstrap && testBootstrap.moduleName,
file: exercise.files[0].path
};
}
export const ng2tsConfig: /*TODO: fix the type to be: CodelabConfigTemplate */any = {
name: 'Angular 101 Codelab (beta)',
id: 'ng2ts',
defaultRunner: 'Angular',
milestones: [
{
name: 'Intro to TypeScript',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'TypeScript',
runner: 'TypeScript',
files: diffFilesResolver.resolve('codelab', {
exercise: [
files.typescript_intro_Codelab_ts,
files.typescript_intro_Guest_ts,
files.typescript_intro_Main_ts
],
test: [files.test],
bootstrap: [
files.typescript_intro_Main_ts
]
}),
}
]
},
{
name: 'Bootstrapping your app',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'Create a component',
files: patchATestWithAFunctionINAHackyWay(diffFilesResolver.resolve('createComponent', {
exercise: [files.appComponent],
reference: [files.appModule, files.main, files.style_css, files.indexHtml],
bootstrap: [files.main],
test: [files.test],
}), 'tests/test.ts', createComponentTest)
},
{
name: 'Create a NgModule',
files: patchATestWithAFunctionINAHackyWay(diffFilesResolver.resolve('createModule', {
exercise: [files.appModule],
reference: [files.appComponent],
hidden: [files.main],
test: [files.test],
bootstrap: [files.main]
}), 'tests/test.ts', createModuleTest)
},
{
name: 'Bootstrap the module',
skipTests: true,
files: patchATestWithAFunctionINAHackyWay(diffFilesResolver.resolve('bootstrap', {
exercise: [files.main],
reference: [files.appComponent, files.appModule],
test: [files.test],
bootstrap: [files.main]
}), 'tests/test.ts', createBootstrapTest)
}
]
},
{
name: 'Templates',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'Set up the page',
files: diffFilesResolver.resolve('templatePageSetup', {
exercise: [files.appHtml],
reference: [files.appComponent, files.appModule, files.main, files.style_css, files.indexHtml],
test: [files.test],
bootstrap: [files.main]
})
}, {
name: 'Add some action',
files: diffFilesResolver.resolve('templateAddAction', {
exercise: [files.appComponent, files.appHtml],
reference: [files.appModule, files.main, files.video_videoItem, files.style_css, files.indexHtml],
test: [files.test],
bootstrap: [files.main],
})
},
{
name: 'Display all videos',
files: diffFilesResolver.resolve('templateAllVideos', {
exercise: [files.appComponent, files.appHtml],
reference: [files.appModule, files.main, files.video_videoItem, files.style_css, files.indexHtml],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Dependency Injection',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'Service injection',
files: diffFilesResolver.resolve('diInjectService', {
exercise: [files.video_videoService, files.appModule, files.appComponent],
reference: [
files.appHtml, files.apiService, files.video_videoItem, files.main, files.style_css, files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
}
,
{
name: 'Component Tree',
exercises: [
{
name: 'Intro',
slide: true,
},
{
name: 'Create VideoComponent',
files: diffFilesResolver.resolve('videoComponentCreate', {
exercise: [files.video_video_component, files.video_video_component_html],
reference: [
files.appModule,
files.video_video_wrapper_component,
files.video_videoService, files.appHtml,
files.appComponent, files.video_videoItem,
files.apiService, files.main, files.style_css, files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: 'Use VideoComponent',
files: diffFilesResolver.resolve('videoComponentUse', {
exercise: [files.appModule, files.appHtml],
reference: [
files.video_video_component_html, files.video_video_component, files.appComponent,
files.video_videoService, files.video_videoItem, files.apiService, files.main, files.style_css,
files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Routing',
exercises: [
{
name: 'Router',
files: diffFilesResolver.resolve('router', {
exercise: [
files.appModule,
files.appHtml,
files.search_search_component,
files.search_search_component_html,
files.upload_upload_component,
files.upload_upload_component_html,
],
reference: [
files.video_video_component_html, files.video_video_component, files.appComponent,
files.video_videoService, files.video_videoItem, files.apiService, files.main, files.style_css,
files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Material',
exercises: [
{
name: 'Material',
files: diffFilesResolver.resolve('material', {
exercise: [
files.appModule,
files.video_video_component_html,
files.appHtml,
],
reference: [
files.video_video_component,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main,
files.style_css,
files.indexHtml,
files.search_search_component,
files.search_search_component_html,
files.upload_upload_component,
files.upload_upload_component_html,
files.material_css
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Forms',
exercises: [
{
name: 'Forms',
files: diffFilesResolver.resolve('forms', {
exercise: [
files.appModule,
files.upload_upload_component_html,
files.upload_upload_component,
],
reference: [
files.appHtml,
files.search_search_component,
files.search_search_component_html,
files.video_video_component_html,
files.video_video_component,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main,
files.style_css,
files.indexHtml,
files.material_css
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Custom events',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'Create ThumbsComponent',
files: diffFilesResolver.resolve('thumbsComponentCreate', {
exercise: [files.thumbs_thumbs_component, files.thumbs_thumbs_html],
reference: [files.apiService, files.appModule, files.main, files.style_css, files.indexHtml],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: 'Use ThumbsComponent',
files: diffFilesResolver.resolve('thumbsComponentUse', {
exercise: [files.video_video_component, files.video_video_component_html, files.appModule],
reference: [
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main,
files.style_css,
files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Content projection',
exercises: [
{
name: 'Intro',
slide: true
},
{
name: 'Add TogglePanelComponent',
files: diffFilesResolver.resolve('togglePanelComponentCreate', {
exercise: [files.toggle_panel_toggle_panel, files.toggle_panel_toggle_panel_html],
reference: [
files.wrapperComponent, files.apiService, files.appModule, files.main, files.style_css, files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
},
{
name: 'Use TogglePanelComponent',
files: diffFilesResolver.resolve('togglePanelComponentUse', {
exercise: [files.video_video_component_html, files.appModule],
reference: [
files.video_video_component,
files.toggle_panel_toggle_panel,
files.toggle_panel_toggle_panel_html,
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main,
files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
},
{
name: 'Pipes (bonus)',
exercises: [
{
name: 'Create a pipe',
files: diffFilesResolver.resolve('fuzzyPipeCreate', {
exercise: [files.fuzzyPipe_fuzzyPipe],
test: [files.test],
bootstrap: [files.main]
})
}, {
name: 'Use the pipe',
files: diffFilesResolver.resolve('fuzzyPipeUse', {
exercise: [files.appModule, files.video_video_component_html],
reference: [
files.fuzzyPipe_fuzzyPipe,
files.contextService,
files.contextComponent,
files.context_context_html,
files.video_video_component,
files.toggle_panel_toggle_panel,
files.toggle_panel_toggle_panel_html,
files.thumbs_thumbs_component,
files.thumbs_thumbs_html,
files.appHtml,
files.appComponent,
files.video_videoService,
files.video_videoItem,
files.apiService,
files.main,
files.indexHtml
],
test: [files.test],
bootstrap: [files.main]
})
}
]
}
,
{
name: 'Survey',
exercises: [
{
slide: true,
name: 'All done!'
}
]
}
]
};
@Injectable()
export class Ng2TsExercises {
getExercises(milestoneId: number, exerciseId: number): ExerciseConfigTemplate {
return ng2tsConfig.milestones[milestoneId].exercises[exerciseId];
}
} | the_stack |
import * as oracledb from 'oracledb';
import defaultOracledb from 'oracledb';
// import dotenv from 'dotenv';
import assert from 'assert';
// dotenv.config();
/*
TABLE SETUP FOR TESTING:
CREATE TABLE CONNOR_TEST_TABLE (
TEST VARCHAR2(20) NOT NULL,
CLOB_COLUMN CLOB
);
*/
const {
DB_CONNECTION_STRING,
// DB_MAX_ROWS,
// DB_PAGE_SIZE,
DB_PASSWORD,
// DB_POOL_MAX,
// DB_POOL_MIN,
DB_USER,
} = process.env;
const initSession = (connection: oracledb.Connection, requestedTag: string, callback: () => void): void => {
connection.execute(`alter session set nls_date_format = 'YYYY-MM-DD' nls_language = AMERICAN`, callback);
};
const testBreak = (connection: oracledb.Connection): Promise<void> =>
new Promise((resolve): void => {
console.log('Testing connection.execute()...');
connection.execute(
` BEGIN
dbms_lock.sleep(:seconds);
END;
`,
[2],
(error: oracledb.DBError): void => {
// ORA-01013: user requested cancel of current operation
assert(error.message.includes('ORA-01013'), 'message not defined for DB error');
assert(error.errorNum !== undefined, 'errorNum not defined for DB error');
assert(error.offset !== undefined, 'offset not defined for DB error');
return resolve();
},
);
setTimeout((): void => {
console.log('Testing connection.execute()...');
connection.break().then((): void => {});
}, 1000);
});
const testGetStatmentInfo = async (connection: oracledb.Connection): Promise<void> => {
console.log('Testing connection.getStatementInfo()...');
const info = await connection.getStatementInfo('SELECT 1 FROM CONNOR_TEST_TABLE WHERE SYSDATE > :myDate');
assert.deepStrictEqual(
info.metaData[0],
{
name: '1',
fetchType: 2002,
dbType: 2,
nullable: true,
precision: 0,
scale: -127,
},
'connection.getStatementInfo() has invalid metaData field in its response',
);
assert(
info.bindNames.findIndex(s => s === 'MYDATE') >= 0,
'connection.getStatementInfo() has invalid bindNames field in its response',
);
assert(info.statementType === 1, 'connection.getStatementInfo() has invalid statementType field in its response');
return;
};
const testQueryStream = async (connection: oracledb.Connection): Promise<void> =>
new Promise(resolve => {
console.log('Testing connection.queryStream()...');
const stream = connection.queryStream('SELECT 1 FROM DUAL WHERE 10 < :myValue', {
myValue: {
dir: oracledb.BIND_IN,
maxSize: 50,
type: oracledb.NUMBER,
val: 20,
},
anotherValue: {
dir: oracledb.BIND_INOUT,
type: oracledb.DB_TYPE_NCLOB,
},
});
let data = '';
stream.on('data', chunk => {
data += chunk;
});
stream.on('metadata', metadata => {
assert.deepStrictEqual(metadata[0], {
name: '1',
});
});
stream.on('end', () => {
return resolve(JSON.parse(data));
});
stream.on('error', err => {
throw err;
});
});
const createAndPopulateLob = (connection: oracledb.Connection): Promise<oracledb.Lob> =>
new Promise(resolve => {
console.log('Testing connection.createLob()...');
connection.createLob(oracledb.CLOB).then(lob => {
lob.write('abcdefg', 'utf-8', err => {
if (err) {
throw err;
}
return resolve(lob);
});
});
});
const testResultSet = async (connection: oracledb.Connection): Promise<void> => {
console.log('Testing ResultSet...');
const result = await connection.execute(
` SELECT 1 FROM DUAL
UNION
SELECT 2 FROM DUAL
UNION
SELECT 3 FROM DUAL`,
{
test: undefined,
},
{
resultSet: true,
},
);
assert.deepStrictEqual(result.metaData[0], { name: '1' });
const { resultSet, lastRowid } = result;
console.log(lastRowid);
console.log('Testing resultSet.getRow()...');
const row = await resultSet.getRow();
assert.deepStrictEqual(row, [1]);
console.log('Testing resultSet.getRows()...');
const rows = await resultSet.getRows(1);
assert.deepStrictEqual(rows, [[2]]);
console.log('Testing resultSet.close()...');
await resultSet.close();
};
const runPromiseTests = async (): Promise<void> => {
try {
if (typeof DB_USER !== 'string') {
throw new Error('DB_USER must be fined');
}
if (typeof DB_PASSWORD !== 'string') {
throw new Error('DB_PASSWORD must be fined');
}
if (typeof DB_CONNECTION_STRING !== 'string') {
throw new Error('DB_CONNECTION_STRING must be fined');
}
console.log('Testing createPool()...');
await oracledb.createPool({
connectString: DB_CONNECTION_STRING,
// edition: 'myEdition',
events: true,
externalAuth: false,
homogeneous: true,
password: DB_PASSWORD,
poolAlias: 'myPool',
poolIncrement: 1,
poolMax: 5,
poolMin: 3,
poolPingInterval: 60,
poolTimeout: 60,
queueTimeout: 60000,
sessionCallback: initSession,
stmtCacheSize: 5,
user: DB_USER,
});
console.log('Testing getPool()...');
const pool = oracledb.getPool('myPool');
console.log('Testing pool.getConnection()...');
const connection = await pool.getConnection();
await testBreak(connection);
// await connection.subscribe('testNotification', {
// sql: 'SELECT * FROM CONNOR_TEST_TABLE',
// callback: async message => {
// assert.strictEqual(message.type, oracledb.SUBSCR_EVENT_TYPE_OBJ_CHANGE);
// await connection.unsubscribe('testNotification');
// }
// })
const lob = 'test'; //await createAndPopulateLob(connection);
console.log('Testing connection.executeMany()...');
// const results = await connection.executeMany(
// `INSERT INTO CONNOR_TEST_TABLE VALUES(
// :stringValue,
// NULL
// )`,
// [
// {
// stringValue: 'test',
// // clobValue: lob,
// },
// {
// stringValue: 'test2',
// // clobValue: lob,
// },
// ],
// {
// autoCommit: false,
// batchErrors: false,
// bindDefs: {
// stringValue: {
// dir: oracledb.BIND_IN,
// maxSize: 50,
// type: oracledb.STRING,
// },
// // clobValue: {
// // maxSize: 10,
// // dir: oracledb.BIND_IN,
// // type: oracledb.CLOB,
// // }
// },
// dmlRowCounts: false,
// },
// );
console.log('Testing lob.close()...');
// await lob.close();
console.log('Testing connection.commit()...');
await connection.commit();
console.log('Testing connection.changePassword()...');
await connection.changePassword(DB_USER, DB_PASSWORD, DB_PASSWORD);
await testGetStatmentInfo(connection);
await testQueryStream(connection);
console.log('Testing connection.ping()...');
await connection.ping();
console.log('Testing connection.rollback()...');
await connection.rollback();
await testResultSet(connection);
console.log('Testing connection.close()...');
await connection.close({ drop: true });
console.log('Testing pool.close()...');
await pool.close(5);
} catch (err) {
console.log(err.message);
}
};
interface One {
one: string;
}
const dbObjectTests = async () => {
const conn = await oracledb.getConnection();
interface Test {
COLUMN1: string;
COLUMN2: string;
}
const TestClass = await conn.getDbObjectClass<Test>('test');
const test1 = new TestClass({
COLUMN1: '1234',
COLUMN2: '1234',
});
test1.COLUMN1 = '1234';
TestClass.prototype;
interface Geom {
SDO_GTYPE: number;
SDO_SRID: string | null;
SDO_POINT: string | null;
SDO_ELEM_INFO: number[];
SDO_ORDINATES: number[];
}
const GeomType = await conn.getDbObjectClass<Geom>('MDSYS.SDO_GEOMETRY');
console.log(GeomType.prototype);
const geom = new GeomType();
geom.SDO_GTYPE = 2003;
geom.SDO_GTYPE = 2003;
geom.SDO_SRID = null;
geom.SDO_POINT = null;
geom.SDO_ELEM_INFO = [1, 1003, 3];
geom.SDO_ORDINATES = [1, 1, 5, 7];
geom.getKeys().find(e => e === 'SDO_ELEM_INFO');
await conn.execute(`INSERT INTO testgeometry (id, geometry) VALUES (:id, :g)`, { id: 1, g: geom });
await conn.execute(`INSERT INTO testgeometry (id, geometry) VALUES (:id, :g)`, {
id: 1,
g: {
type: 'MDSYS.SDO_GEOMETRY',
val: {
SDO_GTYPE: 2003,
SDO_SRID: null,
SDO_POINT: null,
SDO_ELEM_INFO: [1, 1003, 3],
SDO_ORDINATES: [1, 1, 5, 7],
},
},
});
interface OutGeom {
SDO_GTYPE: number;
SDO_SRID: string | null;
SDO_POINT: string | null;
SDO_ELEM_INFO: oracledb.DBObject_OUT<number>;
SDO_ORDINATES: oracledb.DBObject_OUT<number>;
}
const result = await conn.execute<oracledb.DBObject_OUT<OutGeom>[]>(
`SELECT geometry FROM testgeometry WHERE id = 1`,
);
const o = result.rows[0][0];
console.log(o.isCollection);
o.getKeys();
o.SDO_ELEM_INFO.getKeys();
console.log(o.SDO_ELEM_INFO.isCollection);
console.log(o.SDO_ELEM_INFO.getKeys().find(e => typeof e === 'number'));
console.log(o.getValues()[0].SDO_ELEM_INFO);
};
const version4Tests = async () => {
console.log(oracledb.OUT_FORMAT_ARRAY, oracledb.OUT_FORMAT_OBJECT);
const pool = await oracledb.createPool({});
const connection = await pool.getConnection();
const implicitResults = (await connection.execute<One>('SELECT 1 FROM DUAL'))
.implicitResults as oracledb.ResultSet<One>[];
(await implicitResults[0].getRow()).one;
await implicitResults[0].close();
const implicitResults2 = (await connection.execute<One>('SELECT 1 FROM DUAL')).implicitResults as One[][];
const results = implicitResults2[0][0];
console.log(results.one);
const GeomType = await connection.getDbObjectClass('MDSYS.SDO_GEOMETRY');
const geom = new GeomType({
SDO_GTYPE: 2003,
SDO_SRID: null,
SDO_POINT: null,
SDO_ELEM_INFO: [1, 1003, 3],
SDO_ORDINATES: [1, 1, 5, 7],
});
geom.attributes = {
STREET_NUMBER: { type: 2, typeName: 'NUMBER' },
LOCATION: {
type: 2023,
typeName: 'MDSYS.SDO_POINT_TYPE',
typeClass: GeomType,
},
};
new geom.attributes.test.typeClass({});
await connection.execute(`INSERT INTO testgeometry (id, geometry) VALUES (:id, :g)`, { id: 1, g: geom });
const sub = await connection.subscribe('test', {
sql: 'test',
callback: message => {
console.log(message.queueName);
},
});
console.log(sub.regId);
const queue = await connection.getQueue('test', {
payloadType: 'test',
});
const { name, deqOptions, enqOptions, payloadType, payloadTypeClass, payloadTypeName } = queue;
const { condition, consumerName, correlation, mode, msgId, navigation, transformation, visibility, wait } =
deqOptions;
const messages = await queue.deqMany(5);
const lob = await connection.createLob(2);
await lob.getData();
const plsql = `
DECLARE
c1 SYS_REFCURSOR;
c2 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code
FROM locations
WHERE location_id < 1200;
DBMS_SQL.RETURN_RESULT(c1);
OPEN C2 FOR SELECT job_id, employee_id, last_name
FROM employees
WHERE employee_id < 103;
DBMS_SQL.RETURN_RESULT(c2);
END;`;
let result = await connection.execute(plsql);
console.log(result.implicitResults);
result = await connection.execute(plsql, [], { resultSet: true });
for (let i = 0; i < result.implicitResults.length; i++) {
console.log(' Implicit Result Set', i + 1);
const rs = result.implicitResults[i] as oracledb.ResultSet<One>; // get the next ResultSet
let row;
while ((row = await rs.getRow())) {
console.log(' ', row);
}
await rs.close();
}
const queueName = 'DEMO_RAW_QUEUE';
const queue2 = await connection.getQueue(queueName);
await queue2.enqOne('This is my message');
await connection.commit();
const queueName3 = 'DEMO_RAW_QUEUE';
const queue3 = await connection.getQueue(queueName3);
const msg = await queue3.deqOne();
await connection.commit();
console.log(msg.payload.toString());
const message = new queue.payloadTypeClass({
NAME: 'scott',
ADDRESS: 'The Kennel',
});
await queue.enqOne(message);
await connection.commit();
const queue5 = await connection.getQueue(queueName, { payloadType: 'DEMOQUEUE.USER_ADDRESS_TYPE' });
const msg5 = await queue.deqOne();
await connection.commit();
};
const aqTests = async () => {
const c = await oracledb.getConnection();
interface QueueItem {
test: string;
connor: boolean;
test2: number;
}
const MyClass = await c.getDbObjectClass<QueueItem>('test');
const q = await c.getQueue<QueueItem>('test');
q.enqOne('test');
q.enqOne(new Buffer('test'));
q.enqOne(new MyClass());
const msg = await q.deqOne();
msg.payload;
};
interface MyTableRow {
firstColumn: string;
secondColumn: number;
}
const testGenerics = async () => {
const connection = await oracledb.getConnection({
user: 'test',
});
const result = await connection.execute<MyTableRow>('SELECT 1 FROM DUAL');
console.log(result.rows[0].firstColumn);
console.log(result.rows[0].secondColumn);
const result2 = await connection.execute<{ test: string }>(' BEGIN DO_SOMETHING END;', {
test: {
dir: oracledb.BIND_OUT,
val: 'something',
},
});
console.log(result2.outBinds.test);
const sql = `SELECT FIRST_COLUMN, SECOND_COLUMN FROM SOMEWHERE`;
const result3 = await connection.executeMany<MyTableRow>(sql, 5);
console.log(result3.outBinds[0].firstColumn);
};
export const testQueryStreamGenerics = (connection: oracledb.Connection): void => {
interface MyStream {
streamTest: string;
}
const stream = connection.queryStream<MyStream>('SELECT 1 FROM DUAL WHERE 10 < :myValue', {
myValue: {
dir: oracledb.BIND_IN,
maxSize: 50,
type: oracledb.NUMBER,
val: 20,
},
anotherValue: {
dir: oracledb.BIND_INOUT,
type: oracledb.DB_TYPE_NCLOB,
},
});
stream.on('data', data => {
console.log(data);
});
stream.on('metadata', metadata => {
const streamClass = metadata[0].dbTypeClass;
const streamClassInstance = new streamClass({
streamTest: 'success',
});
});
};
const test4point1 = async (): Promise<void> => {
defaultOracledb.poolMaxPerShard = 45;
await oracledb.createPool({
poolMaxPerShard: 5,
});
const connection = await oracledb.getConnection({
shardingKey: ['TEST', 1234, new Date(), new Buffer('1234')],
superShardingKey: ['TEST', 1234, new Date(), new Buffer('1234')],
});
connection.clientInfo = '12345';
connection.dbOp = '12345';
};
export const v5Tests = async (): Promise<void> => {
console.log(oracledb.SYSPRELIM);
defaultOracledb.queueRequests = 0;
defaultOracledb.prefetchRows = 5;
defaultOracledb.queueMax = 0;
defaultOracledb.createPool({
queueRequests: 0,
queueMax: 5,
});
defaultOracledb.initOracleClient({
configDir: '',
driverName: '',
errorUrl: '',
libDir: '',
});
const creds = {
user: 'test',
password: 'test',
connectionString: 'test',
externalAuth: true,
};
await defaultOracledb.startup(creds);
await defaultOracledb.startup(creds, {
force: true,
restrict: true,
pfile: '',
});
await defaultOracledb.shutdown(creds, defaultOracledb.SHUTDOWN_MODE_ABORT);
const conn = await defaultOracledb.getConnection();
await conn.startup({
force: true,
restrict: true,
pfile: '',
});
await conn.shutdown(defaultOracledb.SHUTDOWN_MODE_ABORT);
await conn.execute(
'',
{},
{
prefetchRows: 5,
},
);
};
export const v5point1Tests = (): void => {
console.log(defaultOracledb.DB_TYPE_JSON);
defaultOracledb.dbObjectAsPojo = true;
}; | the_stack |
import { setupListEditor } from './list-setup';
describe('create a list', () => {
const { taskList, li, doc, p, ul, ol, orderedList, unchecked, checked, editor } =
setupListEditor();
it('creates a bulletList', () => {
editor.add(doc(p(''))).insertText('- ');
expect(editor.doc).toEqualProsemirrorNode(doc(ul(li(p('')))));
editor.add(doc(p(''))).insertText('+ ');
expect(editor.doc).toEqualProsemirrorNode(doc(ul(li(p('')))));
editor.add(doc(p(''))).insertText('* ');
expect(editor.doc).toEqualProsemirrorNode(doc(ul(li(p('')))));
});
it('creates an orderedList', () => {
editor.add(doc(p(''))).insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(doc(orderedList({ order: 1 })(li(p('')))));
editor.add(doc(p(''))).insertText('999. ');
expect(editor.doc).toEqualProsemirrorNode(doc(orderedList({ order: 999 })(li(p('')))));
});
it('creates a taskList', () => {
editor.add(doc(p(''))).insertText('[] ');
expect(editor.doc).toEqualProsemirrorNode(doc(taskList(unchecked(p('')))));
editor.add(doc(p(''))).insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(doc(taskList(unchecked(p('')))));
editor.add(doc(p(''))).insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(doc(taskList(checked(p('')))));
editor.add(doc(p(''))).insertText('[X] ');
expect(editor.doc).toEqualProsemirrorNode(doc(taskList(checked(p('')))));
});
it('creates a task list in a bullet list', () => {
editor.add(
doc(
ul(
li(p('<cursor>')), //
),
),
);
editor.insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
unchecked(p('')), //
),
),
);
});
it('creates a task list in an ordered list', () => {
editor.add(
doc(
orderedList({ order: 1 })(
li(p('<cursor>')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('')), //
),
),
);
});
it('creates a bullet list in an ordered list', () => {
editor.add(
doc(
orderedList({ order: 1 })(
li(p('<cursor>')), //
),
),
);
editor.insertText('- ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(p('')), //
),
),
);
});
it('creates a bullet list in a task list', () => {
editor.add(
doc(
taskList(
checked(p('<cursor>')), //
),
),
);
editor.insertText('- ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(p('')), //
),
),
);
});
it('creates an ordered list in a bullet list', () => {
editor.add(
doc(
ul(
li(p('<cursor>')), //
),
),
);
editor.insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
orderedList()(
li(p('')), //
),
),
);
});
it('creates an ordered list in a task list', () => {
editor.add(
doc(
taskList(
unchecked(p('<cursor>')), //
),
),
);
editor.insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
orderedList()(
li(p('')), //
),
),
);
});
it('creates a taskList in a multi-items list', () => {
editor.add(
doc(
ul(
li(p('123')),
li(p('456')),
li(p('<cursor>')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(p('123')), //
li(p('456')), //
),
taskList(
checked(p('')), //
),
),
);
editor.add(
doc(
ul(
li(p('123')),
li(p('<cursor>')), //
li(p('789')),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(p('123')), //
),
taskList(
checked(p('')), //
),
ul(
li(p('789')), //
),
),
);
editor.add(
doc(
ul(
li(p('<cursor>')), //
li(p('456')),
li(p('789')),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('')), //
),
ul(
li(p('456')), //
li(p('789')), //
),
),
);
});
it('creates a taskList in a nested list', () => {
editor.add(
doc(
ul(
li(
p('123'),
ul(
li(p('<cursor>')), //
),
),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(
p('123'),
taskList(
checked(p('<cursor>')), //
),
),
),
),
);
editor.add(
doc(
ul(
li(
p('123'),
ul(
li(p('abc')), //
li(p('<cursor>')), //
),
),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(
p('123'),
ul(
li(p('abc')), //
),
taskList(
checked(p('<cursor>')), //
),
),
),
),
);
editor.add(
doc(
ul(
li(
p('123'),
ul(
li(p('<cursor>')), //
li(p('def')), //
),
),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(
p('123'),
taskList(
checked(p('<cursor>')), //
),
ul(
li(p('def')), //
),
),
),
),
);
editor.add(
doc(
ul(
li(
p('123'),
ul(
li(p('abc')), //
li(p('<cursor>')), //
li(p('def')), //
),
),
),
),
);
editor.insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(
p('123'),
ul(
li(p('abc')), //
),
taskList(
unchecked(p('<cursor>')), //
),
ul(
li(p('def')), //
),
),
),
),
);
});
it('does not create a list if already inside a such list', () => {
editor.add(doc(ul(li(p('<cursor>')))));
editor.insertText('- ');
expect(editor.doc).toEqualProsemirrorNode(doc(ul(li(p('- ')))));
editor.add(doc(orderedList({ order: 1 })(li(p('<cursor>')))));
editor.insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(doc(orderedList({ order: 1 })(li(p('1. ')))));
editor.add(doc(taskList(unchecked(p('<cursor>')))));
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(doc(taskList(unchecked(p('[x] ')))));
});
it('handle sub-list correctly', () => {
editor.add(
doc(
ul(
li(
p('<cursor>root item'), //
ul(
li(p('sub item')), //
),
),
),
),
);
editor.insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
orderedList()(
li(
p('<cursor>root item'), //
ul(
li(p('sub item')), //
),
),
),
),
);
editor.add(
doc(
ul(
li(
p('root item'), //
ol(
li(p('<cursor>sub item')), //
),
),
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
ul(
li(
p('<cursor>root item'), //
taskList(
checked(p('sub item')), //
),
),
),
),
);
});
});
describe('joins lists', () => {
const {
editor,
doc,
taskList,
ul: bulletList,
checked,
unchecked,
p,
orderedList,
li: listItem,
} = setupListEditor();
describe('input rules', () => {
it('bullet list => task list (join backward and forward)', () => {
editor.add(
doc(
taskList(
checked(p('A')), //
),
bulletList(
listItem(p('<cursor>B')), //
),
taskList(
checked(p('C')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('A')), //
checked(p('B')), //
checked(p('C')), //
),
),
);
});
it('bullet list => task list (join backward)', () => {
editor.add(
doc(
taskList(
checked(p('A')), //
),
bulletList(
listItem(p('<cursor>B')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('A')), //
checked(p('B')), //
),
),
);
});
it('bullet list => task list (join forward)', () => {
editor.add(
doc(
bulletList(
listItem(p('<cursor>B')), //
),
taskList(
checked(p('C')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('B')), //
checked(p('C')), //
),
),
);
});
it('ordered list => task list (join backward and forward)', () => {
editor.add(
doc(
taskList(
unchecked(p('A')), //
),
orderedList()(
listItem(p('<cursor>B')), //
),
taskList(
unchecked(p('C')), //
),
),
);
editor.insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
unchecked(p('A')), //
unchecked(p('B')), //
unchecked(p('C')), //
),
),
);
});
it('ordered list => task list (join backward)', () => {
editor.add(
doc(
taskList(
unchecked(p('A')), //
),
orderedList()(
listItem(p('<cursor>B')), //
),
),
);
editor.insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
unchecked(p('A')), //
unchecked(p('B')), //
),
),
);
});
it('ordered list => task list (join forward)', () => {
editor.add(
doc(
orderedList()(
listItem(p('<cursor>B')), //
),
taskList(
unchecked(p('C')), //
),
),
);
editor.insertText('[ ] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
unchecked(p('B')), //
unchecked(p('C')), //
),
),
);
});
it('paragraph => task list (join backward and forward)', () => {
editor.add(
doc(
taskList(
checked(p('A')), //
),
p('<cursor>B'), //
taskList(
checked(p('C')), //
),
),
);
editor.insertText('[x] ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
taskList(
checked(p('A')), //
checked(p('B')), //
checked(p('C')), //
),
),
);
});
it('paragraph => bullet list (join backward)', () => {
editor.add(
doc(
bulletList(
listItem(p('A')), //
),
p('<cursor>B'), //
taskList(
checked(p('C')), //
),
),
);
editor.insertText('- ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
bulletList(
listItem(p('A')), //
listItem(p('B')), //
),
taskList(
checked(p('C')), //
),
),
);
});
it('paragraph => ordered list (join forward)', () => {
editor.add(
doc(
bulletList(
listItem(p('A')), //
),
p('<cursor>B'), //
orderedList()(
listItem(p('C')), //
),
),
);
editor.insertText('1. ');
expect(editor.doc).toEqualProsemirrorNode(
doc(
bulletList(
listItem(p('A')), //
),
orderedList()(
listItem(p('B')), //
listItem(p('C')), //
),
),
);
});
//
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.