text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { CoinTransfer, GraphBatchedTransferAppAction, GraphBatchedTransferAppActionEncoding, GraphBatchedTransferAppState, GraphBatchedTransferAppStateEncoding, singleAssetTwoPartyCoinTransferEncoding, GraphReceipt, GRAPH_BATCHED_SWAP_CONVERSION, } from "@connext/types"; import { getTestVerifyingContract, getAddressFromPrivateKey, getTestGraphReceiptToSign, signGraphReceiptMessage, keyify, signGraphConsumerMessage, getRandomBytes32, } from "@connext/utils"; import { BigNumber, Contract, ContractFactory, constants, utils, Wallet } from "ethers"; import { GraphBatchedTransferApp } from "../../artifacts"; import { expect, provider, mkAddress } from "../utils"; const { Zero } = constants; const { defaultAbiCoder } = utils; const decodeTransfers = (encodedAppState: string): CoinTransfer[] => defaultAbiCoder.decode([singleAssetTwoPartyCoinTransferEncoding], encodedAppState)[0]; const decodeAppState = (encodedAppState: string): GraphBatchedTransferAppState => defaultAbiCoder.decode([GraphBatchedTransferAppStateEncoding], encodedAppState)[0]; const encodeAppState = ( state: GraphBatchedTransferAppState, onlyCoinTransfers: boolean = false, ): string => { if (!onlyCoinTransfers) return defaultAbiCoder.encode([GraphBatchedTransferAppStateEncoding], [state]); return defaultAbiCoder.encode([singleAssetTwoPartyCoinTransferEncoding], [state.coinTransfers]); }; function encodeAppAction(state: GraphBatchedTransferAppAction): string { return defaultAbiCoder.encode([GraphBatchedTransferAppActionEncoding], [state]); } describe("GraphBatchedTransferApp", () => { let indexerWallet: Wallet; let consumerWallet: Wallet; let graphBatchedTransferApp: Contract; async function computeOutcome(state: GraphBatchedTransferAppState): Promise<CoinTransfer[]> { const ret = await graphBatchedTransferApp.computeOutcome(encodeAppState(state)); return keyify(state.coinTransfers, decodeTransfers(ret)); } async function applyAction( state: GraphBatchedTransferAppState, action: GraphBatchedTransferAppAction, ): Promise<GraphBatchedTransferAppState> { const ret = await graphBatchedTransferApp.applyAction( encodeAppState(state), encodeAppAction(action), ); return keyify(state, decodeAppState(ret)); } async function validateOutcome(outcome: CoinTransfer[], postState: GraphBatchedTransferAppState) { expect(outcome[0].to).eq(postState.coinTransfers[0].to); expect(outcome[0].amount.toString()).eq(postState.coinTransfers[0].amount.toString()); expect(outcome[1].to).eq(postState.coinTransfers[1].to); expect(outcome[1].amount.toString()).eq(postState.coinTransfers[1].amount.toString()); } async function validateAction( preState: GraphBatchedTransferAppState, postState: GraphBatchedTransferAppState, action: GraphBatchedTransferAppAction, ): Promise<void> { const calculatedState = { ...preState, coinTransfers: [ { amount: preState.coinTransfers[0].amount.sub( action.totalPaid.mul(preState.swapRate).div(GRAPH_BATCHED_SWAP_CONVERSION), ), to: preState.coinTransfers[0].to, }, { amount: preState.coinTransfers[1].amount.add( action.totalPaid.mul(preState.swapRate).div(GRAPH_BATCHED_SWAP_CONVERSION), ), to: preState.coinTransfers[1].to, }, ], chainId: BigNumber.from(preState.chainId), finalized: true, }; expect(postState).to.deep.equal(calculatedState); } async function getInitialState(receipt: GraphReceipt): Promise<GraphBatchedTransferAppState> { return { coinTransfers: [ { amount: BigNumber.from(10000), to: mkAddress("0xa"), }, { amount: Zero, to: mkAddress("0xB"), }, ], attestationSigner: getAddressFromPrivateKey(indexerWallet.privateKey), consumerSigner: getAddressFromPrivateKey(consumerWallet.privateKey), chainId: (await indexerWallet.provider.getNetwork()).chainId, verifyingContract: getTestVerifyingContract(), subgraphDeploymentID: receipt.subgraphDeploymentID, swapRate: BigNumber.from(1).mul(GRAPH_BATCHED_SWAP_CONVERSION), paymentId: getRandomBytes32(), finalized: false, }; } async function getAction( receipt: GraphReceipt, totalPaid: BigNumber, state0: GraphBatchedTransferAppState, ): Promise<GraphBatchedTransferAppAction> { const attestationSignature = await signGraphReceiptMessage( receipt, state0.chainId, state0.verifyingContract, indexerWallet.privateKey, ); const consumerSignature = await signGraphConsumerMessage( receipt, state0.chainId, state0.verifyingContract, totalPaid, state0.paymentId, consumerWallet.privateKey, ); return { totalPaid, requestCID: receipt.requestCID, responseCID: receipt.responseCID, attestationSignature, consumerSignature, }; } beforeEach(async () => { indexerWallet = provider.getWallets()[0]; consumerWallet = provider.getWallets()[1]; graphBatchedTransferApp = await new ContractFactory( GraphBatchedTransferApp.abi, GraphBatchedTransferApp.bytecode, indexerWallet, ).deploy(); }); it("can unlock a batched payment with correct signatures and no swap rate", async () => { const receipt = getTestGraphReceiptToSign(); const totalPaid = BigNumber.from(500); const state0 = await getInitialState(receipt); const action = await getAction(receipt, totalPaid, state0); const state1 = await applyAction(state0, action); await validateAction(state0, state1, action); const outcome = await computeOutcome(state1); await validateOutcome(outcome, state1); }); it("can unlock a batched payment with correct signatures and a swap rate", async () => { const receipt = getTestGraphReceiptToSign(); const totalPaid = BigNumber.from(500); const state0 = await getInitialState(receipt); state0.swapRate = BigNumber.from(1).mul(GRAPH_BATCHED_SWAP_CONVERSION).div(2); // 0.5 const action = await getAction(receipt, totalPaid, state0); const state1 = await applyAction(state0, action); await validateAction(state0, state1, action); const outcome = await computeOutcome(state1); await validateOutcome(outcome, state1); }); // it("can repeatedly create and unlock payments", async () => { // const iterations = 5; // const receipt = getTestGraphReceiptToSign(); // const initialState = await getInitialState(receipt); // let latestState: GraphBatchedTransferAppState; // let prevState = initialState; // for (let i = 0; i < iterations; i++) { // // Create // const createAction = await getCreateAction(receipt); // latestState = await applyAction(prevState, createAction); // await validateAction(prevState, latestState, createAction); // prevState = latestState; // // Unlock // const signature: string = await signGraphReceiptMessage( // receipt, // await wallet.getChainId(), // prevState.verifyingContract, // wallet.privateKey, // ); // const unlockAction = await getUnlockAction(receipt, signature); // latestState = await applyAction(prevState, unlockAction); // await validateAction(prevState, latestState, unlockAction); // prevState = latestState; // } // const outcome = await computeOutcome(latestState!); // expect(outcome[0].amount).to.eq( // initialState.coinTransfers[0].amount.sub(BigNumber.from(10).mul(iterations)), // ); // expect(outcome[1].amount).to.eq( // initialState.coinTransfers[1].amount.add(BigNumber.from(10).mul(iterations)), // ); // }); // it("cannot take action when state is finalized", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const finalizedState = { // ...state0, // finalized: true, // }; // const action0 = await getCreateAction(receipt); // await expect(applyAction(finalizedState, action0)).revertedWith( // "Cannot take action on finalized state", // ); // }); // it("cannot call create with odd turnNum", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const oddState = { // ...state0, // turnNum: state0.turnNum + 1, // }; // const action0 = await getCreateAction(receipt); // await expect(applyAction(oddState, action0)).revertedWith( // "Transfers can only be created by the app initiator", // ); // }); // it("cannot create for more value than you have", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const poorState = { // ...state0, // coinTransfers: [ // { // ...state0.coinTransfers[0], // amount: BigNumber.from(5), // }, // { // ...state0.coinTransfers[1], // }, // ], // }; // const action0 = await getCreateAction(receipt); // await expect(applyAction(poorState, action0)).revertedWith( // "Cannot create transfer for more value than in balance", // ); // }); // it("cannot call unlock with even turnNum", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const signature = await signGraphReceiptMessage( // receipt, // state0.chainId, // state0.verifyingContract, // wallet.privateKey, // ); // const action0 = await getUnlockAction(receipt, signature); // await expect(applyAction(state0, action0)).revertedWith( // "Transfers can only be unlocked by the app responder", // ); // }); // it("cannot call unlock with incorrect signature", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const action0 = await getCreateAction(receipt); // const state1 = await applyAction(state0, action0); // await validateAction(state0, state1, action0); // const badSignature = hexZeroPad(hexlify(1), 65); // const action1 = await getUnlockAction(receipt, badSignature); // await expect(applyAction(state1, action1)).revertedWith( // "ECDSA: invalid signature 'v' value", // ); // }); // it("does not update balances if cancelled", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const action0 = await getCreateAction(receipt); // const state1 = await applyAction(state0, action0); // await validateAction(state0, state1, action0); // const emptySignature = hexZeroPad(hexlify(0), 65); // let action1 = await getUnlockAction(receipt, emptySignature); // action1 = { // ...action1, // responseCID: HashZero, // } // const state2 = await applyAction(state1, action1); // expect(state2).to.deep.eq({ // ...state0, // turnNum: BigNumber.from(state0.turnNum + 2), // chainId: BigNumber.from(state0.chainId) // }) // }); // it("can finalize on either turntaker", async () => { // const receipt = getTestGraphReceiptToSign(); // const state0 = await getInitialState(receipt); // const finalizeAction = await getFinalizeAction() // const finalizeEvens = await applyAction(state0, finalizeAction) // await validateAction(state0, finalizeEvens, finalizeAction) // const action0 = await getCreateAction(receipt); // const state1 = await applyAction(state0, action0); // await validateAction(state0, state1, action0); // const finalizeOdds = await applyAction(state1, finalizeAction) // await validateAction(state1, finalizeOdds, finalizeAction) // }) // it("can get the correct turntaker", async () => { // const receipt = getTestGraphReceiptToSign(); // const evenState = await getInitialState(receipt); // const participants = [ // mkAddress("0xa"), // mkAddress("0xB") // ] // const turnTakerEven = await graphBatchedTransferApp.getTurnTaker(encodeAppState(evenState), participants); // expect(turnTakerEven).to.be.eq(participants[0]) // const oddState = { // ...evenState, // turnNum: evenState.turnNum+1, // } // const turnTakerOdd = await graphBatchedTransferApp.getTurnTaker(encodeAppState(oddState), participants); // expect(turnTakerOdd).to.be.eq(participants[1]) // }) });
the_stack
import React, { useEffect, useState } from 'react'; import { Button, Form, message, Modal, Select, Tag, Typography } from 'antd'; import styled from 'styled-components'; import { CorpUser, EntityType, OwnerEntityType, OwnershipType, SearchResult, } from '../../../../../../../types.generated'; import { useEntityRegistry } from '../../../../../../useEntityRegistry'; import { CustomAvatar } from '../../../../../../shared/avatar'; import analytics, { EventType, EntityActionType } from '../../../../../../analytics'; import { OWNERSHIP_DISPLAY_TYPES } from './ownershipUtils'; import { useAddOwnersMutation } from '../../../../../../../graphql/mutations.generated'; import { useGetSearchResultsLazyQuery } from '../../../../../../../graphql/search.generated'; const SearchResultContainer = styled.div` display: flex; justify-content: space-between; align-items: center; padding: 2px; `; const SearchResultContent = styled.div` display: flex; justify-content: center; align-items: center; `; const SelectInput = styled(Select)` > .ant-select-selector { height: 36px; } `; type Props = { urn: string; type: EntityType; visible: boolean; defaultOwnerType?: OwnershipType; hideOwnerType?: boolean | undefined; onCloseModal: () => void; refetch?: () => Promise<any>; }; // value: {ownerUrn: string, ownerEntityType: EntityType} type SelectedOwner = { label: string; value; }; export const AddOwnersModal = ({ urn, type, visible, hideOwnerType, defaultOwnerType, onCloseModal, refetch, }: Props) => { const entityRegistry = useEntityRegistry(); const [addOwnersMutation] = useAddOwnersMutation(); const ownershipTypes = OWNERSHIP_DISPLAY_TYPES; const [selectedOwners, setSelectedOwners] = useState<SelectedOwner[]>([]); const [selectedOwnerType, setSelectedOwnerType] = useState<OwnershipType>(defaultOwnerType || OwnershipType.None); // User and group dropdown search results! const [userSearch, { data: userSearchData }] = useGetSearchResultsLazyQuery(); const [groupSearch, { data: groupSearchData }] = useGetSearchResultsLazyQuery(); const userSearchResults = userSearchData?.search?.searchResults || []; const groupSearchResults = groupSearchData?.search?.searchResults || []; const combinedSearchResults = [...userSearchResults, ...groupSearchResults]; // Add owners Form const [form] = Form.useForm(); useEffect(() => { if (ownershipTypes) { setSelectedOwnerType(ownershipTypes[0].type); } }, [ownershipTypes]); /** * When a owner search result is selected, add the new owner to the selectedOwners * value: {ownerUrn: string, ownerEntityType: EntityType} */ const onSelectOwner = (selectedValue: { key: string; label: React.ReactNode; value: string }) => { const filteredActors = combinedSearchResults .filter((result) => result.entity.urn === selectedValue.value) .map((result) => result.entity); if (filteredActors.length) { const actor = filteredActors[0]; const ownerEntityType = actor && actor.type === EntityType.CorpGroup ? OwnerEntityType.CorpGroup : OwnerEntityType.CorpUser; const newValues = [ ...selectedOwners, { label: selectedValue.value, value: { ownerUrn: selectedValue.value, ownerEntityType, }, }, ]; setSelectedOwners(newValues); } }; // When a owner search result is deselected, remove the Owner const onDeselectOwner = (selectedValue: { key: string; label: React.ReactNode; value: string }) => { const newValues = selectedOwners.filter((owner) => owner.label !== selectedValue.value); setSelectedOwners(newValues); }; // When a owner type is selected, set the type as selected type. const onSelectOwnerType = (newType: OwnershipType) => { setSelectedOwnerType(newType); }; // Invokes the search API as the owner types const handleSearch = (entityType: EntityType, text: string, searchQuery: any) => { if (text.length > 2) { searchQuery({ variables: { input: { type: entityType, query: text, start: 0, count: 5, }, }, }); } }; // Invokes the user search API for both users and groups. const handleActorSearch = (text: string) => { handleSearch(EntityType.CorpUser, text, userSearch); handleSearch(EntityType.CorpGroup, text, groupSearch); }; // Renders a search result in the select dropdown. const renderSearchResult = (result: SearchResult) => { const avatarUrl = result.entity.type === EntityType.CorpUser ? (result.entity as CorpUser).editableProperties?.pictureLink || undefined : undefined; const displayName = entityRegistry.getDisplayName(result.entity.type, result.entity); return ( <SearchResultContainer> <SearchResultContent> <CustomAvatar size={24} name={displayName} photoUrl={avatarUrl} isGroup={result.entity.type === EntityType.CorpGroup} /> <div>{displayName}</div> </SearchResultContent> </SearchResultContainer> ); }; const onModalClose = () => { setSelectedOwners([]); setSelectedOwnerType(defaultOwnerType || OwnershipType.None); form.resetFields(); onCloseModal(); }; // Function to handle the modal action's const onOk = async () => { if (selectedOwners.length === 0) { return; } const inputs = selectedOwners.map((selectedActor) => { const input = { ownerUrn: selectedActor.value.ownerUrn, ownerEntityType: selectedActor.value.ownerEntityType, type: selectedOwnerType, }; return input; }); try { await addOwnersMutation({ variables: { input: { owners: inputs, resourceUrn: urn, }, }, }); message.success({ content: 'Owners Added', duration: 2 }); analytics.event({ type: EventType.EntityActionEvent, actionType: EntityActionType.UpdateOwnership, entityType: type, entityUrn: urn, }); } catch (e: unknown) { message.destroy(); if (e instanceof Error) { message.error({ content: `Failed to add owners: \n ${e.message || ''}`, duration: 3 }); } } finally { refetch?.(); onModalClose(); } }; const tagRender = (props) => { // eslint-disable-next-line react/prop-types const { label, closable, onClose } = props; const onPreventMouseDown = (event) => { event.preventDefault(); event.stopPropagation(); }; return ( <Tag onMouseDown={onPreventMouseDown} closable={closable} onClose={onClose} style={{ padding: '0px 7px 0px 0px', marginRight: 3, display: 'flex', justifyContent: 'start', alignItems: 'center', }} > {label} </Tag> ); }; return ( <Modal title="Add Owners" visible={visible} onCancel={onModalClose} keyboard footer={ <> <Button onClick={onModalClose} type="text"> Cancel </Button> <Button id="addOwnerButton" disabled={selectedOwners.length === 0} onClick={onOk}> Add </Button> </> } > <Form layout="vertical" form={form} colon={false}> <Form.Item key="owners" name="owners" label={<Typography.Text strong>Owner</Typography.Text>}> <Typography.Paragraph>Find a user or group</Typography.Paragraph> <Form.Item name="owner"> <SelectInput labelInValue value={selectedOwners} autoFocus mode="multiple" filterOption={false} placeholder="Search for users or groups..." onSelect={(asset: any) => onSelectOwner(asset)} onDeselect={(asset: any) => onDeselectOwner(asset)} onSearch={handleActorSearch} tagRender={tagRender} > {combinedSearchResults?.map((result) => ( <Select.Option key={result?.entity?.urn} value={result.entity.urn}> {renderSearchResult(result)} </Select.Option> ))} </SelectInput> </Form.Item> </Form.Item> {!hideOwnerType && ( <Form.Item label={<Typography.Text strong>Type</Typography.Text>}> <Typography.Paragraph>Choose an owner type</Typography.Paragraph> <Form.Item name="type"> <Select defaultValue={selectedOwnerType} value={selectedOwnerType} onChange={onSelectOwnerType} > {ownershipTypes.map((ownerType) => ( <Select.Option key={ownerType.type} value={ownerType.type}> <Typography.Text>{ownerType.name}</Typography.Text> <div> <Typography.Paragraph style={{ wordBreak: 'break-all' }} type="secondary"> {ownerType.description} </Typography.Paragraph> </div> </Select.Option> ))} </Select> </Form.Item> </Form.Item> )} </Form> </Modal> ); };
the_stack
import test from 'ava'; import {JacksonError} from '../src/core/JacksonError'; import {JsonIdentityInfo, ObjectIdGenerator} from '../src/decorators/JsonIdentityInfo'; import {JsonManagedReference} from '../src/decorators/JsonManagedReference'; import {JsonBackReference} from '../src/decorators/JsonBackReference'; import {JsonIdentityReference} from '../src/decorators/JsonIdentityReference'; import {JsonClassType} from '../src/decorators/JsonClassType'; import {ObjectMapper} from '../src/databind/ObjectMapper'; import {JsonProperty} from '../src/decorators/JsonProperty'; import {JsonGetter} from '../src/decorators/JsonGetter'; import {JsonSetter} from '../src/decorators/JsonSetter'; test('Fail Infinite recursion', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book', user); const item2 = new Item(2, 'Computer', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const err = t.throws<Error>(() => { objectMapper.stringify<User>(user); }); t.assert(err instanceof Error); }); test('@JsonManagedReference And @JsonBackReference at property level', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) @JsonManagedReference() items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) @JsonBackReference() owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book', user); const item2 = new Item(2, 'Computer', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"id":1,"name":"Book"},{"id":2,"name":"Computer"}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.assert(userParsed.items.length === 2); t.assert(userParsed.items[0] instanceof Item); t.assert(userParsed.items[0].owner === userParsed); t.assert(userParsed.items[1].owner === userParsed); }); test('@JsonManagedReference And @JsonBackReference at method level', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } @JsonGetter() @JsonManagedReference() @JsonClassType({type: () => [Array, [Item]]}) getItems(): Item[] { return this.items; } @JsonSetter() setItems(@JsonClassType({type: () => [Array, [Item]]}) items: Item[]) { this.items = items; } } class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } @JsonGetter() @JsonBackReference() @JsonClassType({type: () => [User]}) getOwner(): User { return this.owner; } @JsonSetter() setOwner(@JsonClassType({type: () => [User]}) owner: User) { this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book', user); const item2 = new Item(2, 'Computer', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"id":1,"name":"Book"},{"id":2,"name":"Computer"}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.assert(userParsed.items.length === 2); t.assert(userParsed.items[0] instanceof Item); t.assert(userParsed.items[0].owner === userParsed); t.assert(userParsed.items[1].owner === userParsed); }); test('Fail @JsonIdentityInfo id already seen without scope', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book', user); const item2 = new Item(2, 'Computer', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"id":1,"name":"Book","owner":1},{"id":2,"name":"Computer","owner":1}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const err = t.throws<JacksonError>(() => { objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); }); t.assert(err instanceof JacksonError); }); test('@JsonIdentityInfo One To Many', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string, @JsonClassType({type: () => [User]}) owner: User) { this.id = id; this.name = name; this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book', user); const item2 = new Item(2, 'Computer', user); user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"id":1,"name":"Book","owner":1},{"id":2,"name":"Computer","owner":1}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.assert(userParsed.items.length === 2); t.assert(userParsed.items[0] instanceof Item); t.assert(userParsed.items[0].owner === userParsed); t.assert(userParsed.items[1].owner === userParsed); }); test('@JsonIdentityInfo One To Many at property level', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) owner: User; constructor(id: number, name: string) { this.id = id; this.name = name; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book'); const item2 = new Item(2, 'Computer'); user.items.push(...[item1, item2]); item1.owner = user; item2.owner = user; const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Item>(item1); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"name":"Book","owner":{"items":[1,{"id":2,"name":"Computer","owner":1}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}')); const itemParsed = objectMapper.parse<Item>(jsonData, {mainCreator: () => [Item]}); t.assert(itemParsed instanceof Item); t.assert(itemParsed.owner instanceof User); t.assert(itemParsed.owner.items.length === 2); t.assert(itemParsed.owner.items[0] instanceof Item); t.assert(itemParsed.owner.items[1] instanceof Item); t.assert(itemParsed.owner.items[0].owner === itemParsed.owner); t.assert(itemParsed.owner.items[1].owner === itemParsed.owner); }); test('@JsonIdentityInfo One To Many at method level', t => { class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string) { this.id = id; this.name = name; } @JsonGetter() @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) @JsonClassType({type: () => [User]}) getOwner(): User { return this.owner; } @JsonSetter() @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) setOwner(@JsonClassType({type: () => [User]}) owner: User) { this.owner = owner; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(1, 'Book'); const item2 = new Item(2, 'Computer'); user.items.push(...[item1, item2]); item1.owner = user; item2.owner = user; const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<Item>(item1); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"name":"Book","owner":{"items":[1,{"id":2,"name":"Computer","owner":1}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}}')); const itemParsed = objectMapper.parse<Item>(jsonData, {mainCreator: () => [Item]}); t.assert(itemParsed instanceof Item); t.assert(itemParsed.owner instanceof User); t.assert(itemParsed.owner.items.length === 2); t.assert(itemParsed.owner.items[0] instanceof Item); t.assert(itemParsed.owner.items[1] instanceof Item); t.assert(itemParsed.owner.items[0].owner === itemParsed.owner); t.assert(itemParsed.owner.items[1].owner === itemParsed.owner); }); test('@JsonIdentityInfo Many To Many', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [Array, [User]]}) owners: User[] = []; constructor(id: number, name: string) { this.id = id; this.name = name; } } const user1 = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const user2 = new User(2, 'alex.beta@gmail.com', 'Alex', 'Beta'); const item1 = new Item(1, 'Book'); const item2 = new Item(2, 'Computer'); user1.items.push(...[item1, item2]); user2.items.push(...[item1]); item1.owners.push(...[user1, user2]); item2.owners.push(...[user1]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user1); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[{"owners":[1,{"items":[1],"id":2,"email":"alex.beta@gmail.com","firstname":"Alex","lastname":"Beta"}],"id":1,"name":"Book"},{"owners":[1],"id":2,"name":"Computer"}],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); const userParsed = objectMapper.parse<User>(jsonData, {mainCreator: () => [User]}); t.assert(userParsed instanceof User); t.assert(userParsed.items.length === 2); t.assert(userParsed.items[0] instanceof Item); t.assert(userParsed.items[0].owners.includes(userParsed)); t.assert(userParsed.items[0].owners.find((owner) => owner.id === user2.id)); }); test('@JsonIdentityInfo One To Many with @JsonIdentityReference', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) @JsonIdentityReference({alwaysAsId: true}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string) { this.id = id; this.name = name; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(2, 'Book'); item1.owner = user; const item2 = new Item(3, 'Computer'); item2.owner = user; user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"items":[2,3],"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa"}')); }); test('@JsonIdentityInfo One To Many with @JsonIdentityReference at property level', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) @JsonIdentityReference({alwaysAsId: true}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string) { this.id = id; this.name = name; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(2, 'Book'); item1.owner = user; const item2 = new Item(3, 'Computer'); item2.owner = user; user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[2,3]}')); }); test('@JsonIdentityInfo One To Many with @JsonIdentityReference at method level', t => { @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'User'}) class User { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) email: string; @JsonProperty() @JsonClassType({type: () => [String]}) firstname: string; @JsonProperty() @JsonClassType({type: () => [String]}) lastname: string; @JsonProperty() @JsonClassType({type: () => [Array, [Item]]}) items: Item[] = []; constructor(id: number, email: string, firstname: string, lastname: string) { this.id = id; this.email = email; this.firstname = firstname; this.lastname = lastname; } @JsonGetter() @JsonClassType({type: () => [Array, [Item]]}) @JsonIdentityReference({alwaysAsId: true}) getItems() { return this.items; } } @JsonIdentityInfo({generator: ObjectIdGenerator.PropertyGenerator, property: 'id', scope: 'Item'}) class Item { @JsonProperty() @JsonClassType({type: () => [Number]}) id: number; @JsonProperty() @JsonClassType({type: () => [String]}) name: string; @JsonProperty() @JsonClassType({type: () => [User]}) owner: User; constructor(id: number, name: string) { this.id = id; this.name = name; } } const user = new User(1, 'john.alfa@gmail.com', 'John', 'Alfa'); const item1 = new Item(2, 'Book'); item1.owner = user; const item2 = new Item(3, 'Computer'); item2.owner = user; user.items.push(...[item1, item2]); const objectMapper = new ObjectMapper(); const jsonData = objectMapper.stringify<User>(user); // eslint-disable-next-line max-len t.deepEqual(JSON.parse(jsonData), JSON.parse('{"id":1,"email":"john.alfa@gmail.com","firstname":"John","lastname":"Alfa","items":[2,3]}')); });
the_stack
export const geo: any = { "湖北": [115.65875349263533, 30.53695878561894], "武汉": [115.65875349263533, 30.53695878561894], "日本": [139.666002, 35.806528], "日本本土": [139.666002, 35.806528], "泰国": [100.486347, 13.756726], "越南": [105.705142, 20.984919], "韩国": [126.954566, 37.604327], "新加坡": [103.864104, 1.356423], "菲律宾": [121.028927, 14.639007], "美国": [-77.044809, 38.92539], "澳大利亚": [149.196095, -35.297238], "哥伦比亚": [-74.077266, 4.713585], "英国": [-0.123734, 51.520443], "意大利": [12.492066, 41.890308], "墨西哥": [-99.14181, 19.433633], "巴西": [-47.884669, -15.789425], "法国": [2.342448, 48.862116], "尼泊尔": [83.962161, 28.233497], "马来西亚": [101.694057, 3.154895], "德国": [13.377271, 52.525661], "芬兰": [24.938224, 60.174998], "加拿大": [-123.148102, 49.301414], "斯里兰卡": [79.925521, 7.001598], "阿联酋": [54.384789, 24.499524], "印度": [77.103978, 28.711647], "俄罗斯": [37.624784, 55.754853], "柬埔寨": [104.893317, 11.559897], "瑞典": [18.088995, 59.331415], "比利时": [4.342511, 50.851975], "罗马尼亚": [26.09219, 44.436037], "格鲁吉亚": [44.83234, 41.712311], "爱沙尼亚": [24.752065, 59.441325], "阿富汗": [69.208133, 34.565176], "荷兰": [4.894574, 52.374505], "北马其顿": [21.421686, 42.004319], "阿尔及利亚": [3.049362, 36.761518], "丹麦": [12.438406, 55.67431], "克罗地亚": [15.967546, 45.816012], "希腊": [23.729501, 37.984104], "奥地利": [16.37037, 48.214517], "黎巴嫩": [35.503502, 33.895949], "伊拉克": [44.358585, 33.322544], "阿曼": [58.410737, 23.594832], "瑞士": [145.803238, -41.192415], "挪威": [10.75167, 59.915741], "以色列": [35.223994, 31.789095], "西班牙": [-3.698616, 40.42095], "巴林": [50.585871, 26.23612], "科威特": [47.980026, 29.37729], "伊朗": [51.388399, 35.69037], }; const cityCenterJson = { municipalities: [{n: "北京", g: "116.395645,39.929986|12"}, {n: "上海", g: "121.487899,31.249162|12"}, { n: "天津", g: "117.210813,39.14393|12" }, {n: "重庆", g: "106.530635,29.544606|12"}], provinces: [{ n: "安徽", g: "117.216005,31.859252|8", cities: [{n: "合肥", g: "117.282699,31.866942|12"}, {n: "安庆", g: "117.058739,30.537898|13"}, { n: "蚌埠", g: "117.35708,32.929499|13" }, {n: "亳州", g: "115.787928,33.871211|13"}, {n: "巢湖", g: "117.88049,31.608733|13"}, { n: "池州", g: "117.494477,30.660019|14" }, {n: "滁州", g: "118.32457,32.317351|13"}, {n: "阜阳", g: "115.820932,32.901211|13"}, { n: "淮北", g: "116.791447,33.960023|13" }, {n: "淮南", g: "117.018639,32.642812|13"}, {n: "黄山", g: "118.29357,29.734435|13"}, { n: "六安", g: "116.505253,31.755558|13" }, {n: "马鞍山", g: "118.515882,31.688528|13"}, {n: "宿州", g: "116.988692,33.636772|13"}, { n: "铜陵", g: "117.819429,30.94093|14" }, {n: "芜湖", g: "118.384108,31.36602|12"}, {n: "宣城", g: "118.752096,30.951642|13"}] }, { n: "福建", g: "117.984943,26.050118|8", cities: [{n: "福州", g: "119.330221,26.047125|12"}, {n: "龙岩", g: "117.017997,25.078685|13"}, { n: "南平", g: "118.181883,26.643626|13" }, {n: "宁德", g: "119.542082,26.656527|14"}, {n: "莆田", g: "119.077731,25.44845|13"}, { n: "泉州", g: "118.600362,24.901652|12" }, {n: "三明", g: "117.642194,26.270835|14"}, {n: "厦门", g: "118.103886,24.489231|12"}, { n: "漳州", g: "117.676205,24.517065|12" }] }, { n: "甘肃", g: "102.457625,38.103267|6", cities: [{n: "兰州", g: "103.823305,36.064226|12"}, {n: "白银", g: "104.171241,36.546682|13"}, { n: "定西", g: "104.626638,35.586056|13" }, {n: "甘南州", g: "102.917442,34.992211|14"}, {n: "嘉峪关", g: "98.281635,39.802397|13"}, { n: "金昌", g: "102.208126,38.516072|13" }, {n: "酒泉", g: "98.508415,39.741474|13"}, {n: "临夏州", g: "103.215249,35.598514|13"}, { n: "陇南", g: "104.934573,33.39448|14" }, {n: "平凉", g: "106.688911,35.55011|13"}, {n: "庆阳", g: "107.644227,35.726801|13"}, { n: "天水", g: "105.736932,34.584319|13" }, {n: "武威", g: "102.640147,37.933172|13"}, {n: "张掖", g: "100.459892,38.93932|13"}] }, { n: "广东", g: "113.394818,23.408004|8", cities: [{n: "广州", g: "113.30765,23.120049|12"}, {n: "潮州", g: "116.630076,23.661812|13"}, { n: "东莞", g: "113.763434,23.043024|12" }, {n: "佛山", g: "113.134026,23.035095|13"}, {n: "河源", g: "114.713721,23.757251|12"}, { n: "惠州", g: "114.410658,23.11354|12" }, {n: "江门", g: "113.078125,22.575117|13"}, {n: "揭阳", g: "116.379501,23.547999|13"}, { n: "茂名", g: "110.931245,21.668226|13" }, {n: "梅州", g: "116.126403,24.304571|13"}, {n: "清远", g: "113.040773,23.698469|13"}, { n: "汕头", g: "116.72865,23.383908|13" }, {n: "汕尾", g: "115.372924,22.778731|14"}, {n: "韶关", g: "113.594461,24.80296|13"}, { n: "深圳", g: "114.025974,22.546054|12" }, {n: "阳江", g: "111.97701,21.871517|14"}, {n: "云浮", g: "112.050946,22.937976|13"}, { n: "湛江", g: "110.365067,21.257463|13" }, {n: "肇庆", g: "112.479653,23.078663|13"}, {n: "中山", g: "113.42206,22.545178|12"}, { n: "珠海", g: "113.562447,22.256915|13" }] }, { n: "广西", g: "108.924274,23.552255|7", cities: [{n: "南宁", g: "108.297234,22.806493|12"}, {n: "百色", g: "106.631821,23.901512|13"}, { n: "北海", g: "109.122628,21.472718|13" }, {n: "崇左", g: "107.357322,22.415455|14"}, {n: "防城港", g: "108.351791,21.617398|15"}, { n: "桂林", g: "110.26092,25.262901|12" }, {n: "贵港", g: "109.613708,23.103373|13"}, {n: "河池", g: "108.069948,24.699521|14"}, { n: "贺州", g: "111.552594,24.411054|14" }, {n: "来宾", g: "109.231817,23.741166|14"}, {n: "柳州", g: "109.422402,24.329053|12"}, { n: "钦州", g: "108.638798,21.97335|13" }, {n: "梧州", g: "111.305472,23.485395|13"}, {n: "玉林", g: "110.151676,22.643974|14"}] }, { n: "贵州", g: "106.734996,26.902826|8", cities: [{n: "贵阳", g: "106.709177,26.629907|12"}, {n: "安顺", g: "105.92827,26.228595|13"}, { n: "毕节地区", g: "105.300492,27.302612|14" }, {n: "六盘水", g: "104.852087,26.591866|13"}, {n: "铜仁地区", g: "109.196161,27.726271|14"}, { n: "遵义", g: "106.93126,27.699961|13" }, {n: "黔西南州", g: "104.900558,25.095148|11"}, {n: "黔东南州", g: "107.985353,26.583992|11"}, { n: "黔南州", g: "107.523205,26.264536|11" }] }, { n: "海南", g: "109.733755,19.180501|9", cities: [{n: "海口", g: "110.330802,20.022071|13"}, {n: "白沙", g: "109.358586,19.216056|12"}, { n: "保亭", g: "109.656113,18.597592|12" }, {n: "昌江", g: "109.0113,19.222483|12"}, {n: "儋州", g: "109.413973,19.571153|13"}, { n: "澄迈", g: "109.996736,19.693135|13" }, {n: "东方", g: "108.85101,18.998161|13"}, {n: "定安", g: "110.32009,19.490991|13"}, { n: "琼海", g: "110.414359,19.21483|13" }, {n: "琼中", g: "109.861849,19.039771|12"}, {n: "乐东", g: "109.062698,18.658614|12"}, { n: "临高", g: "109.724101,19.805922|13" }, {n: "陵水", g: "109.948661,18.575985|12"}, {n: "三亚", g: "109.522771,18.257776|12"}, { n: "屯昌", g: "110.063364,19.347749|13" }, {n: "万宁", g: "110.292505,18.839886|13"}, {n: "文昌", g: "110.780909,19.750947|13"}, { n: "五指山", g: "109.51775,18.831306|13" }] }, { n: "河北", g: "115.661434,38.61384|7", cities: [{n: "石家庄", g: "114.522082,38.048958|12"}, {n: "保定", g: "115.49481,38.886565|13"}, { n: "沧州", g: "116.863806,38.297615|13" }, {n: "承德", g: "117.933822,40.992521|14"}, {n: "邯郸", g: "114.482694,36.609308|13"}, { n: "衡水", g: "115.686229,37.746929|13" }, {n: "廊坊", g: "116.703602,39.518611|13"}, {n: "秦皇岛", g: "119.604368,39.945462|12"}, { n: "唐山", g: "118.183451,39.650531|13" }, {n: "邢台", g: "114.520487,37.069531|13"}, {n: "张家口", g: "114.893782,40.811188|13"}] }, { n: "河南", g: "113.486804,34.157184|7", cities: [{n: "郑州", g: "113.649644,34.75661|12"}, {n: "安阳", g: "114.351807,36.110267|12"}, { n: "鹤壁", g: "114.29777,35.755426|13" }, {n: "焦作", g: "113.211836,35.234608|13"}, {n: "开封", g: "114.351642,34.801854|13"}, { n: "洛阳", g: "112.447525,34.657368|12" }, {n: "漯河", g: "114.046061,33.576279|13"}, {n: "南阳", g: "112.542842,33.01142|13"}, { n: "平顶山", g: "113.300849,33.745301|13" }, {n: "濮阳", g: "115.026627,35.753298|12"}, {n: "三门峡", g: "111.181262,34.78332|13"}, { n: "商丘", g: "115.641886,34.438589|13" }, {n: "新乡", g: "113.91269,35.307258|13"}, {n: "信阳", g: "114.085491,32.128582|13"}, { n: "许昌", g: "113.835312,34.02674|13" }, {n: "周口", g: "114.654102,33.623741|13"}, {n: "驻马店", g: "114.049154,32.983158|13"}] }, { n: "黑龙江", g: "128.047414,47.356592|6", cities: [{n: "哈尔滨", g: "126.657717,45.773225|12"}, {n: "大庆", g: "125.02184,46.596709|12"}, { n: "大兴安岭地区", g: "124.196104,51.991789|10" }, {n: "鹤岗", g: "130.292472,47.338666|13"}, {n: "黑河", g: "127.50083,50.25069|14"}, { n: "鸡西", g: "130.941767,45.32154|13" }, {n: "佳木斯", g: "130.284735,46.81378|12"}, {n: "牡丹江", g: "129.608035,44.588521|13"}, { n: "七台河", g: "131.019048,45.775005|14" }, {n: "齐齐哈尔", g: "123.987289,47.3477|13"}, {n: "双鸭山", g: "131.171402,46.655102|13"}, { n: "绥化", g: "126.989095,46.646064|13" }, {n: "伊春", g: "128.910766,47.734685|14"}] }, { n: "湖北", g: "112.410562,31.209316|8", cities: [{n: "武汉", g: "114.3162,30.581084|12"}, {n: "鄂州", g: "114.895594,30.384439|14"}, { n: "恩施", g: "109.517433,30.308978|14" }, {n: "黄冈", g: "114.906618,30.446109|14"}, {n: "黄石", g: "115.050683,30.216127|13"}, { n: "荆门", g: "112.21733,31.042611|13" }, {n: "荆州", g: "112.241866,30.332591|12"}, {n: "潜江", g: "112.768768,30.343116|13"}, { n: "神农架林区", g: "110.487231,31.595768|13" }, {n: "十堰", g: "110.801229,32.636994|13"}, {n: "随州", g: "113.379358,31.717858|13"}, { n: "天门", g: "113.12623,30.649047|13" }, {n: "仙桃", g: "113.387448,30.293966|13"}, {n: "咸宁", g: "114.300061,29.880657|13"}, { n: "襄阳", g: "112.176326,32.094934|12" }, {n: "孝感", g: "113.935734,30.927955|13"}, {n: "宜昌", g: "111.310981,30.732758|13"}] }, { n: "湖南", g: "111.720664,27.695864|7", cities: [{n: "长沙", g: "112.979353,28.213478|12"}, {n: "常德", g: "111.653718,29.012149|12"}, { n: "郴州", g: "113.037704,25.782264|13" }, {n: "衡阳", g: "112.583819,26.898164|13"}, {n: "怀化", g: "109.986959,27.557483|13"}, { n: "娄底", g: "111.996396,27.741073|13" }, {n: "邵阳", g: "111.461525,27.236811|13"}, {n: "湘潭", g: "112.935556,27.835095|13"}, { n: "湘西州", g: "109.745746,28.317951|14" }, {n: "益阳", g: "112.366547,28.588088|13"}, {n: "永州", g: "111.614648,26.435972|13"}, { n: "岳阳", g: "113.146196,29.378007|13" }, {n: "张家界", g: "110.48162,29.124889|13"}, {n: "株洲", g: "113.131695,27.827433|13"}] }, { n: "江苏", g: "119.368489,33.013797|8", cities: [{n: "南京", g: "118.778074,32.057236|12"}, {n: "常州", g: "119.981861,31.771397|12"}, { n: "淮安", g: "119.030186,33.606513|12" }, {n: "连云港", g: "119.173872,34.601549|12"}, {n: "南通", g: "120.873801,32.014665|12"}, { n: "苏州", g: "120.619907,31.317987|12" }, {n: "宿迁", g: "118.296893,33.95205|13"}, {n: "泰州", g: "119.919606,32.476053|13"}, { n: "无锡", g: "120.305456,31.570037|12" }, {n: "徐州", g: "117.188107,34.271553|12"}, {n: "盐城", g: "120.148872,33.379862|12"}, { n: "扬州", g: "119.427778,32.408505|13" }, {n: "镇江", g: "119.455835,32.204409|13"}] }, { n: "江西", g: "115.676082,27.757258|7", cities: [{n: "南昌", g: "115.893528,28.689578|12"}, {n: "抚州", g: "116.360919,27.954545|13"}, { n: "赣州", g: "114.935909,25.845296|13" }, {n: "吉安", g: "114.992039,27.113848|13"}, {n: "景德镇", g: "117.186523,29.303563|12"}, { n: "九江", g: "115.999848,29.71964|13" }, {n: "萍乡", g: "113.859917,27.639544|13"}, {n: "上饶", g: "117.955464,28.457623|13"}, { n: "新余", g: "114.947117,27.822322|13" }, {n: "宜春", g: "114.400039,27.81113|13"}, {n: "鹰潭", g: "117.03545,28.24131|13"}] }, { n: "吉林", g: "126.262876,43.678846|7", cities: [{n: "长春", g: "125.313642,43.898338|12"}, {n: "白城", g: "122.840777,45.621086|13"}, { n: "白山", g: "126.435798,41.945859|13" }, {n: "吉林", g: "126.564544,43.871988|12"}, {n: "辽源", g: "125.133686,42.923303|13"}, { n: "四平", g: "124.391382,43.175525|12" }, {n: "松原", g: "124.832995,45.136049|13"}, {n: "通化", g: "125.94265,41.736397|13"}, { n: "延边", g: "129.485902,42.896414|13" }] }, { n: "辽宁", g: "122.753592,41.6216|8", cities: [{n: "沈阳", g: "123.432791,41.808645|12"}, {n: "鞍山", g: "123.007763,41.118744|13"}, { n: "本溪", g: "123.778062,41.325838|12" }, {n: "朝阳", g: "120.446163,41.571828|13"}, {n: "大连", g: "121.593478,38.94871|12"}, { n: "丹东", g: "124.338543,40.129023|12" }, {n: "抚顺", g: "123.92982,41.877304|12"}, {n: "阜新", g: "121.660822,42.01925|14"}, { n: "葫芦岛", g: "120.860758,40.74303|13" }, {n: "锦州", g: "121.147749,41.130879|13"}, {n: "辽阳", g: "123.172451,41.273339|14"}, { n: "盘锦", g: "122.073228,41.141248|13" }, {n: "铁岭", g: "123.85485,42.299757|13"}, {n: "营口", g: "122.233391,40.668651|13"}] }, { n: "内蒙古", g: "114.415868,43.468238|5", cities: [{n: "呼和浩特", g: "111.660351,40.828319|12"}, {n: "阿拉善盟", g: "105.695683,38.843075|14"}, { n: "包头", g: "109.846239,40.647119|12" }, {n: "巴彦淖尔", g: "107.423807,40.76918|12"}, {n: "赤峰", g: "118.930761,42.297112|12"}, { n: "鄂尔多斯", g: "109.993706,39.81649|12" }, {n: "呼伦贝尔", g: "119.760822,49.201636|12"}, {n: "通辽", g: "122.260363,43.633756|12"}, { n: "乌海", g: "106.831999,39.683177|13" }, {n: "乌兰察布", g: "113.112846,41.022363|12"}, {n: "锡林郭勒盟", g: "116.02734,43.939705|11"}, { n: "兴安盟", g: "122.048167,46.083757|11" }] }, { n: "宁夏", g: "106.155481,37.321323|8", cities: [{n: "银川", g: "106.206479,38.502621|12"}, {n: "固原", g: "106.285268,36.021523|13"}, { n: "石嘴山", g: "106.379337,39.020223|13" }, {n: "吴忠", g: "106.208254,37.993561|14"}, {n: "中卫", g: "105.196754,37.521124|14"}] }, { n: "青海", g: "96.202544,35.499761|7", cities: [{n: "西宁", g: "101.767921,36.640739|12"}, {n: "果洛州", g: "100.223723,34.480485|11"}, { n: "海东地区", g: "102.085207,36.51761|11" }, {n: "海北州", g: "100.879802,36.960654|11"}, {n: "海南州", g: "100.624066,36.284364|11"}, { n: "海西州", g: "97.342625,37.373799|11" }, {n: "黄南州", g: "102.0076,35.522852|11"}, {n: "玉树州", g: "97.013316,33.00624|14"}] }, { n: "山东", g: "118.527663,36.09929|8", cities: [{n: "济南", g: "117.024967,36.682785|12"}, {n: "滨州", g: "117.968292,37.405314|12"}, { n: "东营", g: "118.583926,37.487121|12" }, {n: "德州", g: "116.328161,37.460826|12"}, {n: "菏泽", g: "115.46336,35.26244|13"}, { n: "济宁", g: "116.600798,35.402122|13" }, {n: "莱芜", g: "117.684667,36.233654|13"}, {n: "聊城", g: "115.986869,36.455829|12"}, { n: "临沂", g: "118.340768,35.072409|12" }, {n: "青岛", g: "120.384428,36.105215|12"}, {n: "日照", g: "119.50718,35.420225|12"}, { n: "泰安", g: "117.089415,36.188078|13" }, {n: "威海", g: "122.093958,37.528787|13"}, {n: "潍坊", g: "119.142634,36.716115|12"}, { n: "烟台", g: "121.309555,37.536562|12" }, {n: "枣庄", g: "117.279305,34.807883|13"}, {n: "淄博", g: "118.059134,36.804685|12"}] }, { n: "山西", g: "112.515496,37.866566|7", cities: [{n: "太原", g: "112.550864,37.890277|12"}, {n: "长治", g: "113.120292,36.201664|12"}, { n: "大同", g: "113.290509,40.113744|12" }, {n: "晋城", g: "112.867333,35.499834|13"}, {n: "晋中", g: "112.738514,37.693362|13"}, { n: "临汾", g: "111.538788,36.099745|13" }, {n: "吕梁", g: "111.143157,37.527316|14"}, {n: "朔州", g: "112.479928,39.337672|13"}, { n: "忻州", g: "112.727939,38.461031|12" }, {n: "阳泉", g: "113.569238,37.869529|13"}, {n: "运城", g: "111.006854,35.038859|13"}] }, { n: "陕西", g: "109.503789,35.860026|7", cities: [{n: "西安", g: "108.953098,34.2778|12"}, {n: "安康", g: "109.038045,32.70437|13"}, { n: "宝鸡", g: "107.170645,34.364081|12" }, {n: "汉中", g: "107.045478,33.081569|13"}, {n: "商洛", g: "109.934208,33.873907|13"}, { n: "铜川", g: "108.968067,34.908368|13" }, {n: "渭南", g: "109.483933,34.502358|13"}, {n: "咸阳", g: "108.707509,34.345373|13"}, { n: "延安", g: "109.50051,36.60332|13" }, {n: "榆林", g: "109.745926,38.279439|12"}] }, { n: "四川", g: "102.89916,30.367481|7", cities: [{n: "成都", g: "104.067923,30.679943|12"}, {n: "阿坝州", g: "102.228565,31.905763|15"}, { n: "巴中", g: "106.757916,31.869189|14" }, {n: "达州", g: "107.494973,31.214199|14"}, {n: "德阳", g: "104.402398,31.13114|13"}, { n: "甘孜州", g: "101.969232,30.055144|15" }, {n: "广安", g: "106.63572,30.463984|13"}, {n: "广元", g: "105.819687,32.44104|13"}, { n: "乐山", g: "103.760824,29.600958|13" }, {n: "凉山州", g: "102.259591,27.892393|14"}, {n: "泸州", g: "105.44397,28.89593|14"}, { n: "南充", g: "106.105554,30.800965|13" }, {n: "眉山", g: "103.84143,30.061115|13"}, {n: "绵阳", g: "104.705519,31.504701|12"}, { n: "内江", g: "105.073056,29.599462|13" }, {n: "攀枝花", g: "101.722423,26.587571|14"}, {n: "遂宁", g: "105.564888,30.557491|12"}, { n: "雅安", g: "103.009356,29.999716|13" }, {n: "宜宾", g: "104.633019,28.769675|13"}, {n: "资阳", g: "104.63593,30.132191|13"}, { n: "自贡", g: "104.776071,29.359157|13" }] }, { n: "西藏", g: "89.137982,31.367315|6", cities: [{n: "拉萨", g: "91.111891,29.662557|13"}, {n: "阿里地区", g: "81.107669,30.404557|11"}, { n: "昌都地区", g: "97.185582,31.140576|15" }, {n: "林芝地区", g: "94.349985,29.666941|11"}, {n: "那曲地区", g: "92.067018,31.48068|14"}, { n: "日喀则地区", g: "88.891486,29.269023|14" }, {n: "山南地区", g: "91.750644,29.229027|11"}] }, { n: "新疆", g: "85.614899,42.127001|6", cities: [{n: "乌鲁木齐", g: "87.564988,43.84038|12"}, {n: "阿拉尔", g: "81.291737,40.61568|13"}, { n: "阿克苏地区", g: "80.269846,41.171731|12" }, {n: "阿勒泰地区", g: "88.137915,47.839744|13"}, {n: "巴音郭楞", g: "86.121688,41.771362|12"}, { n: "博尔塔拉州", g: "82.052436,44.913651|11" }, {n: "昌吉州", g: "87.296038,44.007058|13"}, {n: "哈密地区", g: "93.528355,42.858596|13"}, { n: "和田地区", g: "79.930239,37.116774|13" }, {n: "喀什地区", g: "75.992973,39.470627|12"}, {n: "克拉玛依", g: "84.88118,45.594331|13"}, { n: "克孜勒苏州", g: "76.137564,39.750346|11" }, {n: "石河子", g: "86.041865,44.308259|13"}, {n: "塔城地区", g: "82.974881,46.758684|12"}, { n: "图木舒克", g: "79.198155,39.889223|13" }, {n: "吐鲁番地区", g: "89.181595,42.96047|13"}, {n: "五家渠", g: "87.565449,44.368899|13"}, { n: "伊犁州", g: "81.297854,43.922248|11" }] }, { n: "云南", g: "101.592952,24.864213|7", cities: [{n: "昆明", g: "102.714601,25.049153|12"}, {n: "保山", g: "99.177996,25.120489|13"}, { n: "楚雄州", g: "101.529382,25.066356|13" }, {n: "大理州", g: "100.223675,25.5969|14"}, {n: "德宏州", g: "98.589434,24.44124|14"}, { n: "迪庆州", g: "99.713682,27.831029|14" }, {n: "红河州", g: "103.384065,23.367718|11"}, {n: "丽江", g: "100.229628,26.875351|13"}, { n: "临沧", g: "100.092613,23.887806|14" }, {n: "怒江州", g: "98.859932,25.860677|14"}, {n: "普洱", g: "100.980058,22.788778|14"}, { n: "曲靖", g: "103.782539,25.520758|12" }, {n: "昭通", g: "103.725021,27.340633|13"}, {n: "文山", g: "104.089112,23.401781|14"}, { n: "西双版纳", g: "100.803038,22.009433|13" }, {n: "玉溪", g: "102.545068,24.370447|13"}] }, { n: "浙江", g: "119.957202,29.159494|8", cities: [{n: "杭州", g: "120.219375,30.259244|12"}, {n: "湖州", g: "120.137243,30.877925|12"}, { n: "嘉兴", g: "120.760428,30.773992|13" }, {n: "金华", g: "119.652576,29.102899|12"}, {n: "丽水", g: "119.929576,28.4563|13"}, { n: "宁波", g: "121.579006,29.885259|12" }, {n: "衢州", g: "118.875842,28.95691|12"}, {n: "绍兴", g: "120.592467,30.002365|13"}, { n: "台州", g: "121.440613,28.668283|13" }, {n: "温州", g: "120.690635,28.002838|12"}, {n: "舟山", g: "122.169872,30.03601|13"}] }], other: [{n: "香港", g: "114.186124,22.293586|11"}, {n: "澳门", g: "113.557519,22.204118|13"}, { n: "台湾", g: "120.961454,23.80406|8" }] }; function a(t: string) { const e: any[] = t.split("|"); e[0] = e[0].split(","); return {lng: parseFloat(e[0][0]), lat: parseFloat(e[0][1])}; } /** * @desc 返回城市坐标 * */ export const getCenterByCityName = (t: string) => { t = t.replace("市", ""); for (let e = 0; e < cityCenterJson.municipalities.length; e++) if (cityCenterJson.municipalities[e].n === t) return a(cityCenterJson.municipalities[e].g); for (let e = 0; e < cityCenterJson.other.length; e++) if (cityCenterJson.other[e].n === t) return a(cityCenterJson.other[e].g); const n = cityCenterJson.provinces; for (let e = 0; e < n.length; e++) { if (n[e].n === t) return a(n[e].g); for (let i = n[e].cities, o = 0; o < i.length; o++) if (i[o].n === t) return a(i[o].g); } return null; };
the_stack
import { TimeEntity } from '../../utils/entity-utils'; import BaseTokenizer from './base'; import { makeToken } from './helpers'; // 我觉得这比英语好太多了 const NUMBERS : Record<string, number> = { 〇: 0, 零: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, }; const SMALL_MULTIPLIERS : Record<string, number> = { 十: 10, 百: 100, 千: 1000, }; const BIG_MULTIPLIERS : Record<string, number> = { 万: 1e4, 亿: 1e8, 兆: 1e12 }; const CURRENCIES : Record<string, string> = { '美元': 'usd', '美金': 'usd', '刀': 'usd', '加元': 'cad', '澳元': 'aud', '英镑': 'gbp', '日圆': 'jpy', '日元': 'jpy', '欧元': 'eur', '欧': 'eur', '元': 'cny', '块': 'cny', '$': 'usd', '£': 'gbp', '€': 'eur', '₩': 'krw', '¥': 'cny', }; export default class ChineseTokenizer extends BaseTokenizer { protected _addIntlPrefix(text : string) { // assume PRC if (!text.startsWith('+')) text = '+86' + text; return text; } private _parseWordNumber(text : string) { // numbers in chinese have three levels // individual digits: 一 to 九 // small multipliers: 十,白,千 // big multipliers: 万,亿,兆 // the logic is similar to other languages: you operate a buffer and multiply and add // there is one twist: the final multiplier might be omitted // to distinguish that case, we need to pay attention to the character "零" // if present, the multiplier is reset to 1 and the last digit will be a unit // if absent, the last digit is the previous multiplier divided by 10 // "value" is the total number, "current_small" is the value before a small multiplier, "current_big" is the value before a big multiplier let value = 0; let current_small = 0; let current_big = 0; let lastMultiplier = 1; // example: 三十一万五千 (315000) // 三: value = 0, current_small = 3, current_big = 0 // 十: value = 0, current_small = 0, current_big = 30 // 一: value = 0, current_small = 1, current_big = 30 // 万: value = 310000, current_small = 0, current_big = 0 // 五: value = 310000, current_small = 5, current_big = 0 // 千: value = 310000, current_small = 0, current_big = 5000 // final value 315000 // parse character by character for (let i = 0; i < text.length; i++) { const char = text[i]; if (char === '零') { // reset the multiplier lastMultiplier = 1; } else if (char in BIG_MULTIPLIERS) { const multiplier = BIG_MULTIPLIERS[char]; current_big += current_small; if (current_big === 0) current_big = 1; value += current_big * multiplier; current_big = 0; current_small = 0; lastMultiplier = multiplier/10; } else if (char in SMALL_MULTIPLIERS) { const multiplier = SMALL_MULTIPLIERS[char]; if (current_small === 0) current_small = 1; current_big += current_small * multiplier; current_small = 0; lastMultiplier = multiplier/10; } else if (char in NUMBERS) { current_small += NUMBERS[char]; } } current_big += current_small * lastMultiplier; value += current_big; return value; } protected _initNumbers() { // numbers in digits // can be separated by space or comma this._addDefinition('DIGITS', /[0-9]+(?:(?:{WS}|,)[0-9]+)*/); this._addDefinition('DECIMAL_NUMBER', /\.{DIGITS}|{DIGITS}(?:\.{DIGITS})?/); this._lexer.addRule(/[+-]?{DECIMAL_NUMBER}/, (lexer) => { const value = this._parseDecimalNumber(lexer.text); return makeToken(lexer.index, lexer.text, String(value)); }); // currencies this._lexer.addRule(/{DECIMAL_NUMBER}(?:[美加澳欧]?元|欧|英镑|日圆|日元|块|美金|刀)/, (lexer) => { const unitlength = /[美加澳欧]元|英镑|日[圆元]|美金/.test(lexer.text) ? 2 : 1; const num = lexer.text.substring(0, lexer.text.length-unitlength); const unit = CURRENCIES[lexer.text.substring(lexer.text.length-unitlength)]; const value = this._parseDecimalNumber(num); return makeToken(lexer.index, lexer.text, String(value) + unit, 'CURRENCY', { value, unit }); }); this._lexer.addRule(/{DECIMAL_NUMBER}[a-z]{3}/, (lexer) => { const unitlength = 3; const num = lexer.text.substring(0, lexer.text.length-unitlength); const unit = lexer.text.substring(lexer.text.length-unitlength); const value = this._parseDecimalNumber(num); return makeToken(lexer.index, lexer.text, String(value) + unit, 'CURRENCY', { value, unit }); }); this._lexer.addRule(/(?:[$£€₩¥]){DECIMAL_NUMBER}/, (lexer) => { let unit = lexer.text.match(/[$£€₩¥]/)![0]; unit = CURRENCIES[unit]; const num = lexer.text.replace(/[$£€₩¥]/, ''); const value = this._parseDecimalNumber(num); return makeToken(lexer.index, lexer.text, String(value) + unit, 'CURRENCY', { value, unit }); }); // numbers in words // - "零" (0) can appear pretty much anywhere in a compound number and has no effect (it is ignored on its own) // - "一" (1) is not touched when alone // - small numbers (2 to 12) are normalized to digits // - other numbers are converted to NUMBER tokens // note: trailing multipliers can be omitted, that is, // "二千二" means the same as "二千二百" (2200) rather than "二千零二" (2002) // while extracting, we ignore this, and allow "零" to be interspersed freely // we handle this case when converting the string to JS number // 2 to 9 this._addDefinition('ONE_DIGIT_NUMBER', /[二三四五六七八九]/); // 2 to 12 this._addDefinition('SMALL_NUMBER', /一?十[一二]|{ONE_DIGIT_NUMBER}/); this._lexer.addRule(/{SMALL_NUMBER}/, (lexer) => { const value = this._parseWordNumber(lexer.text); return makeToken(lexer.index, lexer.text, String(value)); }); // 13 to 99 this._addDefinition('MEDIUM_NUMBER', /[二三四五六七八九]十[一二三四五六七八九]?|一?十[三四五六七八九]/); // 1 to 99, as used by large and huge numbers this._addDefinition('LARGE_NUMBER_TRAIL', /{MEDIUM_NUMBER}|{SMALL_NUMBER}|一/); // 100 to 9999 this._addDefinition('LARGE_NUMBER', /(?:[一二三四五六七八九]千零?([一二三四五六七八九]百零?)?|[一二三四五六七八九]?百零?){LARGE_NUMBER_TRAIL}?/); // 10000 and above this._addDefinition('HUGE_NUMBER', /(?:(?:{LARGE_NUMBER}|{MEDIUM_NUMBER}|{SMALL_NUMBER}|一)[万亿兆]零?)+(?:{LARGE_NUMBER}|{MEDIUM_NUMBER}|{SMALL_NUMBER}|一)?/); // medium, large and huge numbers are normalized this._lexer.addRule(/{HUGE_NUMBER}|{LARGE_NUMBER}|{MEDIUM_NUMBER}/, (lexer) => { const value = this._parseWordNumber(lexer.text); return makeToken(lexer.index, lexer.text, String(value)); }); } protected _initOrdinals() { // ordinals are just 第 followed by a number in digit or a number in words // we don't need to do anything special for them } private _findAndParseNumberOffset(letterRegex : RegExp, numberRegex : RegExp, string : string, _default : number) { let match = letterRegex.exec(string); if (match) { return this._parseWordNumber(match[1]); } else { match = numberRegex.exec(string); if (match) return parseInt(match[1]); else return _default; } } private _parseColloquialTime(timestr : string) { let hour, minute; hour = this._findAndParseNumberOffset(/(一?十[一二]|[一二三四五六七八九])点/, /(1[0-2]|[1-9])点/, timestr, 0); const second = this._findAndParseNumberOffset(/([一二三四五六七八九]?十[一二三四五六七八九]?|[一二三四五六七八九])秒/, /([1-5][0-9]|0?[1-9])秒/, timestr, 0); if (timestr.indexOf('钟') >= 0) { minute = 0; } else if (timestr.indexOf('半') >= 0) { minute = 30; } else { const minutematch = /([一三])刻/.exec(timestr); if (minutematch) minute = 15 * this._parseWordNumber(minutematch[1]); else minute = this._findAndParseNumberOffset(/([一二三四五六七八九]?十[一二三四五六七八九]?|[一二三四五六七八九])分/, /([1-5][0-9]|0?[1-9])分/, timestr, 0); if (timestr.indexOf('差') >= 0) { hour -= 1; hour %= 24; minute = 60 - minute; } } return { hour, minute, second }; } protected _initTimes() { // chain up to load ISO time parsing super._initTimes(); // times in words this._addDefinition('MINUTE_OR_SECOND', /[1-5][0-9]|0?[1-9]|[二三四五]?十[一二三四五六七八九]?|[一二三四五六七八九]/); this._addDefinition('NEGATIVE_TIME_OFFSET', /差(?:[一二]刻|{MINUTE_OR_SECOND}分)/); this._addDefinition('COLLOQUIAL_HOUR', /(?:一|{SMALL_NUMBER}|1[0-2]|0?[1-9])点/); this._addDefinition('COLLOQUIAL_TIME', /{NEGATIVE_TIME_OFFSET}{COLLOQUIAL_HOUR}|{COLLOQUIAL_HOUR}{NEGATIVE_TIME_OFFSET}|{COLLOQUIAL_HOUR}(?:[一三]刻|{MINUTE_OR_SECOND}分)(?:{MINUTE_OR_SECOND}秒)?|{COLLOQUIAL_HOUR}[半钟]?/); this._lexer.addRule(/{COLLOQUIAL_TIME}/, (lexer) => { const parsed = this._parseColloquialTime(lexer.text); return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed); }); } private _parseWordDate(text : string, parseTime : ((time : string) => TimeEntity)|null) { const day = this._findAndParseNumberOffset(/(三十一?|[一二]十[一二三四五六七八九]?|[一二三四五六七八九])[号日]/, /(3[01]|[12][0-9]|[1-9])[号日]/, text, -1); const month = this._findAndParseNumberOffset(/(一?十[一二]|[一二三四五六七八九])月/, /(1[0-2]|[1-9])月/, text, -1); // the year is special, the digits are read in sequence without any multiplier let year = -1; const yearmatch = /([〇一二三四五六七八九0-9]{4})年/.exec(text); if (yearmatch) year = parseInt(yearmatch[1].replace(/[〇一二三四五六七八九]/g, (char) => String(NUMBERS[char]))); if (parseTime) { // if we have a time, pick the remaining of the string and parse it const weekstr = /星期|周|礼拜/.exec(text); let dateend; if (weekstr) { // skip the week string and the day number after it dateend = weekstr.index + weekstr[0].length + 1; } else { const daystr = /[号日]/.exec(text); if (daystr) dateend = daystr.index + 1; else dateend = text.indexOf('月') + 1; } const time = parseTime(text.substring(dateend)); return { year, month, day, hour: time.hour, minute: time.minute, second: time.second, timezone: undefined }; } else { return { year, month, day, hour: 0, minute: 0, second: 0, timezone: undefined }; } } protected _initDates() { // init ISO date recognition super._initDates(); this._addDefinition('DAY_NAME', /(星期|周|礼拜)[一二三四五六日天]/); this._addDefinition('DAY', /(?:三十一?|[一二]十[一二三四五六七八九]?|[一二三四五六七八九]|3[01]|[12][0-9]|[1-9])[号日]/); this._addDefinition('MONTH', /(?:一?十[一二]|[一二三四五六七八九]|1[0-2]|[1-9])月/); this._addDefinition('YEAR', /[〇一二三四五六七八九0-9]{4}年/); // dates with words this._lexer.addRule(/(?:{YEAR}?{MONTH}{DAY}|{YEAR}{MONTH})(?:[,,]?{DAY_NAME})?/, (lexer) => { const parsed = this._parseWordDate(lexer.text, null); const normalized = this._normalizeDate(parsed); return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed); }); // date and time this._lexer.addRule(/(?:{YEAR}?{MONTH}{DAY}|{YEAR}{MONTH})(?:[,,]?{DAY_NAME})?在?{PLAIN_TIME}/, (lexer) => { const parsed = this._parseWordDate(lexer.text, (text) => this._parse12HrTime(text, '24h')); const normalized = this._normalizeDate(parsed); return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed); }); // date and time (colloquial) this._lexer.addRule(/(?:{YEAR}?{MONTH}{DAY}|{YEAR}{MONTH})(?:[,,]?{DAY_NAME})?在?{COLLOQUIAL_TIME}/, (lexer) => { const parsed = this._parseWordDate(lexer.text, (text) => this._parseColloquialTime(text)); const normalized = this._normalizeDate(parsed); return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed); }); } }
the_stack
import EventEmitter from "events"; import type { DeviceModel } from "@ledgerhq/devices"; import { TransportRaceCondition, TransportError, StatusCodes, getAltStatusMessage, TransportStatusError, } from "@ledgerhq/errors"; export { TransportError, TransportStatusError, StatusCodes, getAltStatusMessage, }; /** */ export type Subscription = { unsubscribe: () => void; }; /** */ export type Device = any; // Should be a union type of all possible Device object's shape /** * type: add or remove event * descriptor: a parameter that can be passed to open(descriptor) * deviceModel: device info on the model (is it a nano s, nano x, ...) * device: transport specific device info */ export interface DescriptorEvent<Descriptor> { type: "add" | "remove"; descriptor: Descriptor; deviceModel?: DeviceModel | null | undefined; device?: Device; } /** */ export type Observer<Ev> = Readonly<{ next: (event: Ev) => unknown; error: (e: any) => unknown; complete: () => unknown; }>; /** * Transport defines the generic interface to share between node/u2f impl * A **Descriptor** is a parametric type that is up to be determined for the implementation. * it can be for instance an ID, an file path, a URL,... */ export default class Transport { exchangeTimeout = 30000; unresponsiveTimeout = 15000; deviceModel: DeviceModel | null | undefined = null; /** * Statically check if a transport is supported on the user's platform/browser. */ static readonly isSupported: () => Promise<boolean>; /** * List once all available descriptors. For a better granularity, checkout `listen()`. * @return a promise of descriptors * @example * TransportFoo.list().then(descriptors => ...) */ static readonly list: () => Promise<Array<any>>; /** * Listen all device events for a given Transport. The method takes an Obverver of DescriptorEvent and returns a Subscription (according to Observable paradigm https://github.com/tc39/proposal-observable ) * a DescriptorEvent is a `{ descriptor, type }` object. type can be `"add"` or `"remove"` and descriptor is a value you can pass to `open(descriptor)`. * each listen() call will first emit all potential device already connected and then will emit events can come over times, * for instance if you plug a USB device after listen() or a bluetooth device become discoverable. * @param observer is an object with a next, error and complete function (compatible with observer pattern) * @return a Subscription object on which you can `.unsubscribe()` to stop listening descriptors. * @example const sub = TransportFoo.listen({ next: e => { if (e.type==="add") { sub.unsubscribe(); const transport = await TransportFoo.open(e.descriptor); ... } }, error: error => {}, complete: () => {} }) */ static readonly listen: ( observer: Observer<DescriptorEvent<any>> ) => Subscription; /** * attempt to create a Transport instance with potentially a descriptor. * @param descriptor: the descriptor to open the transport with. * @param timeout: an optional timeout * @return a Promise of Transport instance * @example TransportFoo.open(descriptor).then(transport => ...) */ static readonly open: ( descriptor?: any, timeout?: number ) => Promise<Transport>; /** * low level api to communicate with the device * This method is for implementations to implement but should not be directly called. * Instead, the recommanded way is to use send() method * @param apdu the data to send * @return a Promise of response data */ exchange(_apdu: Buffer): Promise<Buffer> { throw new Error("exchange not implemented"); } /** * set the "scramble key" for the next exchanges with the device. * Each App can have a different scramble key and they internally will set it at instanciation. * @param key the scramble key */ setScrambleKey(_key: string) {} /** * close the exchange with the device. * @return a Promise that ends when the transport is closed. */ close(): Promise<void> { return Promise.resolve(); } _events = new EventEmitter(); /** * Listen to an event on an instance of transport. * Transport implementation can have specific events. Here is the common events: * * `"disconnect"` : triggered if Transport is disconnected */ on(eventName: string, cb: (...args: Array<any>) => any): void { this._events.on(eventName, cb); } /** * Stop listening to an event on an instance of transport. */ off(eventName: string, cb: (...args: Array<any>) => any): void { this._events.removeListener(eventName, cb); } emit(event: string, ...args: any): void { this._events.emit(event, ...args); } /** * Enable or not logs of the binary exchange */ setDebugMode() { console.warn( "setDebugMode is deprecated. use @ledgerhq/logs instead. No logs are emitted in this anymore." ); } /** * Set a timeout (in milliseconds) for the exchange call. Only some transport might implement it. (e.g. U2F) */ setExchangeTimeout(exchangeTimeout: number): void { this.exchangeTimeout = exchangeTimeout; } /** * Define the delay before emitting "unresponsive" on an exchange that does not respond */ setExchangeUnresponsiveTimeout(unresponsiveTimeout: number): void { this.unresponsiveTimeout = unresponsiveTimeout; } /** * wrapper on top of exchange to simplify work of the implementation. * @param cla * @param ins * @param p1 * @param p2 * @param data * @param statusList is a list of accepted status code (shorts). [0x9000] by default * @return a Promise of response buffer */ send = async ( cla: number, ins: number, p1: number, p2: number, data: Buffer = Buffer.alloc(0), statusList: Array<number> = [StatusCodes.OK] ): Promise<Buffer> => { if (data.length >= 256) { throw new TransportError( "data.length exceed 256 bytes limit. Got: " + data.length, "DataLengthTooBig" ); } const response = await this.exchange( Buffer.concat([ Buffer.from([cla, ins, p1, p2]), Buffer.from([data.length]), data, ]) ); const sw = response.readUInt16BE(response.length - 2); if (!statusList.some((s) => s === sw)) { throw new TransportStatusError(sw); } return response; }; /** * create() allows to open the first descriptor available or * throw if there is none or if timeout is reached. * This is a light helper, alternative to using listen() and open() (that you may need for any more advanced usecase) * @example TransportFoo.create().then(transport => ...) */ static create( openTimeout = 3000, listenTimeout?: number ): Promise<Transport> { return new Promise((resolve, reject) => { let found = false; const sub = this.listen({ next: (e) => { found = true; if (sub) sub.unsubscribe(); if (listenTimeoutId) clearTimeout(listenTimeoutId); this.open(e.descriptor, openTimeout).then(resolve, reject); }, error: (e) => { if (listenTimeoutId) clearTimeout(listenTimeoutId); reject(e); }, complete: () => { if (listenTimeoutId) clearTimeout(listenTimeoutId); if (!found) { reject( new TransportError( this.ErrorMessage_NoDeviceFound, "NoDeviceFound" ) ); } }, }); const listenTimeoutId = listenTimeout ? setTimeout(() => { sub.unsubscribe(); reject( new TransportError( this.ErrorMessage_ListenTimeout, "ListenTimeout" ) ); }, listenTimeout) : null; }); } exchangeBusyPromise: Promise<void> | null | undefined; exchangeAtomicImpl = async ( f: () => Promise<Buffer | void> ): Promise<Buffer | void> => { if (this.exchangeBusyPromise) { throw new TransportRaceCondition( "An action was already pending on the Ledger device. Please deny or reconnect." ); } let resolveBusy; const busyPromise: Promise<void> = new Promise((r) => { resolveBusy = r; }); this.exchangeBusyPromise = busyPromise; let unresponsiveReached = false; const timeout = setTimeout(() => { unresponsiveReached = true; this.emit("unresponsive"); }, this.unresponsiveTimeout); try { const res = await f(); if (unresponsiveReached) { this.emit("responsive"); } return res; } finally { clearTimeout(timeout); if (resolveBusy) resolveBusy(); this.exchangeBusyPromise = null; } }; decorateAppAPIMethods( self: Record<string, any>, methods: Array<string>, scrambleKey: string ) { for (const methodName of methods) { self[methodName] = this.decorateAppAPIMethod( methodName, self[methodName], self, scrambleKey ); } } _appAPIlock: string | null = null; decorateAppAPIMethod<R, A extends any[]>( methodName: string, f: (...args: A) => Promise<R>, ctx: any, scrambleKey: string ): (...args: A) => Promise<R> { return async (...args) => { const { _appAPIlock } = this; if (_appAPIlock) { return Promise.reject( new TransportError( "Ledger Device is busy (lock " + _appAPIlock + ")", "TransportLocked" ) ); } try { this._appAPIlock = methodName; this.setScrambleKey(scrambleKey); return await f.apply(ctx, args); } finally { this._appAPIlock = null; } }; } static ErrorMessage_ListenTimeout = "No Ledger device found (timeout)"; static ErrorMessage_NoDeviceFound = "No Ledger device found"; }
the_stack
namespace pxt.esp { export interface Segment { addr: number isMapped: boolean isDROM: boolean data: Uint8Array } export interface Image { header: Uint8Array chipName: string segments: Segment[] } const r32 = pxt.HF2.read32 const r16 = pxt.HF2.read16 /* layout: u8 magic 0xE9 u8 numsegs u8 flash_mode u8 flash_size_freq u32 entrypoint // 4 u8 wp_pin // 8 u8 clk/q drv // 9 u8 d/cs drv // 10 u8 hd/wp drv // 11 u16 chip_id // 12 */ interface MemSegment { from: number to: number id: string } interface ChipDesc { name: string chipId: number memmap: MemSegment[] } const chips: ChipDesc[] = [ { name: "esp32", chipId: 0, memmap: [ { from: 0x00000000, to: 0x00010000, id: "PADDING" }, { from: 0x3F400000, to: 0x3F800000, id: "DROM" }, { from: 0x3F800000, to: 0x3FC00000, id: "EXTRAM_DATA" }, { from: 0x3FF80000, to: 0x3FF82000, id: "RTC_DRAM" }, { from: 0x3FF90000, to: 0x40000000, id: "BYTE_ACCESSIBLE" }, { from: 0x3FFAE000, to: 0x40000000, id: "DRAM" }, { from: 0x3FFE0000, to: 0x3FFFFFFC, id: "DIRAM_DRAM" }, { from: 0x40000000, to: 0x40070000, id: "IROM" }, { from: 0x40070000, to: 0x40078000, id: "CACHE_PRO" }, { from: 0x40078000, to: 0x40080000, id: "CACHE_APP" }, { from: 0x40080000, to: 0x400A0000, id: "IRAM" }, { from: 0x400A0000, to: 0x400BFFFC, id: "DIRAM_IRAM" }, { from: 0x400C0000, to: 0x400C2000, id: "RTC_IRAM" }, { from: 0x400D0000, to: 0x40400000, id: "IROM" }, { from: 0x50000000, to: 0x50002000, id: "RTC_DATA" }, ] }, { name: "esp32-s2", chipId: 2, memmap: [ { from: 0x00000000, to: 0x00010000, id: "PADDING" }, { from: 0x3F000000, to: 0x3FF80000, id: "DROM" }, { from: 0x3F500000, to: 0x3FF80000, id: "EXTRAM_DATA" }, { from: 0x3FF9E000, to: 0x3FFA0000, id: "RTC_DRAM" }, { from: 0x3FF9E000, to: 0x40000000, id: "BYTE_ACCESSIBLE" }, { from: 0x3FF9E000, to: 0x40072000, id: "MEM_INTERNAL" }, { from: 0x3FFB0000, to: 0x40000000, id: "DRAM" }, { from: 0x40000000, to: 0x4001A100, id: "IROM_MASK" }, { from: 0x40020000, to: 0x40070000, id: "IRAM" }, { from: 0x40070000, to: 0x40072000, id: "RTC_IRAM" }, { from: 0x40080000, to: 0x40800000, id: "IROM" }, { from: 0x50000000, to: 0x50002000, id: "RTC_DATA" }, ] }, { name: "esp32-s3", chipId: 4, memmap: [ { from: 0x00000000, to: 0x00010000, id: "PADDING" }, { from: 0x3C000000, to: 0x3D000000, id: "DROM" }, { from: 0x3D000000, to: 0x3E000000, id: "EXTRAM_DATA" }, { from: 0x600FE000, to: 0x60100000, id: "RTC_DRAM" }, { from: 0x3FC88000, to: 0x3FD00000, id: "BYTE_ACCESSIBLE" }, { from: 0x3FC88000, to: 0x403E2000, id: "MEM_INTERNAL" }, { from: 0x3FC88000, to: 0x3FD00000, id: "DRAM" }, { from: 0x40000000, to: 0x4001A100, id: "IROM_MASK" }, { from: 0x40370000, to: 0x403E0000, id: "IRAM" }, { from: 0x600FE000, to: 0x60100000, id: "RTC_IRAM" }, { from: 0x42000000, to: 0x42800000, id: "IROM" }, { from: 0x50000000, to: 0x50002000, id: "RTC_DATA" }, ] }, { name: "esp32-c3", chipId: 5, memmap: [ { from: 0x00000000, to: 0x00010000, id: "PADDING" }, { from: 0x3C000000, to: 0x3C800000, id: "DROM" }, { from: 0x3FC80000, to: 0x3FCE0000, id: "DRAM" }, { from: 0x3FC88000, to: 0x3FD00000, id: "BYTE_ACCESSIBLE" }, { from: 0x3FF00000, to: 0x3FF20000, id: "DROM_MASK" }, { from: 0x40000000, to: 0x40060000, id: "IROM_MASK" }, { from: 0x42000000, to: 0x42800000, id: "IROM" }, { from: 0x4037C000, to: 0x403E0000, id: "IRAM" }, { from: 0x50000000, to: 0x50002000, id: "RTC_IRAM" }, { from: 0x50000000, to: 0x50002000, id: "RTC_DRAM" }, { from: 0x600FE000, to: 0x60100000, id: "MEM_INTERNAL2" }, ] }, ] const segHdLen = 8 function segToString(seg: Segment) { return `0x${seg.addr.toString(16)} 0x${seg.data.length.toString(16)} bytes; ` + `${seg.isDROM ? "drom " : ""}${seg.isMapped ? "mapped " : ""}${U.toHex(seg.data.slice(0, 20))}...` } function padSegments(image: Image) { const align = 0x10000 const alignMask = align - 1 image = cloneStruct(image) image.segments.sort((a, b) => a.addr - b.addr) pxt.debug("esp padding:\n" + image.segments.map(segToString).join("\n") + "\n") const mapped = image.segments.filter(s => s.isMapped) const nonMapped = image.segments.filter(s => !s.isMapped) image.segments = [] let foff = image.header.length for (const seg of mapped) { // there's apparently a bug in ESP32 bootloader, that doesn't map the last page if it's smaller than 0x24 const leftoff = (seg.addr + seg.data.length) & alignMask if (leftoff < 0x24) { const padding = new Uint8Array(0x24 - leftoff) seg.data = pxt.U.uint8ArrayConcat([seg.data, padding]) } } while (mapped.length > 0) { let seg = mapped[0] const padLen = alignmentNeeded(seg) if (padLen > 0) { seg = getPaddingSegment(padLen) } else { if (((foff + segHdLen) & alignMask) != (seg.addr & alignMask)) { throw new Error(`pad oops 0 ${foff}+${segHdLen} != ${seg.addr} (mod mask)`) } mapped.shift() } image.segments.push(seg) foff += segHdLen + seg.data.length if (foff & 3) throw new Error("pad oops 1") } // append any remaining non-mapped segments image.segments = image.segments.concat(nonMapped) pxt.debug("esp padded:\n" + image.segments.map(segToString).join("\n") + "\n") return image function alignmentNeeded(seg: Segment) { const reqd = (seg.addr - segHdLen) & alignMask let padLen = (reqd - foff) & alignMask if (padLen == 0) return 0 padLen -= segHdLen if (padLen < 0) padLen += align return padLen } function getPaddingSegment(bytes: number): Segment { if (!nonMapped.length || bytes <= segHdLen) return { addr: 0, isMapped: false, isDROM: false, data: new Uint8Array(bytes) } const seg = nonMapped[0] const res: Segment = { addr: seg.addr, isMapped: seg.isMapped, isDROM: seg.isDROM, data: seg.data.slice(0, bytes) } seg.data = seg.data.slice(bytes) seg.addr += res.data.length if (seg.data.length == 0) nonMapped.shift() return res } } export function toBuffer(image: Image, digest = true) { image = padSegments(image) let size = image.header.length for (const seg of image.segments) { size += segHdLen + seg.data.length } size = (size + 16) & ~15 // align to 16 bytes - last byte will be weak checksum let res = new Uint8Array(size) res.set(image.header) res[1] = image.segments.length let off = image.header.length let checksum = 0xEF for (const seg of image.segments) { pxt.HF2.write32(res, off, seg.addr) pxt.HF2.write32(res, off + 4, seg.data.length) res.set(seg.data, off + segHdLen) off += segHdLen + seg.data.length for (let i = 0; i < seg.data.length; ++i) checksum ^= seg.data[i] } res[res.length - 1] = checksum if (digest) { res[23] = 1 const digest = ts.pxtc.BrowserImpl.sha256buffer(res) res = pxt.U.uint8ArrayConcat([res, pxt.U.fromHex(digest)]) } else { res[23] = 0 // disable digest } // console.log("reparsed\n" + parseBuffer(res).segments.map(segToString).join("\n") + "\n") return res } export function parseBuffer(buf: Uint8Array) { if (buf[0] != 0xE9) throw new Error("ESP: invalid magic: " + buf[0]) let ptr = 24 const chipId = r16(buf, 12) const chipdesc = chips.find(c => c.chipId == chipId) if (!chipdesc) throw new Error("ESP: unknown chipid: " + chipId) const image: Image = { header: buf.slice(0, ptr), chipName: chipdesc.name, segments: [] } const numseg = buf[1] for (let i = 0; i < numseg; ++i) { const offset = r32(buf, ptr) const size = r32(buf, ptr + 4) ptr += segHdLen const data = buf.slice(ptr, ptr + size) if (data.length != size) throw new Error("too short file") ptr += size if (isInSection(offset, "PADDING")) continue const ex = image.segments.filter(seg => seg.addr + seg.data.length == offset)[0] if (ex) ex.data = pxt.U.uint8ArrayConcat([ex.data, data]) else image.segments.push({ addr: offset, isMapped: isInSection(offset, "DROM") || isInSection(offset, "IROM"), isDROM: isInSection(offset, "DROM"), data: data }) } return image function isInSection(addr: number, sect: string) { return chipdesc.memmap.some(m => m.id == sect && m.from <= addr && addr <= m.to) } } export function parseB64(lines: string[]) { return parseBuffer(pxt.U.stringToUint8Array(atob(lines.join("")))) } export function cloneStruct(img: Image) { const res = U.flatClone(img) res.segments = res.segments.map(U.flatClone) return res } }
the_stack
import { createAutocomplete } from '@algolia/autocomplete-core'; import { autocomplete } from '@algolia/autocomplete-js'; import { Hit } from '@algolia/client-search'; import { fireEvent, waitFor, within } from '@testing-library/dom'; import userEvent from '@testing-library/user-event'; import { castToJestMock, createMultiSearchResponse, createPlayground, createSearchClient, runAllMicroTasks, } from '../../../../test/utils'; import { createQuerySuggestionsPlugin } from '../createQuerySuggestionsPlugin'; /* eslint-disable @typescript-eslint/camelcase */ const hits: Hit<any> = [ { instant_search: { exact_nb_hits: 260, facets: { exact_matches: { categories: [ { value: 'Appliances', count: 252, }, { value: 'Ranges, Cooktops & Ovens', count: 229, }, ], }, }, }, nb_words: 1, popularity: 1230, query: 'cooktop', objectID: 'cooktop', _highlightResult: { query: { value: 'cooktop', matchLevel: 'none', matchedWords: [], }, }, }, ]; /* eslint-enable @typescript-eslint/camelcase */ const searchClient = createSearchClient({ search: jest.fn(() => Promise.resolve(createMultiSearchResponse({ hits }))), }); beforeEach(() => { document.body.innerHTML = ''; }); describe('createQuerySuggestionsPlugin', () => { test('has a name', () => { const plugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', }); expect(plugin.name).toBe('aa.querySuggestionsPlugin'); }); test('exposes passed options and excludes default ones', () => { const plugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', transformSource: ({ source }) => source, }); expect(plugin.__autocomplete_pluginOptions).toEqual({ searchClient: expect.any(Object), indexName: expect.any(String), transformSource: expect.any(Function), }); }); test('adds a source with Query Suggestions and renders the template', async () => { const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.children) ).toMatchInlineSnapshot(` Array [ HTMLCollection [ <div class="aa-ItemWrapper" > <div class="aa-ItemContent" > <div class="aa-ItemIcon aa-ItemIcon--noBorder" > <svg fill="currentColor" viewBox="0 0 24 24" > <path d="M16.041 15.856c-0.034 0.026-0.067 0.055-0.099 0.087s-0.060 0.064-0.087 0.099c-1.258 1.213-2.969 1.958-4.855 1.958-1.933 0-3.682-0.782-4.95-2.050s-2.050-3.017-2.050-4.95 0.782-3.682 2.050-4.95 3.017-2.050 4.95-2.050 3.682 0.782 4.95 2.050 2.050 3.017 2.050 4.95c0 1.886-0.745 3.597-1.959 4.856zM21.707 20.293l-3.675-3.675c1.231-1.54 1.968-3.493 1.968-5.618 0-2.485-1.008-4.736-2.636-6.364s-3.879-2.636-6.364-2.636-4.736 1.008-6.364 2.636-2.636 3.879-2.636 6.364 1.008 4.736 2.636 6.364 3.879 2.636 6.364 2.636c2.125 0 4.078-0.737 5.618-1.968l3.675 3.675c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414z" /> </svg> </div> <div class="aa-ItemContentBody" > <div class="aa-ItemContentTitle" > cooktop </div> </div> </div> <div class="aa-ItemActions" > <button class="aa-ItemActionButton" title="Fill query with \\"cooktop\\"" > <svg fill="currentColor" viewBox="0 0 24 24" > <path d="M8 17v-7.586l8.293 8.293c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414l-8.293-8.293h7.586c0.552 0 1-0.448 1-1s-0.448-1-1-1h-10c-0.552 0-1 0.448-1 1v10c0 0.552 0.448 1 1 1s1-0.448 1-1z" /> </svg> </button> </div> </div>, ], ] `); }); }); test('adds categories to suggestions', async () => { const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', categoryAttribute: [ 'instant_search', 'facets', 'exact_matches', 'categories', ], }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { const options = within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.children); expect(options).toHaveLength(2); expect(options[1]).toMatchInlineSnapshot(` HTMLCollection [ <div class="aa-ItemWrapper" > <div class="aa-ItemContent aa-ItemContent--indented" > <div class="aa-ItemContentSubtitle aa-ItemContentSubtitle--standalone" > <span class="aa-ItemContentSubtitleIcon" /> <span> in <span class="aa-ItemContentSubtitleCategory" > Appliances </span> </span> </div> </div> </div>, ] `); }); }); test('adds a single category to the first suggestion by default', async () => { castToJestMock(searchClient.search).mockReturnValueOnce( Promise.resolve( createMultiSearchResponse({ hits: [...hits, ...hits], }) ) ); const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', categoryAttribute: [ 'instant_search', 'facets', 'exact_matches', 'categories', ], }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.textContent) ).toEqual([ 'cooktop', // Query Suggestions item 'in Appliances', // Category item 'cooktop', // Query Suggestions item ]); }); }); test('sets a custom number of items with categories', async () => { castToJestMock(searchClient.search).mockReturnValueOnce( Promise.resolve( createMultiSearchResponse({ hits: [...hits, ...hits, ...hits], }) ) ); const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', categoryAttribute: [ 'instant_search', 'facets', 'exact_matches', 'categories', ], itemsWithCategories: 2, }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.textContent) ).toEqual([ 'cooktop', // Query Suggestions item 'in Appliances', // Category item 'cooktop', // Query Suggestions item 'in Appliances', // Category item 'cooktop', // Query Suggestions item ]); }); }); test('sets a custom number of categories to display per item', async () => { castToJestMock(searchClient.search).mockReturnValueOnce( Promise.resolve( createMultiSearchResponse({ hits: [...hits, ...hits], }) ) ); const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', categoryAttribute: [ 'instant_search', 'facets', 'exact_matches', 'categories', ], categoriesPerItem: 2, }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.textContent) ).toEqual([ 'cooktop', // Query Suggestions item 'in Appliances', // Category item 'in Ranges, Cooktops & Ovens', // Category item 'cooktop', // Query Suggestions item ]); }); }); test('fills the input with the query item key followed by a space on tap ahead', async () => { const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( document.querySelector<HTMLElement>('.aa-Panel') ).toBeInTheDocument(); }); userEvent.click( within(panelContainer).getByRole('button', { name: 'Fill query with "cooktop"', }) ); await runAllMicroTasks(); await waitFor(() => { expect(input.value).toBe('cooktop '); }); }); test('supports custom templates', async () => { const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', transformSource({ source }) { return { ...source, templates: { item({ item, createElement, Fragment }) { return createElement( Fragment, null, createElement('span', null, item.query), createElement('button', null, `Fill with "${item.query}"`) ); }, }, }; }, }); const container = document.createElement('div'); const panelContainer = document.createElement('div'); document.body.appendChild(panelContainer); autocomplete({ container, panelContainer, plugins: [querySuggestionsPlugin], }); const input = container.querySelector<HTMLInputElement>('.aa-Input'); fireEvent.input(input, { target: { value: 'a' } }); await waitFor(() => { expect( within( panelContainer.querySelector( '[data-autocomplete-source-id="querySuggestionsPlugin"]' ) ) .getAllByRole('option') .map((option) => option.children) ).toMatchInlineSnapshot(` Array [ HTMLCollection [ <span> cooktop </span>, <button> Fill with "cooktop" </button>, ], ] `); }); }); test('supports user search params', async () => { const querySuggestionsPlugin = createQuerySuggestionsPlugin({ searchClient, indexName: 'indexName', getSearchParams: () => ({ attributesToRetrieve: ['name', 'category'] }), }); const { inputElement } = createPlayground(createAutocomplete, { plugins: [querySuggestionsPlugin], }); userEvent.type(inputElement, 'a'); await runAllMicroTasks(); expect(searchClient.search).toHaveBeenLastCalledWith([ { indexName: 'indexName', query: 'a', params: expect.objectContaining({ attributesToRetrieve: ['name', 'category'], }), }, ]); }); });
the_stack
require('source-map-support').install(); import blaze = require('./blaze'); import expression = require('../src/expression'); import tv4 = require('tv4'); import fs = require('fs'); import Json = require('source-processor'); import error = require('source-processor'); import optimizer = require('../src/optimizer'); import globals = require('../src/globals'); //todo //refactor out traversals var debug_metaschema_validation = false; /** * performs a bottom up traversal of a schema definition, allowing each metaschema processor * to generate constraints */ export function annotate(model: blaze.Rules){ model.schema.root = annotate_schema(model.schema.json, null, null, new SchemaAPI(), model) } /** * pushes ancestors schema constraints to being explicitly being represented in leaf nodes * this is done by leaves being the && concatenation of all ancestors * next in a parent's context is next.parent() in the child context */ export function pushDownConstraints(model:blaze.Rules){ model.schema.root.pushDownConstraints(model.functions, null); } /** * pulls full leaf schema constraints upwards. ancestors constraints are overwritten * by the && concatenation of all children */ export function pullUpConstraints(model:blaze.Rules){ model.schema.root.pullUpConstraints(model.functions, ""); } /** * intergrates the ACL constraints into the schema */ export function combineACL(model:blaze.Rules){ model.schema.root.combineACL(model.functions, model.access, []); } /** * intergrates the ACL constraints into the schema */ export function generateRules(model:blaze.Rules){ var buffer:string[] = []; buffer.push('{\n'); buffer.push(' "rules":'); var symbols = new expression.Symbols(); symbols.loadFunction(model.functions); model.schema.root.generate(symbols, " ", buffer, false); buffer.push('}\n'); //convert buffer into big string var code: string = buffer.join(''); return code; } /** * main model class for schema tree, all schema nodes are parsed into this format by annotate */ export class SchemaNode{ static KEY_PATTERN:string = ".*"; //regex for patterns type: string; properties: {[name:string]:SchemaNode} = {}; constraint: expression.Expression; write: expression.Expression; read: expression.Expression; additionalProperties: boolean; node: any; examples: Json.JArray; nonexamples: Json.JArray; indexOn: string[]; constructor(node:any){ this.node = node; } isLeaf(): boolean{ return Object.keys(this.properties).length == 0; } generate(symbols: expression.Symbols, prefix: string, buffer: string[], use_validation: boolean): string[]{ buffer.push('{\n'); if (this.indexOn.length > 0){ buffer.push(prefix + ' ".indexOn": ["' + this.indexOn.join('", "') + '"],\n'); } buffer.push(prefix + ' ".write":"'); buffer.push(optimizer.escapeEscapes(this.write.generate(symbols))); buffer.push('",\n'); if (use_validation) { //validation is repeated for wilderchilds, so the child constraints fire (when not null) //even when parent is set buffer.push(prefix + ' ".validate":"'); buffer.push(optimizer.escapeEscapes(this.write.generate(symbols))); buffer.push('",\n'); } buffer.push(prefix + ' ".read":"'); buffer.push(optimizer.escapeEscapes(this.read.generate(symbols))); buffer.push('",\n'); var comma_in_properties = false; //recurse for (var property in this.properties){ if (property.indexOf("~$") == 0) { //nullable wildchild var name = property.substr(1); var use_validation_child = true; } else { //normal wildchilds and fixed properties var name = property; var use_validation_child = false; } buffer.push(prefix + ' "' + name + '": '); this.properties[property].generate(symbols, prefix + " ", buffer, use_validation_child); buffer.pop(); //pop closing brace and continue with comma buffer.push('},\n'); comma_in_properties = true; } if (!this.additionalProperties){ buffer.push(prefix + ' "$other":{".validate":"false"'); buffer.push('GETS REMOVED BY CODE BELOW'); comma_in_properties = true; } //remove last trailing comma if (comma_in_properties){ buffer.pop(); buffer.push("}\n"); } else { //else the comma was placed last at the ".read" statement buffer.pop(); buffer.push('"\n'); } buffer.push(prefix); buffer.push("}\n"); return buffer; } /** * moves ancestors constraints to being explicitly being represented in leaf nodes * this is done by leaves being the && concatenation of all ancestors * next in a parent's context is next.parent() in the child context */ pushDownConstraints(functions: expression.Functions, inherited_clause:expression.Expression) { var symbols: expression.Symbols = new expression.Symbols(); symbols.loadFunction(functions); if(inherited_clause != null){ this.constraint = expression.Expression.parse( "(" + inherited_clause.rewriteForChild() + ")&&(" + this.constraint.expandFunctions(symbols) + ")"); } //recurse last for top down for(var property in this.properties){ this.properties[property].pushDownConstraints(functions, this.constraint) } } pullUpConstraints(functions: expression.Functions, child_name):string{ if(this.isLeaf()) return this.constraint.rewriteForParent(child_name); var symbols: expression.Symbols = new expression.Symbols(); symbols.loadFunction(functions); var children_clauses:string = this.constraint.expandFunctions(symbols); //recurse first for bottom up for(var property in this.properties){ children_clauses = "(" +children_clauses+ ") && (" + this.properties[property].pullUpConstraints(functions, property) + ")" } this.constraint = expression.Expression.parse(children_clauses); return this.constraint.rewriteForParent(child_name); } combineACL(functions: expression.Functions, acl: blaze.Access, location: string[]){ //console.log("combineACL", location); var write:string = "false"; var read: string = "false"; var symbols: expression.Symbols = new expression.Symbols(); symbols.loadFunction(functions); //work out what ACL entries are active for this node by ORing active entries clauses together for(var idx in acl){ var entry: blaze.AccessEntry = acl[idx]; if(entry.match(location)){ write = "(" + write + ")||(" + entry.getWriteFor(symbols, location).raw + ")"; read = "(" + read + ")||(" + entry.getReadFor(symbols, location).raw + ")"; } } //combine the write rules with the schema constraints this.write = expression.Expression.parse("(" + this.constraint.raw + ")&&(" + write + ")"); this.read = expression.Expression.parse(read); //recurse for(var property in this.properties){ var child_location: string[] = location.concat(<string>property); this.properties[property].combineACL(functions, acl, child_location); } } getWildchild():string { return getWildchild(this.node).value; } } export class MetaSchema{ validator: Json.JValue; //json schema json used for validation of type compile:(api:SchemaAPI) => void; //function used to generate type specific constraints validate(data: Json.JValue): boolean{ if (debug_metaschema_validation) { console.log("validating data"); console.log(data.toJSON()); console.log("with schema"); console.log(this.validator.toJSON()); } var valid = tv4.validate(data.toJSON(), this.validator.toJSON(), true, true); if(!valid){ throw error.validation( data, this.validator, "schema node", "type schema", tv4.error ).source(data).on(new Error()) } else { if (debug_metaschema_validation) console.log("passed validation"); } if(tv4.getMissingUris().length != 0){ throw error.message("missing $ref definitions: " + tv4.getMissingUris()).source(data).on(new Error()); } return valid; } static parse(json: Json.JValue): MetaSchema{ var result:MetaSchema = new MetaSchema(); result.validator = json.getOrThrow("validator", "no validator defined for the metaschema"); result.compile = <(api:SchemaAPI) => void>new Function("api", json.getOrThrow("compile", "no compile defined for the metaschema").asString().value); return result; } } function annotate_schema(node: Json.JValue, parent: Json.JValue, key: string, api: SchemaAPI, model: blaze.Rules): SchemaNode { if (node.has("$ref")) { //we should replace this node with its definition node = fetchRef(node.getOrThrow("$ref", "").coerceString().value, model); if (key.indexOf("$") == 0 || key.indexOf("~$") == 0) { parent.asObject().put(new Json.JString(key, -1, -1), node) } else { parent.asObject().getOrThrow("properties", "no properties defined above reference with key:" + key).asObject().put(new Json.JString(key, -1, -1), node) } } var annotation = new SchemaNode(node); //recurse to children first in bottom up if (node.has("properties")) { node.getOrThrow("properties", "").asObject().forEach( function(name: Json.JString, child: Json.JValue){ if (name.value.indexOf("$") == 0 || name.value.indexOf("~$") == 0) throw error.message( "properties cannot start with $ or ~$, you probably want a wild(er)child which is not declared in the properties section" ).source(name).on(new Error()); annotation.properties[name.value] = annotate_schema(child, node, name.getString(), api, model); }); } if (globals.debug) console.log("annotate_schema", node.toJSON()); //wildchilds need special treatment as they are not normal properties but still schema nodes if (getWildchild(node)){ //add them as a property annotation var wildname = getWildchild(node).value; var wildkey = getWildchild(node); annotation.properties[wildname] = annotate_schema( node.getOrThrow(wildname, "cant find wildchild"), node, wildname, api, model); //we also convert them into a pattern properties and add it to the JSON schema node so examples can pass var patternProperties = new Json.JObject(); //so we move the wildchild from the root of the schema declaration, //into a child of patternProperties so that the JSON schema validator can read it like a pattern //accepting any property without saying its not declared node.asObject().put( new Json.JString("patternProperties", wildkey.start.position, wildkey.end.position), patternProperties); patternProperties.put( new Json.JString(SchemaNode.KEY_PATTERN, 0,0), node.getOrThrow(wildname, "cant find wildchild")); } else { //console.log("no wildchild") } //fill in all defaults for a schema node api.setContext(node, parent, annotation, model); annotation.type = node.has("type") ? node.getOrThrow("type", "").asString().value: "any"; if (!node.has("constraint")) { node.asObject().put( //synthetically place a constraint in the user source so the SchemaAPI can extend it new Json.JString("constraint", 0,0), new Json.JString("true", 0,0) ) } annotation.additionalProperties = //objects are allowed extra properties by default node.has("additionalProperties") ? node.getOrThrow("additionalProperties", "").asBoolean().value : true; annotation.examples = node.has("examples") ? node.asObject().getOrThrow("examples", "").asArray(): new Json.JArray(); annotation.nonexamples = node.has("nonexamples") ? node.asObject().getOrThrow("nonexamples", "").asArray(): new Json.JArray(); annotation.indexOn = []; //get indexOn, whether specified as a single string or an array if (node.has("indexOn")) { var index: Json.JValue = node.asObject().getOrThrow("indexOn", ""); if (index.type == Json.JType.JString) { annotation.indexOn = [index.asString().value] } else { index.asArray().forEach(function (val) { annotation.indexOn.push(val.asString().value) }) } } //using type information, the metaschema is given an opportunity to customise the node with type specific keywords if (api.metaschema[annotation.type] != undefined){ if (api.metaschema[annotation.type].validate(node)){ //the user compile could actually add more nodes, see schemaAPI.addProperty //if this happens annotate_schema needs to be called for new nodes //entering the system pragmatically in compile (done in addProperty) api.metaschema[annotation.type].compile(api); } else { throw error.validation( node, api.metaschema[annotation.type].validator, "subtree", "annotation.type", tv4.error ).on(new Error()); } } else { throw error.source(node).message("unknown type '" + annotation.type + "' no metaschema to validate it").on(new Error()); } //we parse the constraint after the api has processed it //as it might have changed the constraints as part of its domain annotation.constraint = expression.Expression.parseUser( node.asObject().getOrThrow("constraint", "no constraint defined").coerceString() ); //if the user has supplied examples or non examples, the validity of these are checked annotation.examples.forEach(function(example: Json.JValue){ var valid = tv4.validate(example.toJSON(), node.toJSON(), true, false); if(!valid){ throw error.validation( example, node, "example", "schema", tv4.error ).on(new Error()); } }); annotation.nonexamples.forEach(function(nonexample: Json.JValue){ var valid = tv4.validate(nonexample.toJSON(), node.toJSON(), true, false); if(valid){ throw error.message("nonexample erroneously passed").source(nonexample).on(new Error()); } }); return annotation; } export function fetchRef(url:string, model:blaze.Rules): Json.JValue{ //todo: this should probably be routed through tv4's getSchema method properly //code nicked from tv4.getSchema: var baseUrl = url; //not interested in yet var fragment = ""; if (url.indexOf('#') !== -1) { fragment = url.substring(url.indexOf("#") + 1); baseUrl = url.substring(0, url.indexOf("#")); } var pointerPath = decodeURIComponent(fragment); if (pointerPath.charAt(0) !== "/") { throw error.message("$ref URL not starting with / or #/ " + url).on(new Error()) } var parts = pointerPath.split("/").slice(1); var schema:Json.JValue = model.schema.json; //navigate user source for (var i = 0; i < parts.length; i++) { var component: string = parts[i].replace(/~1/g, "/").replace(/~0/g, "~"); schema = schema.getOrThrow(component, [ JSON.stringify(schema.toJSON()), "could not find schema at " + component + " of " + pointerPath, ].join("\n")) } if (globals.debug) console.log("fetchRef" + url + " retrieved " + JSON.stringify(schema.toJSON())); return schema; } /** * provides hooks for meta-data to pragmatically generate constraints and functions */ export class SchemaAPI{ metaschema:{[name:string]:MetaSchema} = {}; link: Json.JValue; //we provide a pointer to the live representation, so we can updated it node: any; //local context for api application, a raw JSON, for presentation to the meta-schema author parent: any; //local context for api application, also a raw JSON and it should not be updated annotationInProgress: SchemaNode; //local context for api application model: blaze.Rules; constructor(){ //load all built in schema definitions from schema directory var files = fs.readdirSync(blaze.root + "schema/metaschema"); for(var i in files){ if (!files.hasOwnProperty(i)) continue; var path = blaze.root + "schema/metaschema"+'/'+files[i]; var metaschema_def = blaze.load_yaml(path); var typename: string = metaschema_def.getOrThrow("name", "meta-schema is not named in: " + path).asString().value; console.log("loading type " + typename + " definition from " + path); this.metaschema[typename] = MetaSchema.parse(metaschema_def); } } /** * before the metaschema is given a hook for adding constraints, this method is called to * point the api at the right schema instances * @param node * @param parent * @param annotationInProgress */ setContext(node: Json.JValue, parent: Json.JValue, annotationInProgress: SchemaNode, model: blaze.Rules){ this.link = node; this.node = this.link.toJSON(); this.parent = parent == null ? null : parent.toJSON(); this.annotationInProgress = annotationInProgress; this.model = model; } /** * User method for adding a type specific constraint, the constraint is &&ed to the current constraints */ addConstraint(expression:string): void { if (globals.debug) console.log("addConstraint " + expression); this.link.asObject().put( new Json.JString("constraint", 0,0), new Json.JString( "("+ this.link.getOrThrow("constraint", "constraint not defined").coerceString().value + ") && (" + expression + ")", 0,0) ) } /** * User method for dynamically adding a property as a schema node */ addProperty(name:string, json:any):void{ throw new Error("redo since refactor, not reflecting change from raw json to Json.JValue"); this.node[name] = json; //as this is called through compile, which is part way through the annotation, //this new node would be over looked, so we need call the annotation routine explicitly out of turn var extra_annotator = new SchemaAPI(); extra_annotator.setContext(json, this.node, this.annotationInProgress, this.model); this.annotationInProgress.properties[name] = annotate_schema(json, this.node, name, extra_annotator, this.model); } /** * User method for read access to schema fields * returns null if the field is not present * specifying type ('array', 'object', 'string', 'boolean', 'number') is optional */ getField(name:string, type: string): any{ if(globals.debug) console.log("getField on", name, "result:", this.node[name], this.node); if(this.node[name] == null) return null; //so the field is present, now we check the type if (type !== undefined) { if(type == 'array') { return this.link.getOrThrow(name, "").asArray().toJSON } else if(type == 'object') { return this.link.getOrThrow(name, "").asObject().toJSON } else if(type == 'string') { return this.link.getOrThrow(name, "").asString().toJSON } else if(type == 'boolean') { return this.link.getOrThrow(name, "").asBoolean().toJSON } else if(type == 'number') { return this.link.getOrThrow(name, "").asNumber().toJSON } else { throw error.message("unrecognised type specified: " + type).on(new Error()) } } return this.node[name]; } /** * user method for retrieving the wildchild's name for this node * call getField(getWildchild()) if you want the wildchilds schema node * @returns {string} */ getWildchild(): string{ return getWildchild(this.node).value } } export function getWildchild(node: Json.JValue): Json.JString{ var wildchild: Json.JString = null; node.asObject().forEach( function(keyword: Json.JString, child: Json.JValue){ var name: string = keyword.value; if (name.indexOf("$") == 0 || name.indexOf("~$") == 0) { if(wildchild == null) wildchild = keyword; else{ throw error.message("multiple wildchilds defined:\n").source(node).on(new Error()) } } }); return wildchild; }
the_stack
import * as singleLineString from "single-line-string"; import * as Web3 from "web3"; // Utils import { BigNumber } from "../../utils/bignumber"; import { generateTxOptions } from "../../utils/transaction_utils"; // Types import { TxData } from "../types"; // Invariants import { Assertions } from "../invariants"; // APIs import { ContractsAPI } from "./"; // Wrappers import { DebtTokenContract } from "../wrappers"; export interface ERC721 { balanceOf(owner: string): Promise<BigNumber>; ownerOf(tokenID: BigNumber): Promise<string>; exists(tokenID: BigNumber): Promise<boolean>; approveAsync(to: string, tokenID: BigNumber, options?: TxData): Promise<string>; getApproved(tokenID: BigNumber): Promise<string>; setApprovalForAllAsync(operator: string, approved: boolean, options?: TxData): Promise<string>; isApprovedForAll(owner: string, operator: string): Promise<boolean>; transferAsync(to: string, tokenID: BigNumber, options?: TxData): Promise<string>; transferFromAsync( from: string, to: string, tokenID: BigNumber, data?: string, options?: TxData, ): Promise<string>; } const ERC721_TRANSFER_GAS_MAXIMUM = 200000; export const DebtTokenAPIErrors = { ONLY_OWNER: (account: string) => singleLineString` Specified debt token does not belong to account ${account} `, NOT_OWNER: () => singleLineString`The recipient cannot be the owner of the debt token.`, TOKEN_WITH_ID_DOES_NOT_EXIST: () => singleLineString`The debt token specified does not exist.`, ACCOUNT_UNAUTHORIZED_TO_TRANSFER: (account: string) => singleLineString` Transaction sender ${account} neither owns the specified token nor is approved to transfer it. `, RECIPIENT_WONT_RECOGNIZE_TOKEN: (recipient: string) => singleLineString` Recipient ${recipient} is a contract that does not implement the ERC721Receiver interface, and therefore cannot have ERC721 tokens transferred to it. `, OWNER_CANNOT_BE_OPERATOR: () => singleLineString`Owner cannot list themselves as operator.`, }; export class DebtTokenAPI implements ERC721 { private web3: Web3; private contracts: ContractsAPI; private assert: Assertions; constructor(web3: Web3, contracts: ContractsAPI) { this.web3 = web3; this.contracts = contracts; this.assert = new Assertions(web3, this.contracts); } public async balanceOf(owner: string): Promise<BigNumber> { // Assert owner is a valid address. this.assert.schema.address("owner", owner); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); return debtTokenContract.balanceOf.callAsync(owner); } public async ownerOf(tokenID: BigNumber): Promise<string> { // Assert token is valid. this.assert.schema.wholeNumber("tokenID", tokenID); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); // Assert token exists. await this.assert.debtToken.exists( debtTokenContract, tokenID, DebtTokenAPIErrors.TOKEN_WITH_ID_DOES_NOT_EXIST(), ); return debtTokenContract.ownerOf.callAsync(tokenID); } public async exists(tokenID: BigNumber): Promise<boolean> { // Assert token is valid. this.assert.schema.wholeNumber("tokenID", tokenID); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); return debtTokenContract.exists.callAsync(tokenID); } public async approveAsync(to: string, tokenID: BigNumber, options?: TxData): Promise<string> { // Assert `to` is a valid address. this.assert.schema.address("to", to); // Assert token is valid. this.assert.schema.wholeNumber("tokenID", tokenID); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); const txOptions = await generateTxOptions(this.web3, ERC721_TRANSFER_GAS_MAXIMUM, options); const { from } = txOptions; // Ensure the token exists. await this.assert.debtToken.exists( debtTokenContract, tokenID, DebtTokenAPIErrors.TOKEN_WITH_ID_DOES_NOT_EXIST(), ); // Ensure the owner of the token is the one invoking `approve` await this.assert.debtToken.onlyOwner( debtTokenContract, tokenID, from, DebtTokenAPIErrors.ONLY_OWNER(from), ); // Ensure the approvee is not the owner. await this.assert.debtToken.notOwner( debtTokenContract, tokenID, to, DebtTokenAPIErrors.NOT_OWNER(), ); return debtTokenContract.approve.sendTransactionAsync(to, tokenID, txOptions); } public async getApproved(tokenID: BigNumber): Promise<string> { // Assert token is valid. this.assert.schema.wholeNumber("tokenID", tokenID); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); // Assert token exists. await this.assert.debtToken.exists( debtTokenContract, tokenID, DebtTokenAPIErrors.TOKEN_WITH_ID_DOES_NOT_EXIST(), ); return debtTokenContract.getApproved.callAsync(tokenID); } public async setApprovalForAllAsync( operator: string, approved: boolean, options?: TxData, ): Promise<string> { const debtTokenContract = await this.contracts.loadDebtTokenAsync(); const txOptions = await generateTxOptions(this.web3, ERC721_TRANSFER_GAS_MAXIMUM, options); this.assert.schema.address("operator", operator); if (operator === txOptions.from) { throw new Error(DebtTokenAPIErrors.OWNER_CANNOT_BE_OPERATOR()); } return debtTokenContract.setApprovalForAll.sendTransactionAsync( operator, approved, txOptions, ); } public async isApprovedForAll(owner: string, operator: string): Promise<boolean> { this.assert.schema.address("operator", operator); this.assert.schema.address("owner", owner); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); return debtTokenContract.isApprovedForAll.callAsync(owner, operator); } public async transferAsync(to: string, tokenID: BigNumber, options?: TxData): Promise<string> { this.validateTransferArguments(to, tokenID); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); const txOptions = await generateTxOptions(this.web3, ERC721_TRANSFER_GAS_MAXIMUM, options); await this.assertTransferValid(debtTokenContract, to, tokenID, txOptions); const owner = await this.ownerOf(tokenID); return debtTokenContract.safeTransferFrom.sendTransactionAsync( owner, to, tokenID, "", txOptions, ); } public async transferFromAsync( from: string, to: string, tokenID: BigNumber, data?: string, options?: TxData, ): Promise<string> { this.validateTransferFromArguments(from, to, tokenID, data); const txOptions = await generateTxOptions(this.web3, ERC721_TRANSFER_GAS_MAXIMUM, options); const debtTokenContract = await this.contracts.loadDebtTokenAsync(); await this.assertTransferFromValid(debtTokenContract, from, to, tokenID, data, txOptions); return debtTokenContract.safeTransferFrom.sendTransactionAsync( from, to, tokenID, data, txOptions, ); } private async assertTransferValid( debtTokenContract: DebtTokenContract, to: string, tokenID: BigNumber, txOptions: TxData, ): Promise<void> { // Assert token exists await this.assert.debtToken.exists( debtTokenContract, tokenID, DebtTokenAPIErrors.TOKEN_WITH_ID_DOES_NOT_EXIST(), ); // Assert that message sender can transfer said token await this.assert.debtToken.canBeTransferredByAccount( debtTokenContract, tokenID, txOptions.from, DebtTokenAPIErrors.ACCOUNT_UNAUTHORIZED_TO_TRANSFER(txOptions.from), ); // Assert that `to` can be the recipient of an ERC721 token await this.assert.debtToken.canBeReceivedByAccountWithData( this.web3, tokenID, to, txOptions.from, "", DebtTokenAPIErrors.RECIPIENT_WONT_RECOGNIZE_TOKEN(to), ); } private async assertTransferFromValid( debtTokenContract: DebtTokenContract, from: string, to: string, tokenID: BigNumber, data: string, txOptions: TxData, ): Promise<void> { // Assert token exists await this.assert.debtToken.exists( debtTokenContract, tokenID, DebtTokenAPIErrors.TOKEN_WITH_ID_DOES_NOT_EXIST(), ); // Assert token belongs to `from` await this.assert.debtToken.onlyOwner( debtTokenContract, tokenID, from, DebtTokenAPIErrors.ONLY_OWNER(from), ); // Assert that message sender can transfer said token await this.assert.debtToken.canBeTransferredByAccount( debtTokenContract, tokenID, txOptions.from, DebtTokenAPIErrors.ACCOUNT_UNAUTHORIZED_TO_TRANSFER(txOptions.from), ); // Assert that `to` can be the recipient of an ERC721 token await this.assert.debtToken.canBeReceivedByAccountWithData( this.web3, tokenID, to, from, data, DebtTokenAPIErrors.RECIPIENT_WONT_RECOGNIZE_TOKEN(to), ); } private validateTransferArguments(to: string, tokenID: BigNumber): void { this.assert.schema.address("to", to); this.assert.schema.wholeNumber("tokenID", tokenID); } private validateTransferFromArguments( from: string, to: string, tokenID: BigNumber, data?: string, ): void { this.validateTransferArguments(to, tokenID); this.assert.schema.address("from", from); if (data) { this.assert.schema.bytes("data", data); } } }
the_stack
import { describe, it } from "mocha"; import rewire from "rewire"; import sinon from "sinon"; import { assert } from "chai"; import { packedValue } from "../../src/custom_types"; const converters = rewire("../../src/converters"); function newArrayBuffer(bytes: number[]): ArrayBuffer { const ab = new ArrayBuffer(bytes.length), ua = new Uint8Array(ab); for (let i = 0; i < ua.length; i++) { ua[i] = bytes[i]; } return ab; } const toPackedTests = [ { name: "4-byte Input", inputs: { hex: "41424344", b64: "QUJDRA==", arrayBuffer: newArrayBuffer([0x41, 0x42, 0x43, 0x44]), uint8Array: Uint8Array.from([0x41, 0x42, 0x43, 0x44]), existing: [0x45000000], existingMod: [0x00000045], lengthExisting: 8, }, outputs: { original: [0x41424344], existing: [0x45414243, 0x44000000], originalMod: [0x44434241], existingMod: [0x43424145, 0x00000044], length: 32, }, }, ]; function toPackedTestsBuilder( funcToTest: ( // eslint-disable-next-line @typescript-eslint/no-explicit-any input: any, existingBin: number[] | undefined, existingBinLen: number | undefined, bigEndianMod: -1 | 1 ) => packedValue, inputType: "hex" | "b64" | "arrayBuffer" | "uint8Array" ): void { toPackedTests.forEach((test) => { it(`${test.name} - No Existing Input`, () => { assert.deepEqual(funcToTest(test.inputs[inputType], undefined, undefined, -1), { value: test.outputs.original, binLen: test.outputs.length, }); }); it(`${test.name} - Existing Input`, () => { assert.deepEqual( funcToTest(test.inputs[inputType], test.inputs.existing.slice(), test.inputs.lengthExisting, -1), { value: test.outputs.existing, binLen: test.outputs.length + test.inputs.lengthExisting, } ); }); it(`${test.name} - No Existing Input with Endian Modifier`, () => { assert.deepEqual(funcToTest(test.inputs[inputType], undefined, undefined, 1), { value: test.outputs.originalMod, binLen: test.outputs.length, }); }); it(`${test.name} - Existing Input with Endian Modifier`, () => { assert.deepEqual( funcToTest(test.inputs[inputType], test.inputs.existingMod.slice(), test.inputs.lengthExisting, 1), { value: test.outputs.existingMod, binLen: test.outputs.length + test.inputs.lengthExisting, } ); }); }); } describe("Test hex2packed", () => { const hex2packed = converters.__get__("hex2packed"); // Basic I/O tests toPackedTestsBuilder(hex2packed, "hex"); // Input Validation Tests it("Invalid Length Exception", () => { assert.throws(() => { hex2packed("F", undefined, undefined, -1); }, "String of HEX type must be in byte increments"); }); it("Invalid Character Exception", () => { assert.throws(() => { hex2packed("GG", [], 0 - 1); }, "String of HEX type contains invalid characters"); }); }); describe("Test b642packed", () => { const b642packed = converters.__get__("b642packed"); // Basic I/O tests toPackedTestsBuilder(b642packed, "b64"); // Input Validation Tests it("Invalid '=' Exception", () => { assert.throws(() => { b642packed("=F", undefined, undefined, -1); }, "Invalid '=' found in base-64 string"); }); it("Invalid Character Exception", () => { assert.throws(() => { b642packed("$", undefined, undefined, -1); }, "Invalid character in base-64 string"); }); }); describe("Test uint8array2packed", () => { const uint8array2packed = converters.__get__("uint8array2packed"); toPackedTestsBuilder(uint8array2packed, "uint8Array"); }); describe("Test arrayBuffer2packed", () => { const arraybuffer2packed = converters.__get__("arraybuffer2packed"); toPackedTestsBuilder(arraybuffer2packed, "arrayBuffer"); }); describe("Test bytes2packed", () => { const bytes2packed = converters.__get__("bytes2packed"), shortBytes = String.fromCharCode(1, 2, 3), longBytes = String.fromCharCode(1, 2, 3, 4, 5); it("3-Byte Input - No Existing Input", () => { assert.deepEqual(bytes2packed(shortBytes, undefined, undefined, -1), { value: [0x01020300], binLen: 24, }); }); it("5-Byte Input - No Existing Input", () => { assert.deepEqual(bytes2packed(longBytes, undefined, undefined, -1), { value: [0x01020304, 0x05000000], binLen: 40, }); }); it("3-Byte Input - Existing Input", () => { assert.deepEqual(bytes2packed(shortBytes, [0x05000000], 8, -1), { value: [0x05010203], binLen: 32, }); }); it("5-Byte Input - Existing Input", () => { assert.deepEqual(bytes2packed(longBytes, [0x06000000], 8, -1), { value: [0x06010203, 0x04050000], binLen: 48, }); }); it("3-Byte Input - No Existing Input with Endian Modifier", () => { assert.deepEqual(bytes2packed(shortBytes, undefined, undefined, 1), { value: [0x00030201], binLen: 24, }); }); it("5-Byte Input - No Existing Input with Endian Modifier", () => { assert.deepEqual(bytes2packed(longBytes, undefined, undefined, 1), { value: [0x04030201, 0x00000005], binLen: 40, }); }); it("3-Byte Input - Existing Input with Endian Modifier", () => { assert.deepEqual(bytes2packed(shortBytes, [0x00000004], 8, 1), { value: [0x03020104], binLen: 32, }); }); it("5-Byte Input - Existing Input with Endian Modifier", () => { assert.deepEqual(bytes2packed(longBytes, [0x00000006], 8, 1), { value: [0x03020106, 0x00000504], binLen: 48, }); }); }); describe("Test str2packed", () => { const str2packed = converters.__get__("str2packed"), toPackedTextTests = [ { name: "'ABCDE' Input", inputs: { string: "ABCDE", existing: [0x46470000], existingMod: [0x00004746], lengthExisting: 16, }, outputs: { utf8: [0x41424344, 0x45000000], utf8Mod: [0x44434241, 0x00000045], utf8Existing: [0x46474142, 0x43444500], lengthUtf8: 40, utf16le: [0x41004200, 0x43004400, 0x45000000], utf16leMod: [0x00420041, 0x00440043, 0x00000045], utf16leExisting: [0x46474100, 0x42004300, 0x44004500], utf16be: [0x00410042, 0x00430044, 0x00450000], utf16beMod: [0x42004100, 0x44004300, 0x00004500], utf16beExisting: [0x46470041, 0x00420043, 0x00440045], lengthUtf16: 80, }, }, { name: "U+00F1 Input (2 UTF-8 Bytes)", inputs: { string: "\u00F1", existing: [0x46470000], existingMod: [0x00004746], lengthExisting: 16, }, outputs: { utf8: [0xc3b10000 | 0], utf8Mod: [0x0000b1c3], utf8Existing: [0x4647c3b1], lengthUtf8: 16, utf16le: [0xf1000000 | 0], utf16leMod: [0x000000f1 | 0], utf16leExisting: [0x4647f100], utf16be: [0x00f10000], utf16beMod: [0x0000f100], utf16beExisting: [0x464700f1], lengthUtf16: 16, }, }, { name: "U+1E4D Input (3 UTF-8 Bytes)", inputs: { string: "\u1E4D", existing: [0x46470000], existingMod: [0x00004746], lengthExisting: 16, }, outputs: { utf8: [0xe1b98d00 | 0], utf8Mod: [0x008db9e1], utf8Existing: [0x4647e1b9, 0x8d000000 | 0], lengthUtf8: 24, utf16le: [0x4d1e0000], utf16leMod: [0x00001e4d], utf16leExisting: [0x46474d1e], utf16be: [0x1e4d0000], utf16beMod: [0x00004d1e], utf16beExisting: [0x46471e4d], lengthUtf16: 16, }, }, { name: "U+10348 Input (4 UTF-8 Bytes, 4 UTF-16 Bytes)", inputs: { string: "𐍈", existing: [0x46470000], existingMod: [0x00004746], lengthExisting: 16, }, outputs: { utf8: [0xf0908d88 | 0], utf8Mod: [0x888d90f0 | 0], utf8Existing: [0x4647f090, 0x8d880000 | 0], lengthUtf8: 32, utf16le: [0x00d848df], utf16leMod: [0xdf48d800 | 0], utf16leExisting: [0x464700d8, 0x48df0000], utf16be: [0xd800df48 | 0], utf16beMod: [0x48df00d8 | 0], utf16beExisting: [0x4647d800, 0xdf480000 | 0], lengthUtf16: 32, }, }, ]; toPackedTextTests.forEach((test) => { it(`${test.name} UTF8 - No Existing Input`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF8", undefined, undefined, -1), { value: test.outputs.utf8, binLen: test.outputs.lengthUtf8, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF8 - No Existing Input With Endian Modifier`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF8", undefined, undefined, 1), { value: test.outputs.utf8Mod, binLen: test.outputs.lengthUtf8, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF8 - Existing Input`, () => { assert.deepEqual( str2packed(test.inputs.string, "UTF8", test.inputs.existing.slice(), test.inputs.lengthExisting, -1), { value: test.outputs.utf8Existing, binLen: test.outputs.lengthUtf8 + test.inputs.lengthExisting, } ); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16LE - No Existing Input`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF16LE", undefined, undefined, -1), { value: test.outputs.utf16le, binLen: test.outputs.lengthUtf16, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16LE - No Existing Input with Endian Modifier`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF16LE", undefined, undefined, 1), { value: test.outputs.utf16leMod, binLen: test.outputs.lengthUtf16, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16LE - Existing Input`, () => { assert.deepEqual( str2packed(test.inputs.string, "UTF16LE", test.inputs.existing.slice(), test.inputs.lengthExisting, -1), { value: test.outputs.utf16leExisting, binLen: test.outputs.lengthUtf16 + test.inputs.lengthExisting, } ); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16BE - No Existing Input`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF16BE", undefined, undefined, -1), { value: test.outputs.utf16be, binLen: test.outputs.lengthUtf16, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16BE - No Existing Input with Endian Modifier`, () => { assert.deepEqual(str2packed(test.inputs.string, "UTF16BE", undefined, undefined, 1), { value: test.outputs.utf16beMod, binLen: test.outputs.lengthUtf16, }); }); }); toPackedTextTests.forEach((test) => { it(`${test.name} UTF16BE - Existing Input`, () => { assert.deepEqual( str2packed(test.inputs.string, "UTF16BE", test.inputs.existing.slice(), test.inputs.lengthExisting, -1), { value: test.outputs.utf16beExisting, binLen: test.outputs.lengthUtf16 + test.inputs.lengthExisting, } ); }); }); }); // Input value to be reused across all the packed2* tests const packedToInput = [0x00112233, 0xaabbccdd]; describe("Test packed2hex", () => { const packed2hex = converters.__get__("packed2hex"); it("16-bit Input", () => { assert.equal(packed2hex(packedToInput, 16, -1, { outputUpper: false }), "0011"); }); it("64-bit Input", () => { assert.equal(packed2hex(packedToInput, 64, -1, { outputUpper: false }), "00112233aabbccdd"); }); it("64-bit Input with Output Uppercase", () => { assert.equal(packed2hex(packedToInput, 64, -1, { outputUpper: true }), "00112233AABBCCDD"); }); it("16-bit Input with Endian Modifier", () => { assert.equal(packed2hex(packedToInput, 16, 1, { outputUpper: false }), "3322"); }); it("64-bit with Endian Modifier", () => { assert.equal(packed2hex(packedToInput, 64, 1, { outputUpper: false }), "33221100ddccbbaa"); }); }); describe("Test packed2b64", () => { const packed2b64 = converters.__get__("packed2b64"); it("8-bit Input", () => { assert.equal(packed2b64(packedToInput, 8, -1, { b64Pad: "=" }), "AA=="); }); it("16-bit Input", () => { assert.equal(packed2b64(packedToInput, 16, -1, { b64Pad: "=" }), "ABE="); }); it("64-bit Input", () => { assert.equal(packed2b64(packedToInput, 64, -1, { b64Pad: "=" }), "ABEiM6q7zN0="); }); it("64-bit Input with # Pad", () => { assert.equal(packed2b64(packedToInput, 64, -1, { b64Pad: "#" }), "ABEiM6q7zN0#"); }); it("16-bit Input with Endian Modifier", () => { assert.equal(packed2b64(packedToInput, 16, 1, { b64Pad: "=" }), "MyI="); }); it("64-bit with Endian Modifier", () => { assert.equal(packed2b64(packedToInput, 64, 1, { b64Pad: "=" }), "MyIRAN3Mu6o="); }); }); describe("Test packed2bytes", () => { const packed2bytes = converters.__get__("packed2bytes"); it("16-bit Input", () => { assert.equal(packed2bytes(packedToInput, 16, -1), String.fromCharCode(0, 0x11)); }); it("64-bit Input", () => { assert.equal(packed2bytes(packedToInput, 64, -1), String.fromCharCode(0, 0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc, 0xdd)); }); it("16-bit Input with Endian Modifier", () => { assert.equal(packed2bytes(packedToInput, 16, 1), String.fromCharCode(0x33, 0x22)); }); it("64-bit with Endian Modifier", () => { assert.equal(packed2bytes(packedToInput, 64, 1), String.fromCharCode(0x33, 0x22, 0x11, 0, 0xdd, 0xcc, 0xbb, 0xaa)); }); }); describe("Test packed2arraybuffer", () => { const packed2arraybuffer = converters.__get__("packed2arraybuffer"); it("16-bit Input", () => { assert.deepEqual(packed2arraybuffer(packedToInput, 16, -1), newArrayBuffer([0, 0x11])); }); it("64-bit Input", () => { assert.deepEqual( packed2arraybuffer(packedToInput, 64, -1), newArrayBuffer([0, 0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc, 0xdd]) ); }); it("16-bit Input with Endian Modifier", () => { assert.deepEqual(packed2arraybuffer(packedToInput, 16, 1), newArrayBuffer([0x33, 0x22])); }); it("64-bit with Endian Modifier", () => { assert.deepEqual( packed2arraybuffer(packedToInput, 64, 1), newArrayBuffer([0x33, 0x22, 0x11, 0, 0xdd, 0xcc, 0xbb, 0xaa]) ); }); }); describe("Test packed2uint8array", () => { const packed2uint8array = converters.__get__("packed2uint8array"); it("16-bit Input", () => { assert.deepEqual(packed2uint8array(packedToInput, 16, -1), Uint8Array.from([0, 0x11])); }); it("64-bit Input", () => { assert.deepEqual( packed2uint8array(packedToInput, 64, -1), Uint8Array.from([0, 0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc, 0xdd]) ); }); it("16-bit Input with Endian Modifier", () => { assert.deepEqual(packed2uint8array(packedToInput, 16, 1), Uint8Array.from([0x33, 0x22])); }); it("64-bit with Endian Modifier", () => { assert.deepEqual( packed2uint8array(packedToInput, 64, 1), Uint8Array.from([0x33, 0x22, 0x11, 0, 0xdd, 0xcc, 0xbb, 0xaa]) ); }); }); describe("Test packed2uint8array", () => { const packed2uint8array = converters.__get__("packed2uint8array"); it("16-bit Input", () => { assert.deepEqual(packed2uint8array(packedToInput, 16, -1), Uint8Array.from([0, 0x11])); }); it("64-bit Input", () => { assert.deepEqual( packed2uint8array(packedToInput, 64, -1), Uint8Array.from([0, 0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc, 0xdd]) ); }); it("16-bit Input with Endian Modifier", () => { assert.deepEqual(packed2uint8array(packedToInput, 16, 1), Uint8Array.from([0x33, 0x22])); }); it("64-bit with Endian Modifier", () => { assert.deepEqual( packed2uint8array(packedToInput, 64, 1), Uint8Array.from([0x33, 0x22, 0x11, 0, 0xdd, 0xcc, 0xbb, 0xaa]) ); }); }); describe("Test getStrConverter", () => { let revert, strConverter; // getStrConverter is actually exported but mixing rewire and sinon imports causes a node.js core dump const getStrConverter = converters.__get__("getStrConverter"), funcNameToInputValueMappings = [ { inputValue: "HEX", funcName: "hex2packed" }, { inputValue: "B64", funcName: "b642packed" }, { inputValue: "BYTES", funcName: "bytes2packed" }, { inputValue: "ARRAYBUFFER", funcName: "arraybuffer2packed" }, { inputValue: "UINT8ARRAY", funcName: "uint8array2packed" }, ]; funcNameToInputValueMappings.forEach((mapping) => { it(`${mapping.funcName} Mapping`, () => { const spy = sinon.spy(); revert = converters.__set__(mapping.funcName, spy); strConverter = getStrConverter(mapping.inputValue, "UTF8", -1); strConverter("00", [], 0); assert.isTrue(spy.calledWithExactly("00", [], 0, -1)); revert(); }); }); // Needed to be handled separately due to utf type being passed into eventual function it("str2packed Mapping", () => { const spy = sinon.spy(); converters.__with__({ str2packed: spy })(() => { strConverter = getStrConverter("TEXT", "UTF8", -1); strConverter("00", [], 0); assert.isTrue(spy.calledWithExactly("00", "UTF8", [], 0, -1)); }); }); it("Invalid UTF Exception", () => { assert.throws(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore - Deliberate bad UTF value to test exceptions getStrConverter("HEX", "UTF32", -1); }, "encoding must be UTF8, UTF16BE, or UTF16LE"); }); it("Invalid Input Type", () => { assert.throws(() => { getStrConverter("GARBAGE", "UTF8", -1); }, "format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY"); }); it("arraybuffer2packed Unsupported", () => { converters.__with__({ ArrayBuffer: sinon.stub().throws() })(() => { assert.throws(() => { getStrConverter("ARRAYBUFFER", "UTF8", -1); }, "ARRAYBUFFER not supported by this environment"); }); }); it("uint8array2packed Unsupported", () => { converters.__with__({ Uint8Array: sinon.stub().throws() })(() => { assert.throws(() => { getStrConverter("UINT8ARRAY", "UTF8", -1); }, "UINT8ARRAY not supported by this environment"); }); }); }); describe("Test getOutputConverter", () => { let spy, revert, outputConverter; // getOutputConverter is actually exported but mixing rewire and sinon imports causes a node.js core dump const getOutputConverter = converters.__get__("getOutputConverter"), funcNameToInputValueMappings = [ { inputValue: "HEX", funcName: "packed2hex", needsOptions: true }, { inputValue: "B64", funcName: "packed2b64", needsOptions: true }, { inputValue: "BYTES", funcName: "packed2bytes", needsOptions: false }, { inputValue: "ARRAYBUFFER", funcName: "packed2arraybuffer", needsOptions: false }, { inputValue: "UINT8ARRAY", funcName: "packed2uint8array", needsOptions: false }, ], options = { outputUpper: false, b64Pad: "", outputLen: -1 }; funcNameToInputValueMappings.forEach((mapping) => { it(`${mapping.funcName} Mapping`, () => { spy = sinon.spy(); revert = converters.__set__(mapping.funcName, spy); outputConverter = getOutputConverter(mapping.inputValue, 0, -1, options); outputConverter([0]); if (mapping.needsOptions === true) { assert.isTrue(spy.calledWithExactly([0], 0, -1, options)); } else { assert.isTrue(spy.calledWithExactly([0], 0, -1)); } revert(); }); }); it("Invalid Input Type", () => { assert.throws(() => { getOutputConverter("GARBAGE", -1, -1, options); }, "HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY"); }); it("arraybuffer2packed Unsupported", () => { converters.__with__({ ArrayBuffer: sinon.stub().throws() })(() => { assert.throws(() => { getOutputConverter("ARRAYBUFFER", 0, -1, options); }, "ARRAYBUFFER not supported by this environment"); }); }); it("uint8array2packed Unsupported", () => { converters.__with__({ Uint8Array: sinon.stub().throws() })(() => { assert.throws(() => { getOutputConverter("UINT8ARRAY", 0, -1, options); }, "UINT8ARRAY not supported by this environment"); }); }); });
the_stack
import * as React from "react"; import { Dict, isFunction, objectKeys } from "@chakra-ui/utils"; import { createToastStore, DefaultToastOptions, TimerToast, useToastTimer, } from "../../index"; export interface Toast extends TimerToast { content?: Content; placement: ToastPlacement; } export type Renderable = JSX.Element | string | number | null; export type ValueFunction<Value, Arg> = (arg: Arg) => Value; export type ValueOrFunction<Value, Arg> = Value | ValueFunction<Value, Arg>; export type ContentType = { toast: Toast; handlers: useToastsReturnType; }; export type Content = ValueOrFunction<Renderable, ContentType> | Dict; export type ToastPlacement = | "top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right"; /* ========================================================================= Toast Provider ========================================================================== */ const defaultOptions: DefaultToastOptions<Toast> = { animationDuration: 300, pausedAt: null, pauseDuration: 0, placement: "bottom-center", autoDismiss: false, dismissDuration: 3000, }; const [ToastProvider, useToastStore, useCreateToast, useToastHandlers] = createToastStore<Toast, Content>(defaultOptions); export { ToastProvider, useCreateToast, useToastHandlers, useToastStore }; /* ========================================================================= ToastBarHelpers ========================================================================== */ export const useToasts = () => { const { toasts } = useToastStore(); const { updateToast, removeToast, ...restHanlders } = useToastHandlers(); const visibleToasts = toasts.filter(t => t.visible); const sortedToasts = getPlacementSortedToasts(toasts); const timerHandlers = useToastTimer(visibleToasts, updateToast, removeToast); return { toasts: sortedToasts, ...timerHandlers, removeToast, ...restHanlders, }; }; export type useToastsReturnType = ReturnType<typeof useToasts>; /* ========================================================================= Components - Trigger ========================================================================== */ export const TriggerButton: React.FC< React.HTMLAttributes<HTMLButtonElement> > = props => { const { style, ...rest } = props; return ( <button style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: "auto", height: "1rem", minWidth: "1rem", paddingTop: "1rem", paddingBottom: "1rem", paddingRight: "0.5rem", paddingLeft: "0.5rem", fontSize: "14px", lineHeight: "20px", fontWeight: 500, boxShadow: "none", border: "none", color: "white", verticalAlign: "middle", transition: "all 0.3s ease", background: "black", borderRadius: "6px", appearance: "none", whiteSpace: "nowrap", marginTop: "0.5rem", marginBottom: "0.5rem", cursor: "pointer", ...style, }} {...rest} /> ); }; const contents = [ "Amet soufflé carrot cake tootsie roll jelly-o chocolate cake.", "Chocolate bar gummies sweet roll macaroon powder sweet tart croissant.", "Pastry ice cream bear claw cupcake topping caramels jelly beans chocolate cheesecake.", "Candy canes pastry cake tart powder.", "Tootsie roll bear claw sesame snaps candy cheesecake caramels cookie.", "Lemon drops donut marzipan gummi bears cotton candy cotton candy jelly-o carrot cake.", "Lemon drops pastry apple pie biscuit tart tootsie roll.", "Brownie icing chupa chups cake cookie halvah gummi bears halvah.", "Sesame snaps donut gingerbread marshmallow topping powder.", "Biscuit chocolate cheesecake pudding candy canes tart halvah sweet.", "Sugar plum cake candy carrot cake.", "Ice cream marzipan liquorice candy canes sesame snaps danish soufflé lollipop candy canes.", "Lemon drops cotton candy pudding.", "Pie cake soufflé cupcake jujubes sugar plum.", "Liquorice lollipop oat cake.", ]; const types = ["info", "success", "warning", "error"]; const placements = [ { placement: "top-left", reverseOrder: false }, { placement: "top-center", reverseOrder: false }, { placement: "top-right", reverseOrder: false }, { placement: "bottom-left", reverseOrder: true }, { placement: "bottom-center", reverseOrder: true }, { placement: "bottom-right", reverseOrder: true }, ]; export function getRandomItems(items: any) { const index = Math.floor(Math.random() * items.length); return items[index]; } export function getRandomContent() { return getRandomItems(contents); } export function getRandomType() { return getRandomItems(types); } export function getRandomPlacement() { return getRandomItems(placements); } /* ========================================================================= Components - Alert ========================================================================== */ export const ToastBar = () => { const handlers = useToasts(); const { toasts } = handlers; return ( <> {objectKeys(toasts).map(placement => { const toastsList = toasts[placement]; return ( <ToastContainer key={placement} placement={placement}> {toastsList.map(toast => { const { content } = toast; return ( <React.Fragment key={toast.id}> {isFunction(content) ? content({ toast, handlers }) : content} </React.Fragment> ); })} </ToastContainer> ); })} </> ); }; const placememtStyles = { "top-left": { top: 10, left: 20 }, "top-center": { top: 10, left: "50%", transform: "translateX(-50%)" }, "top-right": { top: 10, right: 20 }, "bottom-left": { bottom: 10, left: 20 }, "bottom-center": { bottom: 10, left: "50%", transform: "translateX(-50%)" }, "bottom-right": { bottom: 10, right: 20 }, }; export const ToastContainer: React.FC<Pick<Toast, "placement">> = props => { const { placement, ...rest } = props; return ( <div style={{ boxSizing: "border-box", maxHeight: "100%", maxWidth: "100%", position: "fixed", zIndex: 9999, ...placememtStyles[placement], }} {...rest} /> ); }; function getTranslate(placement: ToastPlacement) { const pos = placement.split("-"); const relevantPlacement = pos[1] === "center" ? pos[0] : pos[1]; const translateMap = { right: "translate3d(120%, 0, 0)", left: "translate3d(-120%, 0, 0)", bottom: "translate3d(0, 120%, 0)", top: "translate3d(0, -120%, 0)", }; return translateMap[relevantPlacement]; } export const ToastWrapper: React.FC<{ toast: Toast }> = props => { const { toast, children } = props; const ref = React.useRef<HTMLDivElement>(null); return ( <div ref={ref} style={{ transition: "all 0.3s ease", transform: toast.visible ? "translate3d(0,0,0)" : getTranslate(toast.placement), opacity: toast.visible ? 1 : 0, }} > {children} </div> ); }; // Styles from https://jossmac.github.io/react-toast-notifications/ export type AlertType = "info" | "success" | "error" | "warning"; export const Alert: React.FC< React.HTMLAttributes<HTMLDivElement> & { toast: Toast; hideToast: (toastId: string) => void; type?: AlertType; content: any; } > = props => { const { toast, type = "info", content, hideToast, children, ...rest } = props; return ( <AlertWrapper type={type} {...rest}> {children} <AlertContent>{content}</AlertContent> <CloseButton toast={toast} hideToast={hideToast} /> </AlertWrapper> ); }; const typeStyles = { info: { bg: "white", color: "rgb(80, 95, 121)", indicator: "rgb(38, 132, 255)", }, success: { bg: "rgb(227, 252, 239)", color: "rgb(0, 102, 68)", indicator: "rgb(54, 179, 126)", }, error: { bg: "rgb(255, 235, 230)", color: "rgb(191, 38, 0)", indicator: "rgb(255, 86, 48)", }, warning: { bg: "rgb(255, 250, 230)", color: "rgb(255, 139, 0)", indicator: "rgb(255, 171, 0)", }, }; export const AlertWrapper: React.FC< React.HTMLAttributes<HTMLDivElement> & { type: AlertType } > = props => { const { type, ...rest } = props; return ( <div role="alert" style={{ display: "flex", width: "360px", padding: "8px", backgroundColor: typeStyles[type].bg, color: typeStyles[type].color, borderRadius: "4px", marginBottom: "20px", boxShadow: "rgb(0 0 0 / 18%) 0px 3px 8px", }} {...rest} /> ); }; export const AlertIndicator: React.FC<{ toast: Toast; type?: AlertType; }> = props => { const { toast, type = "info", ...rest } = props; return ( <div style={{ backgroundColor: typeStyles[type].indicator, borderTopLeftRadius: "4px", borderBottomLeftRadius: "4px", color: "rgb(227, 252, 239)", flexShrink: 0, paddingBottom: "8px", paddingTop: "8px", position: "relative", overflow: "hidden", textAlign: "center", width: "4px", borderRadius: "4px", }} {...rest} > <div style={{ animation: `shrink ${toast.dismissDuration}ms linear`, animationPlayState: toast.pausedAt ? "paused" : "running", backgroundColor: "rgba(0,0,0,0.1)", bottom: 0, height: 0, left: 0, opacity: toast.autoDismiss ? 1 : 0, position: "absolute", width: "100%", }} ></div> </div> ); }; export const AlertContent: React.FC<{}> = props => { return ( <div style={{ flexGrow: 1, lineHeight: 1.5, padding: "8px" }} {...props} /> ); }; export const CloseButton: React.FC<{ toast: Toast; hideToast: (toastId: string) => void; }> = props => { const { toast, hideToast, ...rest } = props; return ( <TriggerButton style={{ cursor: "pointer", flexShrink: 0, background: "transparent", color: "black", alignSelf: "center", }} onClick={() => hideToast(toast.id)} {...rest} > <CloseIcon /> <div className="sr-only">Close</div> </TriggerButton> ); }; export const CloseIcon: React.FC<{}> = props => { return ( <svg aria-hidden="true" height="20" width="20" viewBox="0 0 14 16" style={{ display: "inline-block", verticalAlign: "text-top", fill: "currentcolor", }} {...props} > <path fillRule="evenodd" d="M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z" /> </svg> ); }; /* ========================================================================= Helpers ========================================================================== */ export type SortedToastList = Record<ToastPlacement, Toast[]>; export const getPlacementSortedToasts = (toasts: Toast[]) => toasts.reduce((acc, curr) => { if (!acc[curr.placement]) acc[curr.placement] = []; acc[curr.placement].push(curr); return acc; }, {} as SortedToastList);
the_stack
import { expect } from 'chai'; import { simulate } from 'simulate-event'; import { CommandRegistry } from '@phosphor/commands'; import { Platform } from '@phosphor/domutils'; import { MessageLoop } from '@phosphor/messaging'; import { VirtualDOM, h } from '@phosphor/virtualdom'; import { CommandPalette, Widget } from '@phosphor/widgets'; class LogPalette extends CommandPalette { events: string[] = []; handleEvent(event: Event): void { super.handleEvent(event); this.events.push(event.type); } } const defaultOptions: CommandPalette.IItemOptions = { command: 'test', category: 'Test Category', args: { foo: 'bar' }, rank: 42 } describe('@phosphor/widgets', () => { let commands: CommandRegistry; let palette: CommandPalette; beforeEach(() => { commands = new CommandRegistry(); palette = new CommandPalette({ commands }); }); afterEach(() => { palette.dispose(); }); describe('CommandPalette', () => { describe('#constructor()', () => { it('should accept command palette instantiation options', () => { expect(palette).to.be.an.instanceof(CommandPalette); expect(palette.node.classList.contains('p-CommandPalette')).to.equal(true); }); }); describe('#dispose()', () => { it('should dispose of the resources held by the command palette', () => { palette.addItem(defaultOptions); palette.dispose(); expect(palette.items.length).to.equal(0); expect(palette.isDisposed).to.equal(true); }); }); describe('#commands', () => { it('should get the command registry for the command palette', () => { expect(palette.commands).to.equal(commands); }); }); describe('#renderer', () => { it('should default to the default renderer', () => { expect(palette.renderer).to.equal(CommandPalette.defaultRenderer); }); }); describe('#searchNode', () => { it('should return the search node of a command palette', () => { expect(palette.searchNode.classList.contains('p-CommandPalette-search')).to.equal(true); }); }); describe('#inputNode', () => { it('should return the input node of a command palette', () => { expect(palette.inputNode.classList.contains('p-CommandPalette-input')).to.equal(true); }); }); describe('#contentNode', () => { it('should return the content node of a command palette', () => { expect(palette.contentNode.classList.contains('p-CommandPalette-content')).to.equal(true); }); }); describe('#items', () => { it('should be a read-only array of the palette items', () => { expect(palette.items.length).to.equal(0); palette.addItem(defaultOptions); expect(palette.items.length).to.equal(1); expect(palette.items[0].command).to.equal('test'); }); }); describe('#addItem()', () => { it('should add an item to a command palette using options', () => { expect(palette.items.length).to.equal(0); palette.addItem(defaultOptions); expect(palette.items.length).to.equal(1); expect(palette.items[0].command).to.equal('test'); }); context('CommandPalette.IItem', () => { describe('#command', () => { it('should return the command name of a command item', () => { let item = palette.addItem(defaultOptions); expect(item.command).to.equal('test'); }); }); describe('#args', () => { it('should return the args of a command item', () => { let item = palette.addItem(defaultOptions); expect(item.args).to.deep.equal(defaultOptions.args); }); it('should default to an empty object', () => { let item = palette.addItem({ command: 'test', category: 'test' }); expect(item.args).to.deep.equal({}); }); }); describe('#category', () => { it('should return the category of a command item', () => { let item = palette.addItem(defaultOptions); expect(item.category).to.equal(defaultOptions.category); }); }); describe('#rank', () => { it('should return the rank of a command item', () => { let item = palette.addItem(defaultOptions); expect(item.rank).to.deep.equal(defaultOptions.rank); }); it('should default to `Infinity`', () => { let item = palette.addItem({ command: 'test', category: 'test' }); expect(item.rank).to.equal(Infinity); }); }); describe('#label', () => { it('should return the label of a command item', () => { let label = 'test label'; commands.addCommand('test', { execute: () => { }, label }); let item = palette.addItem(defaultOptions); expect(item.label).to.equal(label); }); }); describe('#caption', () => { it('should return the caption of a command item', () => { let caption = 'test caption'; commands.addCommand('test', { execute: () => { }, caption }); let item = palette.addItem(defaultOptions); expect(item.caption).to.equal(caption); }); }); describe('#className', () => { it('should return the class name of a command item', () => { let className = 'testClass'; commands.addCommand('test', { execute: () => { }, className }); let item = palette.addItem(defaultOptions); expect(item.className).to.equal(className); }); }); describe('#isEnabled', () => { it('should return whether a command item is enabled', () => { let called = false; commands.addCommand('test', { execute: () => { }, isEnabled: () => { called = true; return false; } }); let item = palette.addItem(defaultOptions); expect(called).to.equal(false); expect(item.isEnabled).to.equal(false); expect(called).to.equal(true); }); }); describe('#isToggled', () => { it('should return whether a command item is toggled', () => { let called = false; commands.addCommand('test', { execute: () => { }, isToggled: () => { called = true; return true; } }); let item = palette.addItem(defaultOptions); expect(called).to.equal(false); expect(item.isToggled).to.equal(true); expect(called).to.equal(true); }); }); describe('#isVisible', () => { it('should return whether a command item is visible', () => { let called = false; commands.addCommand('test', { execute: () => { }, isVisible: () => { called = true; return false; } }); let item = palette.addItem(defaultOptions); expect(called).to.equal(false); expect(item.isVisible).to.equal(false); expect(called).to.equal(true); }); }); describe('#keyBinding', () => { it('should return the key binding of a command item', () => { commands.addKeyBinding({ keys: ['Ctrl A'], selector: 'body', command: 'test', args: defaultOptions.args }); let item = palette.addItem(defaultOptions); expect(item.keyBinding!.keys).to.deep.equal(['Ctrl A']); }); }); }); }); describe('#removeItem()', () => { it('should remove an item from a command palette by item', () => { expect(palette.items.length).to.equal(0); let item = palette.addItem(defaultOptions); expect(palette.items.length).to.equal(1); palette.removeItem(item); expect(palette.items.length).to.equal(0); }); }); describe('#removeItemAt()', () => { it('should remove an item from a command palette by index', () => { expect(palette.items.length).to.equal(0); palette.addItem(defaultOptions); expect(palette.items.length).to.equal(1); palette.removeItemAt(0); expect(palette.items.length).to.equal(0); }); }); describe('#clearItems()', () => { it('should remove all items from a command palette', () => { expect(palette.items.length).to.equal(0); palette.addItem({ command: 'test', category: 'one' }); palette.addItem({ command: 'test', category: 'two' }); expect(palette.items.length).to.equal(2); palette.clearItems(); expect(palette.items.length).to.equal(0); }); }); describe('#refresh()', () => { it('should schedule a refresh of the search items', () => { commands.addCommand('test', { execute: () => { }, label: 'test' }); palette.addItem(defaultOptions); MessageLoop.flush(); let content = palette.contentNode; let itemClass = '.p-CommandPalette-item'; let items = () => content.querySelectorAll(itemClass); expect(items()).to.have.length(1); palette.inputNode.value = 'x'; palette.refresh(); MessageLoop.flush(); expect(items()).to.have.length(0); }); }); describe('#handleEvent()', () => { it('should handle click, keydown, and input events', () => { let palette = new LogPalette({ commands }); Widget.attach(palette, document.body); ['click', 'keydown', 'input'].forEach(type => { simulate(palette.node, type); expect(palette.events).to.contain(type); }); palette.dispose(); }); context('click', () => { it('should trigger a command when its item is clicked', () => { let called = false; commands.addCommand('test', { execute: () => called = true }); palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); let node = palette.contentNode.querySelector('.p-CommandPalette-item')!; simulate(node, 'click'); expect(called).to.equal(true); }); it('should ignore the event if it is not a left click', () => { let called = false; commands.addCommand('test', { execute: () => called = true }); palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); let node = palette.contentNode.querySelector('.p-CommandPalette-item')!; simulate(node, 'click', { button: 1 }); expect(called).to.equal(false); }); }); context('keydown', () => { it('should navigate down if down arrow is pressed', () => { commands.addCommand('test', { execute: () => { } }); let content = palette.contentNode; palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); let node = content.querySelector('.p-mod-active'); expect(node).to.equal(null); simulate(palette.node, 'keydown', { keyCode: 40 }); // Down arrow MessageLoop.flush(); node = content.querySelector('.p-CommandPalette-item.p-mod-active'); expect(node).to.not.equal(null); }); it('should navigate up if up arrow is pressed', () => { commands.addCommand('test', { execute: () => { } }); let content = palette.contentNode; palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); let node = content.querySelector('.p-mod-active'); expect(node).to.equal(null); simulate(palette.node, 'keydown', { keyCode: 38 }); // Up arrow MessageLoop.flush(); node = content.querySelector('.p-CommandPalette-item.p-mod-active'); expect(node).to.not.equal(null); }); it('should ignore if modifier keys are pressed', () => { let called = false; commands.addCommand('test', { execute: () => called = true }); let content = palette.contentNode; palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); let node = content.querySelector('.p-mod-active'); expect(node).to.equal(null); ['altKey', 'ctrlKey', 'shiftKey', 'metaKey'].forEach(key => { let options: any = { keyCode: 38 }; options[key] = true; simulate(palette.node, 'keydown', options); node = content.querySelector('.p-CommandPalette-item.p-mod-active'); expect(node).to.equal(null); }); }); it('should trigger active item if enter is pressed', () => { let called = false; commands.addCommand('test', { execute: () => called = true }); let content = palette.contentNode; palette.addItem(defaultOptions); Widget.attach(palette, document.body); MessageLoop.flush(); expect(content.querySelector('.p-mod-active')).to.equal(null); simulate(palette.node, 'keydown', { keyCode: 40 }); // Down arrow simulate(palette.node, 'keydown', { keyCode: 13 }); // Enter expect(called).to.equal(true); }); }); context('input', () => { it('should filter the list of visible items', () => { ['A', 'B', 'C', 'D', 'E'].forEach(name => { commands.addCommand(name, { execute: () => { }, label: name }); palette.addItem({ command: name, category: 'test' }); }); Widget.attach(palette, document.body); MessageLoop.flush(); let content = palette.contentNode; let itemClass = '.p-CommandPalette-item'; let items = () => content.querySelectorAll(itemClass); expect(items()).to.have.length(5); palette.inputNode.value = 'A'; palette.refresh(); MessageLoop.flush(); expect(items()).to.have.length(1); }); it('should filter by both text and category', () => { let categories = ['Z', 'Y']; let names = [ ['A1', 'B2', 'C3', 'D4', 'E5'], ['F1', 'G2', 'H3', 'I4', 'J5'] ]; names.forEach((values, index) => { values.forEach(command => { palette.addItem({ command, category: categories[index] }); commands.addCommand(command, { execute: () => { }, label: command }); }); }); Widget.attach(palette, document.body); MessageLoop.flush(); let headers = () => palette.node.querySelectorAll('.p-CommandPalette-header'); let items = () => palette.node.querySelectorAll('.p-CommandPalette-item'); let input = (value: string) => { palette.inputNode.value = value; palette.refresh(); MessageLoop.flush(); }; expect(items()).to.have.length(10); input(`${categories[1]}`); // Category match expect(items()).to.have.length(5); input(`${names[1][0]}`); // Label match expect(items()).to.have.length(1); input(`${categories[1]} B`); // No match expect(items()).to.have.length(0); input(`${categories[1]} I`); // Category and text match expect(items()).to.have.length(1); input('1'); // Multi-category match expect(headers()).to.have.length(2); expect(items()).to.have.length(2); }); }); }); describe('.Renderer', () => { let renderer = new CommandPalette.Renderer(); let item: CommandPalette.IItem = null!; let enabledFlag = true; let toggledFlag = false; beforeEach(() => { enabledFlag = true; toggledFlag = false; commands.addCommand('test', { label: 'Test Command', caption: 'A simple test command', className: 'testClass', isEnabled: () => enabledFlag, isToggled: () => toggledFlag, execute: () => { } }); commands.addKeyBinding({ command: 'test', keys: ['Ctrl A'], selector: 'body' }); item = palette.addItem({ command: 'test', category: 'Test Category' }); }); describe('#renderHeader()', () => { it('should render a header node for the palette', () => { let vNode = renderer.renderHeader({ category: 'Test Category', indices: null }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-header')).to.equal(true); expect(node.innerHTML).to.equal('Test Category'); }); it('should mark the matching indices', () => { let vNode = renderer.renderHeader({ category: 'Test Category', indices: [1, 2, 6, 7, 8] }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-header')).to.equal(true); expect(node.innerHTML).to.equal('T<mark>es</mark>t C<mark>ate</mark>gory'); }); }); describe('#renderItem()', () => { it('should render an item node for the palette', () => { let vNode = renderer.renderItem({ item, indices: null, active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-item')).to.equal(true); expect(node.classList.contains('p-mod-disabled')).to.equal(false); expect(node.classList.contains('p-mod-toggled')).to.equal(false); expect(node.classList.contains('p-mod-active')).to.equal(false); expect(node.classList.contains('testClass')).to.equal(true); expect(node.getAttribute('data-command')).to.equal('test'); expect(node.querySelector('.p-CommandPalette-itemShortcut')).to.not.equal(null); expect(node.querySelector('.p-CommandPalette-itemLabel')).to.not.equal(null); expect(node.querySelector('.p-CommandPalette-itemCaption')).to.not.equal(null); }); it('should handle the disabled item state', () => { enabledFlag = false; let vNode = renderer.renderItem({ item, indices: null, active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-mod-disabled')).to.equal(true); }); it('should handle the toggled item state', () => { toggledFlag = true; let vNode = renderer.renderItem({ item, indices: null, active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-mod-toggled')).to.equal(true); }); it('should handle the active state', () => { let vNode = renderer.renderItem({ item, indices: null, active: true }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-mod-active')).to.equal(true); }); }); describe('#renderEmptyMessage()', () => { it('should render an empty message node for the palette', () => { let vNode = renderer.renderEmptyMessage({ query: 'foo' }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-emptyMessage')).to.equal(true); expect(node.innerHTML).to.equal("No commands found that match 'foo'"); }); }); describe('#renderItemShortcut()', () => { it('should render an item shortcut node', () => { let vNode = renderer.renderItemShortcut({ item, indices: null, active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-itemShortcut')).to.equal(true); if (Platform.IS_MAC) { expect(node.innerHTML).to.equal('\u2303 A'); } else { expect(node.innerHTML).to.equal('Ctrl+A'); } }); }); describe('#renderItemLabel()', () => { it('should render an item label node', () => { let vNode = renderer.renderItemLabel({ item, indices: [1, 2, 3], active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-itemLabel')).to.equal(true); expect(node.innerHTML).to.equal('T<mark>est</mark> Command'); }); }); describe('#renderItemCaption()', () => { it('should render an item caption node', () => { let vNode = renderer.renderItemCaption({ item, indices: null, active: false }); let node = VirtualDOM.realize(vNode); expect(node.classList.contains('p-CommandPalette-itemCaption')).to.equal(true); expect(node.innerHTML).to.equal('A simple test command'); }); }); describe('#createItemClass()', () => { it('should create the full class name for the item node', () => { let name = renderer.createItemClass({ item, indices: null, active: false }); expect(name).to.equal('p-CommandPalette-item testClass'); }); it('should handle the boolean states', () => { enabledFlag = false; toggledFlag = true; let name = renderer.createItemClass({ item, indices: null, active: true }); expect(name).to.equal('p-CommandPalette-item p-mod-disabled p-mod-toggled p-mod-active testClass'); }); }); describe('#createItemDataset()', () => { it('should create the item dataset', () => { let dataset = renderer.createItemDataset({ item, indices: null, active: false }); expect(dataset).to.deep.equal({ command: 'test' }); }); }); describe('#formatHeader()', () => { it('should format unmatched header content', () => { let child1 = renderer.formatHeader({ category: 'Test Category', indices: null }); let child2 = renderer.formatHeader({ category: 'Test Category', indices: [] }); expect(child1).to.equal('Test Category'); expect(child2).to.equal('Test Category'); }); it('should format matched header content', () => { let child = renderer.formatHeader({ category: 'Test Category', indices: [1, 2, 6, 7, 8] }); let node = VirtualDOM.realize(h.div(child)); expect(node.innerHTML).to.equal('T<mark>es</mark>t C<mark>ate</mark>gory'); }); }); describe('#formatEmptyMessage()', () => { it('should format the empty message text', () => { let child = renderer.formatEmptyMessage({ query: 'foo' }); expect(child).to.equal("No commands found that match 'foo'"); }); }); describe('#formatItemShortcut()', () => { it('should format the item shortcut text', () => { let child = renderer.formatItemShortcut({ item, indices: null, active: false }); if (Platform.IS_MAC) { expect(child).to.equal('\u2303 A'); } else { expect(child).to.equal('Ctrl+A'); } }); }); describe('#formatItemLabel()', () => { it('should format unmatched label content', () => { let child1 = renderer.formatItemLabel({ item, indices: null, active: false }); let child2 = renderer.formatItemLabel({ item, indices: [], active: false }); expect(child1).to.equal('Test Command'); expect(child2).to.equal('Test Command'); }); it('should format matched label content', () => { let child = renderer.formatItemLabel({ item, indices: [1, 2, 3], active: false }); let node = VirtualDOM.realize(h.div(child)); expect(node.innerHTML).to.equal('T<mark>est</mark> Command'); }); }); describe('#formatItemCaption()', () => { it('should format the item caption text', () => { let child = renderer.formatItemCaption({ item, indices: null, active: false }); expect(child).to.equal('A simple test command'); }); }); }); }); });
the_stack
import * as React from 'react'; import { View, Animated, Dimensions, TouchableWithoutFeedback, StyleSheet, ViewStyle, ImageStyle, } from 'react-native'; import { Navigation, Layout } from '../../react-native-navigation'; /* Utils - Project Utilities */ import { listen, dispatch } from './events'; enum DirectionType { left = 'left', right = 'right', bottom = 'bottom', top = 'top', } interface IState { sideMenuOpenValue: any; sideMenuOverlayOpacity: any; sideMenuSwipingStarted: boolean; sideMenuIsDismissing: boolean; } interface IProps { /** react-native-navigation */ componentId: string; /** Props */ animationOpenTime: number; animationCloseTime: number; direction: DirectionType; dismissWhenTouchOutside: boolean; fadeOpacity: number; drawerScreenWidth: number | string; drawerScreenHeight: number | string; style: any; } interface HOCProps { Component: React.ComponentType; } interface StylesInterface { sideMenuContainerStyle: ViewStyle; sideMenuOverlayStyle: ImageStyle; } interface DrawerDirectionValuesInterface { [key: string]: number; left: number; right: number; top: number; bottom: number; } interface DrawerReverseDirectionInterface { [key: string]: string; left: string; right: string; } interface SwipeMoveInterface { value: number; direction: string; } class RNNDrawer { static create(Component: React.ComponentType): any { class WrappedDrawer extends React.Component<IProps, IState> { private readonly screenWidth: number; private readonly screenHeight: number; private readonly drawerWidth: number; private readonly drawerHeight: number; private readonly drawerOpenedValues: DrawerDirectionValuesInterface; private animatedDrawer: any; private animatedOpacity: any; private unsubscribeSwipeStart: any; private unsubscribeSwipeMove: any; private unsubscribeSwipeEnd: any; private unsubscribeDismissDrawer: any; static defaultProps = { animationOpenTime: 300, animationCloseTime: 300, direction: 'left', dismissWhenTouchOutside: true, fadeOpacity: 0.6, drawerScreenWidth: '80%', drawerScreenHeight: '100%', }; /** * [ Built-in React method. ] * * Setup the component. Executes when the component is created * * @param {object} props */ constructor(props: IProps) { super(props); this.screenWidth = Dimensions.get('window').width; this.screenHeight = Dimensions.get('window').height; /* * We need to convert the pushed drawer width * to a number as it can either be a string ('20%') * or number (400). */ const _resolveDrawerSize = ( value: number | string, max: number, ): number => { /* * If the type is a string '%' then it should be a percentage relative * to our max size. */ if (typeof value === 'string') { const valueAsNumber = parseFloat(value as string) || 100; const size = max * (valueAsNumber / 100); return size; } return value; }; /** Component Variables */ this.drawerWidth = _resolveDrawerSize( props.drawerScreenWidth, this.screenWidth, ); this.drawerHeight = _resolveDrawerSize( props.drawerScreenHeight, this.screenHeight, ); this.drawerOpenedValues = { left: 0, right: this.screenWidth - this.drawerWidth, top: 0, bottom: this.screenHeight - this.drawerHeight, }; const initialValues: DrawerDirectionValuesInterface = { left: -this.drawerWidth, right: this.screenWidth, top: -this.drawerHeight, bottom: this.screenHeight, }; /** Component State */ this.state = { sideMenuOpenValue: new Animated.Value(initialValues[props.direction]), sideMenuOverlayOpacity: new Animated.Value(0), sideMenuSwipingStarted: false, sideMenuIsDismissing: false, }; /** Component Bindings */ this.touchedOutside = this.touchedOutside.bind(this); this.dismissDrawerWithAnimation = this.dismissDrawerWithAnimation.bind( this, ); this.registerListeners = this.registerListeners.bind(this); this.removeListeners = this.removeListeners.bind(this); Navigation.events().bindComponent(this); } /** * [ Built-in React method. ] * * Executed when the component is mounted to the screen */ componentDidMount() { /** Props */ const { direction, fadeOpacity } = this.props; // Animate side menu open this.animatedDrawer = Animated.timing(this.state.sideMenuOpenValue, { toValue: this.drawerOpenedValues[direction], duration: this.props.animationOpenTime, useNativeDriver: false, }); // Animate outside side menu opacity this.animatedOpacity = Animated.timing( this.state.sideMenuOverlayOpacity, { toValue: fadeOpacity, duration: this.props.animationOpenTime, useNativeDriver: false, }, ); } /** * [ react-native-navigation method. ] * * Executed when the component is navigated to view. */ componentDidAppear() { this.registerListeners(); // If there has been no Swiping, and this component appears, then just start the open animations if (!this.state.sideMenuSwipingStarted) { this.animatedDrawer.start(); this.animatedOpacity.start(); } } /** * [ react-native-navigation method. ] * * Executed when the component is navigated away from view. */ componentDidDisappear() { this.removeListeners(); dispatch('DRAWER_CLOSED'); } /** * Registers all the listenrs for this component */ registerListeners() { /** Props */ const { direction, fadeOpacity } = this.props; // Executes when the side of the screen interaction starts this.unsubscribeSwipeStart = listen('SWIPE_START', () => { this.setState({ sideMenuSwipingStarted: true, }); }); // Executes when the side of the screen is interacted with this.unsubscribeSwipeMove = listen( 'SWIPE_MOVE', ({ value, direction: swipeDirection }: SwipeMoveInterface) => { if (swipeDirection === 'left') { // Calculates the position of the drawer from the left side of the screen const alignedMovementValue = value - this.drawerWidth; // Calculates the percetage 0 - 100 of which the drawer is open const openedPercentage = Math.abs( (Math.abs(alignedMovementValue) / this.drawerWidth) * 100 - 100, ); // Calculates the opacity to set of the screen based on the percentage the drawer is open const normalizedOpacity = Math.min( openedPercentage / 100, fadeOpacity, ); // Does allow the drawer to go further than the maximum width if (this.drawerOpenedValues[direction] > alignedMovementValue) { // Sets the animation values, we use this so we can resume animation from any point this.state.sideMenuOpenValue.setValue(alignedMovementValue); this.state.sideMenuOverlayOpacity.setValue(normalizedOpacity); } } else if (swipeDirection === 'right') { // Works out the distance from right of screen to the finger position const normalizedValue = this.screenWidth - value; // Calculates the position of the drawer from the left side of the screen const alignedMovementValue = this.screenWidth - normalizedValue; // Calculates the percetage 0 - 100 of which the drawer is open const openedPercentage = Math.abs( (Math.abs(normalizedValue) / this.drawerWidth) * 100, ); // Calculates the opacity to set of the screen based on the percentage the drawer is open const normalizedOpacity = Math.min( openedPercentage / 100, fadeOpacity, ); // Does allow the drawer to go further than the maximum width if (this.drawerOpenedValues[direction] < alignedMovementValue) { // Sets the animation values, we use this so we can resume animation from any point this.state.sideMenuOpenValue.setValue(alignedMovementValue); this.state.sideMenuOverlayOpacity.setValue(normalizedOpacity); } } }, ); // Executes when the side of the screen interaction ends this.unsubscribeSwipeEnd = listen( 'SWIPE_END', (swipeDirection: string) => { const reverseDirection: DrawerReverseDirectionInterface = { right: 'left', left: 'right', }; if (swipeDirection === reverseDirection[direction]) { this.animatedDrawer.start(); this.animatedOpacity.start(); } else { if (!this.state.sideMenuIsDismissing) { this.setState( { sideMenuIsDismissing: true, }, () => { this.dismissDrawerWithAnimation(); }, ); } } }, ); // Executes when the drawer needs to be dismissed this.unsubscribeDismissDrawer = listen('DISMISS_DRAWER', () => { if (!this.state.sideMenuIsDismissing) { this.dismissDrawerWithAnimation(); } }); } /** * Removes all the listenrs from this component */ removeListeners() { if (this.unsubscribeSwipeStart) this.unsubscribeSwipeStart(); if (this.unsubscribeSwipeMove) this.unsubscribeSwipeMove(); if (this.unsubscribeSwipeEnd) this.unsubscribeSwipeEnd(); if (this.unsubscribeDismissDrawer) this.unsubscribeDismissDrawer(); } /** * [ Built-in React method. ] * * Allows us to render JSX to the screen */ render() { /** Styles */ const { sideMenuOverlayStyle, sideMenuContainerStyle } = styles; /** Props */ const { direction, style } = this.props; /** State */ const { sideMenuOpenValue, sideMenuOverlayOpacity } = this.state; /** Variables */ const animatedValue = direction === DirectionType.left || direction === DirectionType.right ? { marginLeft: sideMenuOpenValue } : { marginTop: sideMenuOpenValue }; return ( <View style={sideMenuContainerStyle}> <TouchableWithoutFeedback onPress={this.touchedOutside}> <Animated.View style={[ sideMenuOverlayStyle, { opacity: sideMenuOverlayOpacity }, ]} /> </TouchableWithoutFeedback> <Animated.View style={[ { backgroundColor: '#FFF' }, style, { height: this.drawerHeight, width: this.drawerWidth, ...animatedValue, }, ]} > <Component {...this.props} /> </Animated.View> </View> ); } /** * Touched outside drawer */ touchedOutside() { const { dismissWhenTouchOutside } = this.props; if (dismissWhenTouchOutside) { this.dismissDrawerWithAnimation(); } } /** * Dismisses drawer with animation */ dismissDrawerWithAnimation() { const { direction } = this.props; const { sideMenuIsDismissing } = this.state; const closeValues: DrawerDirectionValuesInterface = { left: -this.drawerWidth, right: this.screenWidth, top: -this.drawerHeight, bottom: this.screenHeight, }; // Animate side menu close Animated.timing(this.state.sideMenuOpenValue, { toValue: closeValues[direction], duration: this.props.animationCloseTime, useNativeDriver: false, }).start(() => { Navigation.dismissOverlay(this.props.componentId); this.setState({ sideMenuIsDismissing: false }); }); // Animate outside side menu opacity Animated.timing(this.state.sideMenuOverlayOpacity, { toValue: 0, duration: this.props.animationCloseTime, useNativeDriver: false, }).start(); } } return WrappedDrawer; } /** * Shows a drawer component * * @param layout */ static showDrawer(layout: Layout) { // By default for this library, we make the 'componentBackgroundColor' transparent const componentBackgroundColor = layout?.component?.options?.layout?.componentBackgroundColor ?? 'transparent'; const options = { ...layout?.component?.options, layout: { componentBackgroundColor: componentBackgroundColor, }, }; // Mutate options to add 'transparent' by default // @ts-ignore layout.component.options = { ...options }; Navigation.showOverlay(layout); } /** * Dismiss the drawer component */ static dismissDrawer() { dispatch('DISMISS_DRAWER', true); } } export default RNNDrawer; /** -------------------------------------------- */ /** Component Styling */ /** -------------------------------------------- */ const styles = StyleSheet.create<StylesInterface>({ sideMenuContainerStyle: { flex: 1, flexDirection: 'row', }, sideMenuOverlayStyle: { position: 'absolute', width: '100%', height: '100%', backgroundColor: '#000', }, });
the_stack
import { RuleTester } from 'eslint'; import { validFoundationsImportPath, validImportPath, } from './valid-import-path'; const ruleTester = new RuleTester({ parser: require.resolve('@typescript-eslint/parser'), parserOptions: { ecmaVersion: 2020, sourceType: 'module', }, }); const invalidFoundationsCases = [ { // A single import from the root of foundations code: "import { transitions } from '@guardian/src-foundations';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.", }, ], output: "import { transitions } from '@guardian/source-foundations';", }, { // A single import from a sub-module of foundations code: "import { height } from '@guardian/src-foundations/size';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.", }, ], output: "import { height } from '@guardian/source-foundations';", }, { // A single type import from the root of foundations code: "import type { Breakpoint } from '@guardian/src-foundations';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.", }, ], output: "import type { Breakpoint } from '@guardian/source-foundations';", }, { // A single type import from a sub-module of foundations code: "import type { Breakpoint } from '@guardian/src-foundations/mq';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.", }, ], output: "import type { Breakpoint } from '@guardian/source-foundations';", }, { // Exports that aren't available from foundations any more code: `import { remSize } from '@guardian/src-foundations/size/global';`, errors: [ { message: 'The following export(s) have been removed: remSize.', }, ], output: `import { remSize } from '@guardian/src-foundations/size/global';`, }, { // Exports that aren't available from foundations any more, plus one that is code: `import { remSize, size } from '@guardian/src-foundations/size/global';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been removed: remSize.", }, ], output: `import { remSize } from '@guardian/src-foundations/size/global'; import { size } from '@guardian/source-foundations';`, }, { // Exports that aren't available from foundations any more using an alias code: `import { remSize as rs } from '@guardian/src-foundations/size/global';`, errors: [ { message: 'The following export(s) have been removed: remSize.', }, ], output: `import { remSize as rs } from '@guardian/src-foundations/size/global';`, }, { // Exports that aren't available from foundations any more using an alias, plus one that is code: `import { remSize as rs, size as s } from '@guardian/src-foundations/size/global';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been removed: remSize.", }, ], output: `import { remSize as rs } from '@guardian/src-foundations/size/global'; import { size as s } from '@guardian/source-foundations';`, }, { // Exports that have changed names (foundations typography) code: `import { headline } from '@guardian/src-foundations/typography/obj';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been renamed [from -> to]: headline -> headlineObjectStyles", }, ], output: `import { headline } from '@guardian/source-foundations';`, }, { // Exports that have changed names, alongside some that haven't code: `import { headline, bodySizes } from '@guardian/src-foundations/typography/obj';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been renamed [from -> to]: headline -> headlineObjectStyles", }, ], output: `import { headline, bodySizes } from '@guardian/source-foundations';`, }, { // Exports that have changed names using an alias (foundations typography) code: `import { headline as hl } from '@guardian/src-foundations/typography/obj';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been renamed [from -> to]: headline -> headlineObjectStyles", }, ], output: `import { headline as hl } from '@guardian/source-foundations';`, }, { // Exports that have changed names, alongside some that haven't, using an alias code: `import { headline as hl, bodySizes as bs } from '@guardian/src-foundations/typography/obj';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-foundations' instead.\nThe following export(s) have been renamed [from -> to]: headline -> headlineObjectStyles", }, ], output: `import { headline as hl, bodySizes as bs } from '@guardian/source-foundations';`, }, { // Themes that now come from react-components and have changed names (from foundations) code: `import { labelDefault } from '@guardian/src-foundations/themes';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been renamed [from -> to]: labelDefault -> labelThemeDefault", }, ], output: `import { labelDefault } from '@guardian/source-react-components';`, }, { // Import default code: `import themes from '@guardian/src-foundations/themes';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.", }, ], output: `import themes from '@guardian/src-foundations/themes';`, }, { // Import everything code: `import * as themes from '@guardian/src-foundations/themes';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.", }, ], output: `import * as themes from '@guardian/src-foundations/themes';`, }, { // Import default, and some named things code: `import themes, {labelBrand} from '@guardian/src-foundations/themes';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been renamed [from -> to]: labelBrand -> labelThemeBrand", }, ], output: `import themes, {labelBrand} from '@guardian/src-foundations/themes';`, }, { // Export everything from the root of foundations code: `export * from '@guardian/src-foundations';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-foundations' instead.`, }, ], output: `export * from '@guardian/src-foundations';`, }, { // Export everything with an alias from the root of foundations code: `export * as foundations from '@guardian/src-foundations';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-foundations' instead.`, }, ], output: `export * as foundations from '@guardian/src-foundations';`, }, { // Export everything with an alias from themes code: `export * from '@guardian/src-foundations/themes';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-react-components' instead.`, }, ], output: `export * from '@guardian/src-foundations/themes';`, }, { // Export everything from a submodule of foundations code: `export * from '@guardian/src-foundations/size';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-foundations' instead.`, }, ], output: `export * from '@guardian/src-foundations/size';`, }, { // Export something that's changed names from foundations code: `export { headline } from '@guardian/src-foundations/typography/obj';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-foundations' instead.\nThe following export(s) have been renamed [from -> to]: headline -> headlineObjectStyles`, }, ], output: `export { headline } from '@guardian/source-foundations';`, }, { // Rename theme imports in imports code: `import { choiceCardDefault } from '@guardian/src-foundations/themes';`, errors: [ { message: `@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been renamed [from -> to]: choiceCardDefault -> choiceCardThemeDefault`, }, ], output: `import { choiceCardDefault } from '@guardian/source-react-components';`, }, { // Rename theme imports in exports code: `export { choiceCardDefault } from '@guardian/src-foundations/themes';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-react-components' instead.\nThe following export(s) have been renamed [from -> to]: choiceCardDefault -> choiceCardThemeDefault`, }, ], output: `export { choiceCardDefault } from '@guardian/source-react-components';`, }, { // Rename and remove theme imports code: `import { choiceCardDefault, brand } from '@guardian/src-foundations/themes';`, errors: [ { message: `@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been removed: brand.\nThe following export(s) have been renamed [from -> to]: choiceCardDefault -> choiceCardThemeDefault`, }, ], output: `import { brand } from '@guardian/src-foundations/themes'; import { choiceCardDefault, } from '@guardian/source-react-components';`, }, { // Rename and remove theme imports regardless of order code: `import { brand, choiceCardDefault } from '@guardian/src-foundations/themes';`, errors: [ { message: `@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been removed: brand.\nThe following export(s) have been renamed [from -> to]: choiceCardDefault -> choiceCardThemeDefault`, }, ], output: `import { brand } from '@guardian/src-foundations/themes'; import { choiceCardDefault } from '@guardian/source-react-components';`, }, ]; ruleTester.run('valid-foundations-import-path', validFoundationsImportPath, { valid: [ `import { breakpoints } from '@guardian/source-foundations'`, `import type { Breakpoint } from '@guardian/source-foundations'`, ], invalid: invalidFoundationsCases, }); ruleTester.run('valid-import-path', validImportPath, { valid: [ `import { Label } from '@guardian/source-react-components'`, `import type { LabelProps } from '@guardian/source-react-components'`, `import { breakpoints } from '@guardian/source-foundations'`, `import type { Breakpoint } from '@guardian/source-foundations'`, ], invalid: [ ...invalidFoundationsCases, { // A single component import from a component package code: "import { Label } from '@guardian/src-label';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.", }, ], output: "import { Label } from '@guardian/source-react-components';", }, { // A single type import from a component package code: "import type { LabelProps } from '@guardian/src-label';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.", }, ], output: "import type { LabelProps } from '@guardian/source-react-components';", }, { // Multiple imports from a single package code: "import { Label, Legend } from '@guardian/src-label';", errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.", }, ], output: "import { Label, Legend } from '@guardian/source-react-components';", }, { // Helpers removed exports code: `import { storybookBackgrounds } from '@guardian/src-helpers';`, errors: [ { message: 'The following export(s) have been removed: storybookBackgrounds.', }, ], output: `import { storybookBackgrounds } from '@guardian/src-helpers';`, }, { // Helpers moved exports code: `import type { Props } from '@guardian/src-helpers';`, errors: [ { message: `@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.`, }, ], output: `import type { Props } from '@guardian/source-react-components';`, }, { // Export everything from a component code: `export * from '@guardian/src-button';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-react-components' instead.`, }, ], output: `export * from '@guardian/src-button';`, }, { // Export everything from helpers code: `export * from '@guardian/src-helpers';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-react-components' instead.`, }, ], output: `export * from '@guardian/src-helpers';`, }, { // Export something from helpers code: `export type { Props } from '@guardian/src-helpers';`, errors: [ { message: `@guardian/src-* packages are deprecated. Export from '@guardian/source-react-components' instead.`, }, ], output: `export type { Props } from '@guardian/source-react-components';`, }, { // Export something that's gone from helpers code: `export { storybookBackgrounds } from '@guardian/src-helpers';`, errors: [ { message: `The following export(s) have been removed: storybookBackgrounds.`, }, ], output: `export { storybookBackgrounds } from '@guardian/src-helpers';`, }, { // Import something that's gone from foundations code: `import { palette } from '@guardian/src-foundations';`, errors: [ { message: `The following export(s) have been removed: palette.`, }, ], output: `import { palette } from '@guardian/src-foundations';`, }, { // Themes that now come from react-components and have changed names (from component) code: `import { buttonReaderRevenue } from '@guardian/src-button';`, errors: [ { message: "@guardian/src-* packages are deprecated. Import from '@guardian/source-react-components' instead.\nThe following export(s) have been renamed [from -> to]: buttonReaderRevenue -> buttonThemeReaderRevenue", }, ], output: `import { buttonReaderRevenue } from '@guardian/source-react-components';`, }, ], });
the_stack
import type { ImageStyle, TextStyle, ViewStyle, EasingFunction, } from 'react-native'; export interface Animation { timing100: number; timing200: number; timing300: number; timing400: number; timing500: number; timing600: number; timing700: number; timing800: number; timing900: number; timing1000: number; easeOutCurve: EasingFunction; easeInCurve: EasingFunction; easeInOutCurve: EasingFunction; easeInQuinticCurve: EasingFunction; easeOutQuinticCurve: EasingFunction; easeInOutQuinticCurve: EasingFunction; linearCurve: EasingFunction; } export interface ColorTokens { // Primary Palette primaryA: string; primaryB: string; primary: string; primary50: string; primary100: string; primary200: string; primary300: string; primary400: string; primary500: string; primary600: string; primary700: string; // Accent Palette accent: string; accent50: string; accent100: string; accent200: string; accent300: string; accent400: string; accent500: string; accent600: string; accent700: string; // Alert Palette negative: string; negative50: string; negative100: string; negative200: string; negative300: string; negative400: string; negative500: string; negative600: string; negative700: string; // Warning Palette warning: string; warning50: string; warning100: string; warning200: string; warning300: string; warning400: string; warning500: string; warning600: string; warning700: string; // Success Palette positive: string; positive50: string; positive100: string; positive200: string; positive300: string; positive400: string; positive500: string; positive600: string; positive700: string; // Monochrome Palette white: string; black: string; mono100: string; mono200: string; mono300: string; mono400: string; mono500: string; mono600: string; mono700: string; mono800: string; mono900: string; mono1000: string; // Rating Palette rating200: string; rating400: string; } export interface CoreContentColorTokens { contentPrimary: string; contentSecondary: string; contentTertiary: string; contentInversePrimary: string; contentInverseSecondary: string; contentInverseTertiary: string; } export interface CoreSemanticColorTokens extends CoreContentColorTokens { // Background backgroundPrimary: string; backgroundSecondary: string; backgroundTertiary: string; backgroundInversePrimary: string; backgroundInverseSecondary: string; // Border borderOpaque: string; borderTransparent?: string; borderSelected: string; borderInverseOpaque: string; borderInverseTransparent?: string; borderInverseSelected: string; } export interface CoreExtensionSemanticColorTokens { // Backgrounds backgroundStateDisabled: string; backgroundOverlayDark?: string; backgroundOverlayLight?: string; backgroundAccent: string; backgroundNegative: string; backgroundWarning: string; backgroundPositive: string; backgroundLightAccent: string; backgroundLightPositive: string; backgroundLightNegative: string; backgroundLightWarning: string; backgroundAlwaysDark: string; backgroundAlwaysLight: string; // Content contentStateDisabled: string; contentAccent: string; contentOnColor: string; contentOnColorInverse: string; contentNegative: string; contentWarning: string; contentPositive: string; // Border borderStateDisabled: string; borderAccent: string; borderAccentLight: string; borderNegative: string; borderWarning: string; borderPositive: string; } export interface SemanticColorTokens extends CoreSemanticColorTokens, CoreExtensionSemanticColorTokens {} export interface Border { borderColor: string; // longhand border-style properties do not accept string values borderStyle: | 'dashed' | 'dotted' | 'double' | 'groove' | 'hidden' | 'inset' | 'none' | 'outset' | 'ridge' | 'solid'; borderWidth: number; } export interface Borders { border100: Border; border200: Border; border300: Border; border400: Border; border500: Border; border600: Border; radius100: number; radius200: number; radius300: number; radius400: number; useRoundedCorners: boolean; buttonBorderRadius: number; surfaceBorderRadius: number; inputBorderRadius: number; popoverBorderRadius: number; } export interface ComponentColorTokens { // Buttons buttonPrimaryFill: string; buttonPrimaryText: string; buttonPrimaryHover: string; buttonPrimaryActive: string; buttonPrimarySelectedText: string; buttonPrimarySelectedFill: string; buttonPrimarySpinnerForeground: string; buttonPrimarySpinnerBackground: string; buttonSecondaryFill: string; buttonSecondaryText: string; buttonSecondaryHover: string; buttonSecondaryActive: string; buttonSecondarySelectedText: string; buttonSecondarySelectedFill: string; buttonSecondarySpinnerForeground: string; buttonSecondarySpinnerBackground: string; buttonTertiaryFill: string; buttonTertiaryText: string; buttonTertiaryHover: string; buttonTertiaryActive: string; buttonTertiarySelectedText: string; buttonTertiarySelectedFill: string; buttonTertiarySpinnerForeground: string; buttonTertiarySpinnerBackground: string; buttonMinimalFill: string; buttonMinimalText: string; buttonMinimalHover: string; buttonMinimalActive: string; buttonMinimalSelectedText: string; buttonMinimalSelectedFill: string; buttonMinimalSpinnerForeground: string; buttonMinimalSpinnerBackground: string; buttonDisabledFill: string; buttonDisabledText: string; buttonDisabledSpinnerForeground: string; buttonDisabledSpinnerBackground: string; // Input inputBorder: string; inputFill: string; inputFillError: string; inputFillDisabled: string; inputFillActive: string; inputFillPositive: string; inputTextDisabled: string; inputBorderError: string; inputBorderPositive: string; inputBorderFocused: string; inputEnhancerFill: string; inputEnhancerFillDisabled: string; inputEnhancerTextDisabled: string; inputPlaceholder: string; inputPlaceholderDisabled: string; // tag tagFontDisabledRampUnit: string; tagOutlinedDisabledRampUnit: string; tagSolidFontRampUnit: string; tagSolidRampUnit: string; tagOutlinedFontRampUnit: string; tagOutlinedRampUnit: string; tagNeutralSolidBackground: string; tagNeutralSolidFont: string; tagNeutralOutlinedBackground: string; tagNeutralOutlinedDisabled: string; tagNeutralOutlinedFont: string; tagNeutralFontDisabled: string; tagPrimarySolidBackground: string; tagPrimarySolidFont: string; tagPrimaryOutlinedBackground: string; tagPrimaryOutlinedDisabled: string; tagPrimaryOutlinedFont: string; tagPrimaryFontDisabled: string; tagAccentSolidBackground: string; tagAccentSolidFont: string; tagAccentOutlinedBackground: string; tagAccentOutlinedDisabled: string; tagAccentOutlinedFont: string; tagAccentFontDisabled: string; tagPositiveSolidBackground: string; tagPositiveSolidFont: string; tagPositiveOutlinedBackground: string; tagPositiveOutlinedDisabled: string; tagPositiveOutlinedFont: string; tagPositiveFontDisabled: string; tagWarningSolidBackground: string; tagWarningSolidFont: string; tagWarningOutlinedBackground: string; tagWarningOutlinedDisabled: string; tagWarningOutlinedFont: string; tagWarningFontDisabled: string; tagNegativeOutlinedFont: string; tagNegativeOutlinedBackground: string; tagNegativeSolidFont: string; tagNegativeSolidBackground: string; tagNegativeFontDisabled: string; tagNegativeOutlinedDisabled: string; tagOrangeOutlinedFont: string; tagOrangeOutlinedBackground: string; tagOrangeSolidFont: string; tagOrangeSolidBackground: string; tagOrangeFontDisabled: string; tagOrangeOutlinedDisabled: string; tagPurpleOutlinedFont: string; tagPurpleOutlinedBackground: string; tagPurpleSolidFont: string; tagPurpleSolidBackground: string; tagPurpleFontDisabled: string; tagPurpleOutlinedDisabled: string; tagBrownOutlinedFont: string; tagBrownOutlinedBackground: string; tagBrownSolidFont: string; tagBrownSolidBackground: string; tagBrownFontDisabled: string; tagBrownOutlinedDisabled: string; } export interface FontTokens { primaryFontFamily: string; } export interface Font { fontFamily: string; fontWeight: | 'bold' | 'normal' | '100' | '200' | '300' | '500' | '600' | '700' | '800' | '900'; fontSize: number; lineHeight: number; } export interface Typography { font100: Font; font150: Font; font200: Font; font250: Font; font300: Font; font350: Font; font400: Font; font450: Font; font550: Font; font650: Font; font750: Font; font850: Font; font950: Font; font1050: Font; font1150: Font; font1250: Font; font1350: Font; font1450: Font; ParagraphXSmall: Font; ParagraphSmall: Font; ParagraphMedium: Font; ParagraphLarge: Font; LabelXSmall: Font; LabelSmall: Font; LabelMedium: Font; LabelLarge: Font; HeadingXSmall: Font; HeadingSmall: Font; HeadingMedium: Font; HeadingLarge: Font; HeadingXLarge: Font; HeadingXXLarge: Font; DisplayXSmall: Font; DisplaySmall: Font; DisplayMedium: Font; DisplayLarge: Font; } export interface Sizing { scale0: number; scale100: number; scale200: number; scale300: number; scale400: number; scale500: number; scale550: number; scale600: number; scale650: number; scale700: number; scale750: number; scale800: number; scale850: number; scale900: number; scale950: number; scale1000: number; scale1200: number; scale1400: number; scale1600: number; scale2400: number; scale3200: number; scale4800: number; IconXSmall: number; IconSmall: number; IconMedium: number; IconLarge: number; } export interface Colors extends ColorTokens, ComponentColorTokens, SemanticColorTokens {} export interface Theme { name: string; animation: Animation; borders: Borders; colors: Colors; sizing: Sizing; typography: Typography; } export type Style = ViewStyle | TextStyle | ImageStyle; export type NamedStyles<T> = { [P in keyof T]: Style; };
the_stack
import { expect } from "chai"; import { ByteStream } from "@itwin/core-bentley"; import { Point3d } from "@itwin/core-geometry"; import { ColorIndex, FeatureIndex, FillFlags, MeshEdge, OctEncodedNormal, OctEncodedNormalPair, PolylineData, QPoint3dList } from "@itwin/core-common"; import { IModelApp } from "../../../IModelApp"; import { MeshArgs, MeshArgsEdges } from "../../../render/primitives/mesh/MeshPrimitives"; import { VertexIndices } from "../../../render/primitives/VertexTable"; import { EdgeParams, EdgeTable } from "../../../render/primitives/EdgeParams"; function makeNormalPair(n0: number, n1: number): OctEncodedNormalPair { return new OctEncodedNormalPair(new OctEncodedNormal(n0), new OctEncodedNormal(n1)); } /* 1 3 * ____ * /\ /\ * /__\/__\ * 0 2 4 */ function createMeshArgs(opts?: { is2d?: boolean }): MeshArgs { const edges = new MeshArgsEdges(); edges.edges.edges = [new MeshEdge(0, 1), new MeshEdge(1, 3), new MeshEdge(3, 4)]; edges.silhouettes.edges = [new MeshEdge(1, 2), new MeshEdge(2, 3)]; edges.silhouettes.normals = [makeNormalPair(0, 0xffff), makeNormalPair(0x1234, 0xfedc)]; edges.polylines.lines = [new PolylineData([0, 2, 4]), new PolylineData([2, 4, 3, 1]), new PolylineData([1, 0])]; return { points: QPoint3dList.fromPoints([new Point3d(0, 0, 0), new Point3d(1, 1, 0), new Point3d(2, 0, 0), new Point3d(3, 1, 0), new Point3d(4, 0, 0)]), vertIndices: [0, 1, 2, 2, 1, 3, 2, 3, 4], edges, fillFlags: FillFlags.None, is2d: true === opts?.is2d, colors: new ColorIndex(), features: new FeatureIndex(), }; } function expectIndices(indices: VertexIndices, expected: number[]): void { expect(indices.data.length).to.equal(expected.length * 3); const stream = ByteStream.fromUint8Array(indices.data); for (const expectedIndex of expected) expect(stream.nextUint24).to.equal(expectedIndex); } // expectedSegments = 2 indices per segment edge. // expectedSilhouettes = 2 indices and 2 oct-encoded normals per silhouette edge. function expectEdgeTable(edges: EdgeTable, expectedSegments: number[], expectedSilhouettes: number[], expectedPaddingBytes = 0): void { expect(expectedSegments.length % 2).to.equal(0); expect(edges.numSegments).to.equal(expectedSegments.length / 2); expect(edges.silhouettePadding).to.equal(expectedPaddingBytes); const stream = ByteStream.fromUint8Array(edges.data); const actualSegments: number[] = []; for (let i = 0; i < expectedSegments.length; i += 2) { actualSegments.push(stream.nextUint24); actualSegments.push(stream.nextUint24); } expect(expectedSilhouettes.length % 4).to.equal(0); const actualSilhouettes: number[] = []; for (let i = 0; i < expectedPaddingBytes; i++) expect(stream.nextUint8).to.equal(0); for (let i = 0; i < expectedSilhouettes.length; i += 4) { actualSilhouettes.push(stream.nextUint24); actualSilhouettes.push(stream.nextUint24); actualSilhouettes.push(stream.nextUint16); actualSilhouettes.push(stream.nextUint16); } expect(actualSegments).to.deep.equal(expectedSegments); expect(actualSilhouettes).to.deep.equal(expectedSilhouettes); } describe("IndexedEdgeParams", () => { describe("when disabled", () => { afterEach(async () => { await IModelApp.shutdown(); }); it("are not produced if unsupported by client device", async () => { await IModelApp.startup({ renderSys: { useWebGL2: false } }); expect(IModelApp.renderSystem.supportsIndexedEdges).to.be.false; expect(IModelApp.tileAdmin.enableIndexedEdges).to.be.false; const args = createMeshArgs(); const edges = EdgeParams.fromMeshArgs(args)!; expect(edges).not.to.be.undefined; expect(edges.segments).not.to.be.undefined; expect(edges.silhouettes).not.to.be.undefined; expect(edges.polylines).to.be.undefined; // converted to segments expect(edges.indexed).to.be.undefined; }); it("are not produced if explicitly disabled by TileAdmin", async () => { await IModelApp.startup({ tileAdmin: { enableIndexedEdges: false } }); expect(IModelApp.renderSystem.supportsIndexedEdges).to.be.true; expect(IModelApp.tileAdmin.enableIndexedEdges).to.be.false; const args = createMeshArgs(); const edges = EdgeParams.fromMeshArgs(args)!; expect(edges).not.to.be.undefined; expect(edges.segments).not.to.be.undefined; expect(edges.silhouettes).not.to.be.undefined; expect(edges.polylines).to.be.undefined; // converted to segments expect(edges.indexed).to.be.undefined; }); }); describe("when enabled", () => { before(async () => { await IModelApp.startup(); }); after(async () => { await IModelApp.shutdown(); }); it("are not produced if MeshArgs supplies no edges", () => { const args = createMeshArgs(); args.edges?.clear(); expect(EdgeParams.fromMeshArgs(args)).to.be.undefined; }); it("are not produced for polylines in 2d", () => { const args = createMeshArgs({ is2d: true }); const edges = EdgeParams.fromMeshArgs(args)!; expect(edges).not.to.be.undefined; expect(edges.polylines).not.to.be.undefined; expect(edges.indexed).not.to.be.undefined; expect(edges.silhouettes).to.be.undefined; expect(edges.segments).to.be.undefined; }); it("are not produced for polylines if width > 3", () => { const args = createMeshArgs(); expect(args.edges).not.to.be.undefined; args.edges!.width = 4; const edges = EdgeParams.fromMeshArgs(args)!; expect(edges).not.to.be.undefined; expect(edges.polylines).not.to.be.undefined; expect(edges.indexed).not.to.be.undefined; expect(edges.silhouettes).to.be.undefined; expect(edges.segments).to.be.undefined; }); it("are created from MeshArgs", () => { const args = createMeshArgs(); const edges = EdgeParams.fromMeshArgs(args)!; expect(edges).not.to.be.undefined; expect(edges.indexed).not.to.be.undefined; expect(edges.polylines).to.be.undefined; expect(edges.silhouettes).to.be.undefined; expect(edges.segments).to.be.undefined; expectIndices(edges.indexed!.indices, [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, ]); expectEdgeTable(edges.indexed!.edges, [ // visible 0, 1, 1, 3, 3, 4, // polylines 0, 2, 2, 4, 2, 4, 3, 4, 1, 3, 0, 1, ], [ // silhouettes 1, 2, 0, 0xffff, 2, 3, 0x1234, 0xfedc, ]); }); it("inserts padding between segments and silhouettes when required", () => { const args = createMeshArgs(); const edges = EdgeParams.fromMeshArgs(args, 15)!; expect(edges).not.to.be.undefined; expect(edges.indexed).not.to.be.undefined; expectIndices(edges.indexed!.indices, [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, ]); expectEdgeTable(edges.indexed!.edges, [ // visible 0, 1, 1, 3, 3, 4, // polylines 0, 2, 2, 4, 2, 4, 3, 4, 1, 3, 0, 1, ], [ // silhouettes 1, 2, 0, 0xffff, 2, 3, 0x1234, 0xfedc, ], 6); function makeEdgeTable(nSegs: number, nSils: number): EdgeTable { const meshargs = createMeshArgs(); const edgs = meshargs.edges!; expect(edgs).not.to.be.undefined; edgs.polylines.clear(); edgs.silhouettes.clear(); edgs.edges.edges = []; for (let i = 0; i < nSegs; i++) edgs.edges.edges.push(new MeshEdge(0, 1)); edgs.silhouettes.edges = []; edgs.silhouettes.normals = []; for (let i = 0; i < nSils; i++) { edgs.silhouettes.edges.push(new MeshEdge(2 + i, 3)); edgs.silhouettes.normals.push(makeNormalPair(4, 5)); } const edgeParams = EdgeParams.fromMeshArgs(meshargs, 15)!; expect(edgeParams).not.to.be.undefined; expect(edgeParams.indexed).not.to.be.undefined; return edgeParams.indexed!.edges; } // Num segments, num silhouettes, expected padding, expected width, expected height const testCases = [ // bad [330, 101, 0, 30, 25], [64, 32, 6, 15, 12], [126, 63, 4, 30, 12], [288, 80, 2, 30, 22], [102, 51, 8, 30, 10], // good [80, 40, 0, 15, 15], [100, 50, 0, 30, 10], [258, 65, 2, 30, 19], [74, 37, 6, 15, 14], ]; for (const test of testCases) { const table = makeEdgeTable(test[0], test[1]); // console.log(JSON.stringify({ index: curIndex++, segs: test[0], sils: test[1], pad: test[2] })); expect(table.numSegments).to.equal(test[0]); expect(table.silhouettePadding).to.equal(test[2]); expect(table.width).to.equal(test[3]); expect(table.height).to.equal(test[4]); const bytes = Array.from(table.data); for (let i = table.numSegments; i < test[1]; i++) { const texelIndex = table.numSegments * 1.5 + test[2] * 0.25 + (i - table.numSegments) * 2.5; const byteIndex = texelIndex * 4; expect(byteIndex).to.equal(Math.floor(byteIndex)); expect(bytes[byteIndex]).to.equal(2 + i); let isEven = 0 === (i & 1); if (0 !== test[2] % 4) isEven = !isEven; const byteIndex2 = Math.floor(texelIndex) * 4 + (isEven ? 0 : 2); expect(byteIndex2).to.equal(byteIndex); } // for (let i = 0; i < table.height * byteWidth; i += byteWidth) // console.log(bytes.slice(i, i + byteWidth).join(" ")); } }); }); });
the_stack
import { FieldType, FunctionExp, GroupByClause, HavingClause, OrderByClause, Query, WhereClause, WithDataCategoryClause, FieldTypeOf, Subquery, FieldFunctionExpression, } from '../api/api-models'; import * as utils from '../utils'; import { FieldData, Formatter, FormatOptions } from '../formatter/formatter'; import { parseQuery } from '../parser/visitor'; export interface SoqlComposeConfig { logging: boolean; // default=false format: boolean; // default=false formatOptions?: FormatOptions; autoCompose: boolean; // default=true } /** * Formats query - This will compose and then parse a query with the provided format options * or the defaults if omitted * @param soql * @param [formatOptions] * @returns */ export function formatQuery(soql: string, formatOptions?: FormatOptions) { return composeQuery(parseQuery(soql), { format: true, formatOptions }); } /** * Composes a parsed query back to a SOQL query * The parsing methods are public in case there is a need to parse just a part of a query, * but the common case is to call the "start()" method * @param soql * @param [config] * @returns query */ export function composeQuery(soql: Query, config: Partial<SoqlComposeConfig> = {}): string { if (!soql) { return ''; } config = config || {}; config.format = config.format ? true : false; if (config.logging) { console.time('composer'); console.log('Composing Query:', soql); console.log('Format output:', config.format); } const query = new Compose(soql, config).query; if (config.logging) { console.timeEnd('composer'); } return query; } /** * Compose * This class handles all the logic for turning a Query into a SOQL query * This depends on the Format class for parts of the processing */ export class Compose { public logging: boolean = false; public format: boolean = false; public query: string; public formatter: Formatter; constructor(private soql: Query, config: Partial<SoqlComposeConfig> = {}) { config = { autoCompose: true, ...config }; const { logging, format } = config; this.logging = logging; this.format = format; this.query = ''; this.formatter = new Formatter(this.format, { logging: this.logging, ...config.formatOptions, }); if (config.autoCompose) { this.start(); } } /** * Starts compose */ public start(): void { this.query = this.parseQuery(this.soql); } /** * If logging is enabled, print the query to the console * @param soql */ private log(soql: string) { if (this.logging) { console.log('Current SOQL:', soql); } } /** * Parses FunctionExp object * Prefers functionName if populated, otherwise will fallback to rawValue * @param fn * @returns fn */ private parseFn(fn: FunctionExp): string { let output: string | undefined; if (fn.rawValue) { output = fn.rawValue; } else { output = fn.functionName; output += `(${(fn.parameters || []).map(param => (utils.isString(param) ? param : this.parseFn(param))).join(', ')})`; } if (fn.alias) { output += ` ${fn.alias}`; } return output; } /** * Parses query * Base entry point for the query * this may be called multiple times recursively for subqueries and WHERE queries * @param query * @returns query */ public parseQuery(query: Query | Subquery): string { const fieldData: FieldData = { fields: this.parseFields(query.fields).map(field => ({ text: field.text, typeOfClause: field.typeOfClause, isSubquery: field.text.startsWith('('), prefix: '', suffix: '', })), isSubquery: utils.isSubquery(query), lineBreaks: [], }; let output = this.formatter.formatClause('SELECT').trimStart(); // Format fields based on configuration this.formatter.formatFields(fieldData); let fieldsOutput = ''; fieldData.fields.forEach(field => { if (Array.isArray(field.typeOfClause)) { fieldsOutput += `${field.prefix}${this.formatter.formatTyeOfField(field.text, field.typeOfClause)}${field.suffix}`; } else { fieldsOutput += `${field.prefix}${field.text}${field.suffix}`; } }); output += this.formatter.formatText(fieldsOutput); output += this.formatter.formatClause('FROM'); if (utils.isSubquery(query)) { const sObjectPrefix = query.sObjectPrefix || []; sObjectPrefix.push(query.relationshipName); output += this.formatter.formatText(`${sObjectPrefix.join('.')}${utils.get(query.sObjectAlias, '', ' ')}`); } else { output += this.formatter.formatText(`${query.sObject}${utils.get(query.sObjectAlias, '', ' ')}`); } this.log(output); if (query.usingScope) { output += this.formatter.formatClause('USING SCOPE'); output += this.formatter.formatText(query.usingScope); this.log(output); } if (query.where) { output += this.formatter.formatClause('WHERE'); output += this.formatter.formatText(this.parseWhereOrHavingClause(query.where)); this.log(output); } if (query.groupBy) { output += this.formatter.formatClause('GROUP BY'); output += this.formatter.formatText(this.parseGroupByClause(query.groupBy)); this.log(output); if (query.having) { output += this.formatter.formatClause('HAVING'); output += this.formatter.formatText(this.parseWhereOrHavingClause(query.having)); this.log(output); } } if (query.orderBy && (!Array.isArray(query.orderBy) || query.orderBy.length > 0)) { output += this.formatter.formatClause('ORDER BY'); output += this.formatter.formatText(this.parseOrderBy(query.orderBy)); this.log(output); } if (utils.isNumber(query.limit)) { output += this.formatter.formatClause('LIMIT'); output += this.formatter.formatText(`${query.limit}`); this.log(output); } if (utils.isNumber(query.offset)) { output += this.formatter.formatClause('OFFSET'); output += this.formatter.formatText(`${query.offset}`); this.log(output); } if (query.withDataCategory) { output += this.formatter.formatClause('WITH DATA CATEGORY'); output += this.formatter.formatText(this.parseWithDataCategory(query.withDataCategory)); this.log(output); } if (query.withSecurityEnforced) { output += this.formatter.formatClause('WITH SECURITY_ENFORCED'); this.log(output); } if (query.for) { output += this.formatter.formatClause('FOR'); output += this.formatter.formatText(query.for); this.log(output); } if (query.update) { output += this.formatter.formatClause('UPDATE'); output += this.formatter.formatText(query.update); this.log(output); } return output; } /** * Parses fields * e.x.: SELECT amount, FORMAT(amount) Amt, (SELECT Id, Name FROM Contacts) * @param fields * @returns fields */ public parseFields(fields: FieldType[]): { text: string; typeOfClause?: string[] }[] { return fields.map(field => { let text = ''; let typeOfClause: string[]; const objPrefix = (field as any).objectPrefix ? `${(field as any).objectPrefix}.` : ''; switch (field.type) { case 'Field': { text = `${objPrefix}${field.field}${field.alias ? ` ${field.alias}` : ''}`; break; } case 'FieldFunctionExpression': { let params = ''; if (field.parameters) { params = field.parameters .map(param => (utils.isString(param) ? param : this.parseFields([param as FieldFunctionExpression]).map(param => param.text))) .join(', '); } text = `${field.functionName}(${params})${field.alias ? ` ${field.alias}` : ''}`; break; } case 'FieldRelationship': { text = `${objPrefix}${field.relationships.join('.')}.${field.field}${utils.hasAlias(field) ? ` ${field.alias}` : ''}`; break; } case 'FieldSubquery': { text = this.formatter.formatSubquery(this.parseQuery(field.subquery)); break; } case 'FieldTypeof': { typeOfClause = this.parseTypeOfField(field); text = typeOfClause.join(' '); break; } default: break; } return { text, typeOfClause }; }); } /** * Parses type of Field * e.x.: TYPEOF What WHEN Account THEN Phone, NumberOfEmployees WHEN Opportunity THEN Amount, CloseDate ELSE Name * @param typeOfField * @returns type of field */ public parseTypeOfField(typeOfField: FieldTypeOf): string[] { const output = [`TYPEOF ${typeOfField.field}`].concat( typeOfField.conditions.map(condition => this.formatter.formatTypeofFieldCondition(condition)), ); output.push(`END`); return output; } /** * Parses where clause * e.x.: WHERE LoginTime > 2010-09-20T22:16:30.000Z AND LoginTime < 2010-09-21T22:16:30.000Z * WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName LIKE 'apple%') AND Id IN (SELECT AccountId FROM Opportunity WHERE isClosed = false) * @param where * @param priorIsNegationOperator - do not set this when calling manually. Recursive call will set this to ensure proper formatting. * @returns where clause */ public parseWhereOrHavingClause(whereOrHaving: WhereClause | HavingClause, tabOffset = 0, priorConditionIsNegation = false): string { let output = ''; const left = whereOrHaving.left; let trimPrecedingOutput = false; if (left) { output += this.formatter.formatParens(left.openParen, '(', utils.isNegationCondition(left)); if (!utils.isNegationCondition(left)) { tabOffset = tabOffset + (left.openParen || 0) - (left.closeParen || 0); if (priorConditionIsNegation) { tabOffset++; } let expression = ''; expression += utils.isValueFunctionCondition(left) ? this.parseFn(left.fn) : left.field; expression += ` ${left.operator} `; if (utils.isValueQueryCondition(left)) { expression += this.formatter.formatSubquery(this.parseQuery(left.valueQuery), 1, true); } else { expression += utils.getAsArrayStr(utils.getWhereValue(left.value, left.literalType)); } output += this.formatter.formatWithIndent(expression); output += this.formatter.formatParens(left.closeParen, ')', priorConditionIsNegation); } } if (utils.isWhereOrHavingClauseWithRightCondition(whereOrHaving)) { const operator = utils.get(whereOrHaving.operator); trimPrecedingOutput = operator === 'NOT'; const formattedData = this.formatter.formatWhereClauseOperators( operator, this.parseWhereOrHavingClause(whereOrHaving.right, tabOffset, utils.isNegationCondition(left)), tabOffset, ); return `${trimPrecedingOutput ? output.trimRight() : output}${formattedData}`.trim(); } else { return output.trim(); } } /** * Parses group by clause * e.x.: GROUP BY CampaignId * @param groupBy * @returns group by clause */ public parseGroupByClause(groupBy: GroupByClause | GroupByClause[]): string { return (Array.isArray(groupBy) ? groupBy : [groupBy]) .map(clause => (utils.isGroupByField(clause) ? clause.field : this.parseFn(clause.fn))) .join(', '); } /** * Parses order by * e.x.: ORDER BY BillingPostalCode ASC NULLS LAST * @param orderBy * @returns order by */ public parseOrderBy(orderBy: OrderByClause | OrderByClause[]): string { if (Array.isArray(orderBy)) { return this.formatter.formatOrderByArray(orderBy.map(ob => this.parseOrderBy(ob))); } else { let output = ''; if (utils.isOrderByField(orderBy)) { output = `${utils.get(orderBy.field, ' ')}`; } else { output += `${this.parseFn(orderBy.fn)} `; } output += `${utils.get(orderBy.order, ' ')}${utils.get(orderBy.nulls, '', 'NULLS ')}`; return output.trim(); } } /** * Parses with data category * e.x.: WITH DATA CATEGORY Geography__c AT (usa__c, uk__c) * @param withDataCategory * @returns with data category */ public parseWithDataCategory(withDataCategory: WithDataCategoryClause): string { return withDataCategory.conditions .map(condition => { const params = condition.parameters.length > 1 ? `(${condition.parameters.join(', ')})` : `${condition.parameters.join(', ')}`; return `${condition.groupName} ${condition.selector} ${params}`; }) .join(' AND '); } }
the_stack
import { TypeAssertion, ValidationContext } from '../types'; import { validate, getType } from '../validator'; import { compile } from '../compiler'; import { serialize, deserialize } from '../serializer'; describe("compiler-5", function() { it("compiler-decorators-1", function() { const schemas = [compile(` type X = @minLength(3) @maxLength(5) string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', minLength: 3, maxLength: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>('12', ty)).toEqual(null); expect(validate<any>('123', ty)).toEqual({value: '123'}); expect(validate<any>('1234', ty)).toEqual({value: '1234'}); expect(validate<any>('12345', ty)).toEqual({value: '12345'}); expect(validate<any>('123456', ty)).toEqual(null); expect(validate<any>(4, ty)).toEqual(null); } } } }); it("compiler-decorators-1b", function() { const schemas = [compile(` type X = @maxLength(5) string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', maxLength: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>('', ty)).toEqual({value: ''}); expect(validate<any>('1', ty)).toEqual({value: '1'}); expect(validate<any>('12', ty)).toEqual({value: '12'}); expect(validate<any>('123', ty)).toEqual({value: '123'}); expect(validate<any>('1234', ty)).toEqual({value: '1234'}); expect(validate<any>('12345', ty)).toEqual({value: '12345'}); expect(validate<any>('123456', ty)).toEqual(null); expect(validate<any>(4, ty)).toEqual(null); } } } }); it("compiler-decorators-1c", function() { const schemas = [compile(` type X = @minLength(3) string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', minLength: 3, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>('12', ty)).toEqual(null); expect(validate<any>('123', ty)).toEqual({value: '123'}); expect(validate<any>('1234', ty)).toEqual({value: '1234'}); expect(validate<any>('12345', ty)).toEqual({value: '12345'}); expect(validate<any>('123456', ty)).toEqual({value: '123456'}); expect(validate<any>(4, ty)).toEqual(null); } } } }); it("compiler-decorators-2", function() { const schemas = [compile(` interface X { a: @minLength(3) @maxLength(5) string; } `), compile(` interface X { @minLength(3) @maxLength(5) a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', minLength: 3, maxLength: 5, }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: ''}, ty)).toEqual(null); expect(validate<any>({a: '1'}, ty)).toEqual(null); expect(validate<any>({a: '12'}, ty)).toEqual(null); expect(validate<any>({a: '123'}, ty)).toEqual({value: {a: '123'}}); expect(validate<any>({a: '1234'}, ty)).toEqual({value: {a: '1234'}}); expect(validate<any>({a: '12345'}, ty)).toEqual({value: {a: '12345'}}); expect(validate<any>({a: '123456'}, ty)).toEqual(null); expect(validate<any>({a: 4}, ty)).toEqual(null); } } } }); it("compiler-decorators-3", function() { const schemas = [compile(` interface X { a?: @minLength(3) @maxLength(5) string; } `), compile(` interface X { @minLength(3) @maxLength(5) a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', minLength: 3, maxLength: 5, } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: ''}, ty)).toEqual(null); expect(validate<any>({a: '1'}, ty)).toEqual(null); expect(validate<any>({a: '12'}, ty)).toEqual(null); expect(validate<any>({a: '123'}, ty)).toEqual({value: {a: '123'}}); expect(validate<any>({a: '1234'}, ty)).toEqual({value: {a: '1234'}}); expect(validate<any>({a: '12345'}, ty)).toEqual({value: {a: '12345'}}); expect(validate<any>({a: '123456'}, ty)).toEqual(null); expect(validate<any>({a: 4}, ty)).toEqual(null); } } } }); it("compiler-decorators-4", function() { const schemas = [compile(` type X = @minValue(3) @maxValue(5) number; `), compile(` type X = @range(3, 5) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', minValue: 3, maxValue: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(2, ty)).toEqual(null); expect(validate<any>(3, ty)).toEqual({value: 3}); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual({value: 5}); expect(validate<any>(6, ty)).toEqual(null); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-4b", function() { const schemas = [compile(` type X = @maxValue(5) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', maxValue: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual({value: 0}); expect(validate<any>(1, ty)).toEqual({value: 1}); expect(validate<any>(2, ty)).toEqual({value: 2}); expect(validate<any>(3, ty)).toEqual({value: 3}); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual({value: 5}); expect(validate<any>(6, ty)).toEqual(null); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-4c", function() { const schemas = [compile(` type X = @minValue(3) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', minValue: 3, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(2, ty)).toEqual(null); expect(validate<any>(3, ty)).toEqual({value: 3}); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual({value: 5}); expect(validate<any>(6, ty)).toEqual({value: 6}); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-5", function() { const schemas = [compile(` interface X { a: @minValue(3) @maxValue(5) number; } `), compile(` interface X { @minValue(3) @maxValue(5) a: number; } `), compile(` interface X { a: @range(3, 5) number; } `), compile(` interface X { @range(3, 5) a: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[2].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[3].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'number', minValue: 3, maxValue: 5, }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 1}, ty)).toEqual(null); expect(validate<any>({a: 2}, ty)).toEqual(null); expect(validate<any>({a: 3}, ty)).toEqual({value: {a: 3}}); expect(validate<any>({a: 4}, ty)).toEqual({value: {a: 4}}); expect(validate<any>({a: 5}, ty)).toEqual({value: {a: 5}}); expect(validate<any>({a: 6}, ty)).toEqual(null); expect(validate<any>({a: '4'}, ty)).toEqual(null); } } } }); it("compiler-decorators-6", function() { const schemas = [compile(` interface X { a?: @minValue(3) @maxValue(5) number; } `), compile(` interface X { @minValue(3) @maxValue(5) a?: number; } `), compile(` interface X { a?: @range(3, 5) number; } `), compile(` interface X { @range(3, 5) a?: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[2].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[3].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', minValue: 3, maxValue: 5, } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 1}, ty)).toEqual(null); expect(validate<any>({a: 2}, ty)).toEqual(null); expect(validate<any>({a: 3}, ty)).toEqual({value: {a: 3}}); expect(validate<any>({a: 4}, ty)).toEqual({value: {a: 4}}); expect(validate<any>({a: 5}, ty)).toEqual({value: {a: 5}}); expect(validate<any>({a: 6}, ty)).toEqual(null); expect(validate<any>({a: '4'}, ty)).toEqual(null); } } } }); it("compiler-decorators-7", function() { const schemas = [compile(` type X = @minValue('C') @maxValue('E') string; `), compile(` type X = @range('C', 'E') string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', minValue: 'C', maxValue: 'E', }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>('A', ty)).toEqual(null); expect(validate<any>('B', ty)).toEqual(null); expect(validate<any>('C', ty)).toEqual({value: 'C'}); expect(validate<any>('D', ty)).toEqual({value: 'D'}); expect(validate<any>('E', ty)).toEqual({value: 'E'}); expect(validate<any>('F', ty)).toEqual(null); } } } }); it("compiler-decorators-8", function() { const schemas = [compile(` interface X { a: @minValue('C') @maxValue('E') string; } `), compile(` interface X { @minValue('C') @maxValue('E') a: string; } `), compile(` interface X { a: @range('C', 'E') string; } `), compile(` interface X { @range('C', 'E') a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[2].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[3].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', minValue: 'C', maxValue: 'E', }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual({value: {a: 'C'}}); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual({value: {a: 'E'}}); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); it("compiler-decorators-9", function() { const schemas = [compile(` interface X { a?: @minValue('C') @maxValue('E') string; } `), compile(` interface X { @minValue('C') @maxValue('E') a?: string; } `), compile(` interface X { a?: @range('C', 'E') string; } `), compile(` interface X { @range('C', 'E') a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[2].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[3].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', minValue: 'C', maxValue: 'E', } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual({value: {a: 'C'}}); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual({value: {a: 'E'}}); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); it("compiler-decorators-10", function() { const schemas = [compile(` type X = @greaterThan(3) @lessThan(5) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', greaterThanValue: 3, lessThanValue: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(2, ty)).toEqual(null); expect(validate<any>(3, ty)).toEqual(null); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual(null); expect(validate<any>(6, ty)).toEqual(null); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-10a", function() { const schemas = [compile(` type X = @lessThan(5) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', lessThanValue: 5, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual({value: 0}); expect(validate<any>(1, ty)).toEqual({value: 1}); expect(validate<any>(2, ty)).toEqual({value: 2}); expect(validate<any>(3, ty)).toEqual({value: 3}); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual(null); expect(validate<any>(6, ty)).toEqual(null); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-10b", function() { const schemas = [compile(` type X = @greaterThan(3) number; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'number', greaterThanValue: 3, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(2, ty)).toEqual(null); expect(validate<any>(3, ty)).toEqual(null); expect(validate<any>(4, ty)).toEqual({value: 4}); expect(validate<any>(5, ty)).toEqual({value: 5}); expect(validate<any>(6, ty)).toEqual({value: 6}); expect(validate<any>('4', ty)).toEqual(null); } } } }); it("compiler-decorators-11", function() { const schemas = [compile(` interface X { a: @greaterThan(3) @lessThan(5) number; } `), compile(` interface X { @greaterThan(3) @lessThan(5) a: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'number', greaterThanValue: 3, lessThanValue: 5, }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 1}, ty)).toEqual(null); expect(validate<any>({a: 2}, ty)).toEqual(null); expect(validate<any>({a: 3}, ty)).toEqual(null); expect(validate<any>({a: 4}, ty)).toEqual({value: {a: 4}}); expect(validate<any>({a: 5}, ty)).toEqual(null); expect(validate<any>({a: 6}, ty)).toEqual(null); expect(validate<any>({a: '4'}, ty)).toEqual(null); } } } }); it("compiler-decorators-12", function() { const schemas = [compile(` interface X { a?: @greaterThan(3) @lessThan(5) number; } `), compile(` interface X { @greaterThan(3) @lessThan(5) a?: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', greaterThanValue: 3, lessThanValue: 5, } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 1}, ty)).toEqual(null); expect(validate<any>({a: 2}, ty)).toEqual(null); expect(validate<any>({a: 3}, ty)).toEqual(null); expect(validate<any>({a: 4}, ty)).toEqual({value: {a: 4}}); expect(validate<any>({a: 5}, ty)).toEqual(null); expect(validate<any>({a: 6}, ty)).toEqual(null); expect(validate<any>({a: '4'}, ty)).toEqual(null); } } } }); it("compiler-decorators-13", function() { const schemas = [compile(` type X = @greaterThan('C') @lessThan('E') string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', greaterThanValue: 'C', lessThanValue: 'E', }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>('A', ty)).toEqual(null); expect(validate<any>('B', ty)).toEqual(null); expect(validate<any>('C', ty)).toEqual(null); expect(validate<any>('D', ty)).toEqual({value: 'D'}); expect(validate<any>('E', ty)).toEqual(null); expect(validate<any>('F', ty)).toEqual(null); } } } }); it("compiler-decorators-14", function() { const schemas = [compile(` interface X { a: @greaterThan('C') @lessThan('E') string; } `), compile(` interface X { @greaterThan('C') @lessThan('E') a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', greaterThanValue: 'C', lessThanValue: 'E', }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual(null); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual(null); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); it("compiler-decorators-15", function() { const schemas = [compile(` interface X { a?: @greaterThan('C') @lessThan('E') string; } `), compile(` interface X { @greaterThan('C') @lessThan('E') a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', greaterThanValue: 'C', lessThanValue: 'E', } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual(null); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual(null); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); it("compiler-decorators-16", function() { const schemas = [compile(` type X = @match(/^[C-E]$/) string; `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'primitive', primitiveName: 'string', pattern: /^[C-E]$/, }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>('A', ty)).toEqual(null); expect(validate<any>('B', ty)).toEqual(null); expect(validate<any>('C', ty)).toEqual({value: 'C'}); expect(validate<any>('D', ty)).toEqual({value: 'D'}); expect(validate<any>('E', ty)).toEqual({value: 'E'}); expect(validate<any>('F', ty)).toEqual(null); } } } }); it("compiler-decorators-17", function() { const schemas = [compile(` interface X { a: @match(/^[C-E]$/) string; } `), compile(` interface X { @match(/^[C-E]$/) a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', pattern: /^[C-E]$/, }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual({value: {a: 'C'}}); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual({value: {a: 'E'}}); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); it("compiler-decorators-18", function() { const schemas = [compile(` interface X { a?: @match(/^[C-E]$/) string; } `), compile(` interface X { @match(/^[C-E]$/) a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'X', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'X', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'X', typeName: 'X', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', pattern: /^[C-E]$/, } }] ], }; // const ty = getType(schema, 'X'); for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) { expect(ty).toEqual(rhs); expect(validate<any>({a: 0}, ty)).toEqual(null); expect(validate<any>({a: 'A'}, ty)).toEqual(null); expect(validate<any>({a: 'B'}, ty)).toEqual(null); expect(validate<any>({a: 'C'}, ty)).toEqual({value: {a: 'C'}}); expect(validate<any>({a: 'D'}, ty)).toEqual({value: {a: 'D'}}); expect(validate<any>({a: 'E'}, ty)).toEqual({value: {a: 'E'}}); expect(validate<any>({a: 'F'}, ty)).toEqual(null); } } } }); });
the_stack
import yoga from 'yoga-layout-prebuilt'; import { ReactTestRendererNode } from 'react-test-renderer'; import { ViewStyle, PlatformBridge } from '../types'; import { Context } from '../utils/Context'; import { createStringMeasurer } from '../utils/createStringMeasurer'; import { hasAnyDefined } from '../utils/hasAnyDefined'; import { pick } from '../utils/pick'; import { computeTextTree } from './computeTextTree'; import { INHERITABLE_FONT_STYLES } from '../utils/constants'; import { isDefined } from '../utils/isDefined'; import { getSymbolMasterById } from '../symbol'; // flatten all styles (including nested) into one object export const getStyles = (node: ReactTestRendererNode): ViewStyle => { if (typeof node === 'string') { return {}; } let { style } = node.props; if (Array.isArray(style)) { const flattened = Array.prototype.concat.apply([], style); const themeFlattened = Array.prototype.concat.apply([], flattened); const objectsOnly = themeFlattened.filter((f) => f); style = Object.assign({}, ...objectsOnly); } return style; }; export const computeYogaNode = (bridge: PlatformBridge) => ( node: ReactTestRendererNode, context: Context, ): { node: yoga.YogaNode; stop?: boolean } => { const yogaNode = yoga.Node.create(); const hasStyle = typeof node !== 'string' && node.props && node.props.style; const style: ViewStyle = hasStyle ? getStyles(node) : {}; // Setup default symbol instance dimensions if (typeof node !== 'string' && node.type === 'sketch_symbolinstance') { const symbolProps = node.props; const symbolMaster = getSymbolMasterById(symbolProps.symbolID); if (!symbolMaster) { throw new Error('Cannot find Symbol Master with id ' + symbolProps.symbolID); } const { frame } = symbolMaster; yogaNode.setWidth(frame.width); yogaNode.setHeight(frame.height); } if (typeof node !== 'string' && node.type === 'sketch_svg') { const svgProps = node.props; // Width if (isDefined(svgProps.width)) { yogaNode.setWidth(svgProps.width); } // Height if (isDefined(svgProps.height)) { yogaNode.setHeight(svgProps.height); } } if (hasStyle) { // http://facebook.github.io/react-native/releases/0.48/docs/layout-props.html // Width if (isDefined(style.width)) { yogaNode.setWidth(style.width); } // Height if (isDefined(style.height)) { yogaNode.setHeight(style.height); } // Min-Height if (isDefined(style.minHeight)) { yogaNode.setMinHeight(style.minHeight); } // Min-Width if (isDefined(style.minWidth)) { yogaNode.setMinWidth(style.minWidth); } // Max-Height if (isDefined(style.maxHeight)) { yogaNode.setMaxHeight(style.maxHeight); } // Min-Width if (isDefined(style.maxWidth)) { yogaNode.setMaxWidth(style.maxWidth); } // Margin if (isDefined(style.marginTop)) { yogaNode.setMargin(yoga.EDGE_TOP, style.marginTop); } if (isDefined(style.marginBottom)) { yogaNode.setMargin(yoga.EDGE_BOTTOM, style.marginBottom); } if (isDefined(style.marginLeft)) { yogaNode.setMargin(yoga.EDGE_LEFT, style.marginLeft); } if (isDefined(style.marginRight)) { yogaNode.setMargin(yoga.EDGE_RIGHT, style.marginRight); } if (isDefined(style.marginVertical)) { yogaNode.setMargin(yoga.EDGE_VERTICAL, style.marginVertical); } if (isDefined(style.marginHorizontal)) { yogaNode.setMargin(yoga.EDGE_HORIZONTAL, style.marginHorizontal); } if (isDefined(style.margin)) { yogaNode.setMargin(yoga.EDGE_ALL, style.margin); } // Padding if (isDefined(style.paddingTop)) { yogaNode.setPadding(yoga.EDGE_TOP, style.paddingTop); } if (isDefined(style.paddingBottom)) { yogaNode.setPadding(yoga.EDGE_BOTTOM, style.paddingBottom); } if (isDefined(style.paddingLeft)) { yogaNode.setPadding(yoga.EDGE_LEFT, style.paddingLeft); } if (isDefined(style.paddingRight)) { yogaNode.setPadding(yoga.EDGE_RIGHT, style.paddingRight); } if (isDefined(style.paddingVertical)) { yogaNode.setPadding(yoga.EDGE_VERTICAL, style.paddingVertical); } if (isDefined(style.paddingHorizontal)) { yogaNode.setPadding(yoga.EDGE_HORIZONTAL, style.paddingHorizontal); } if (isDefined(style.padding)) { yogaNode.setPadding(yoga.EDGE_ALL, style.padding); } // Border if (isDefined(style.borderTopWidth)) { yogaNode.setBorder(yoga.EDGE_TOP, style.borderTopWidth); } if (isDefined(style.borderBottomWidth)) { yogaNode.setBorder(yoga.EDGE_BOTTOM, style.borderBottomWidth); } if (isDefined(style.borderLeftWidth)) { yogaNode.setBorder(yoga.EDGE_LEFT, style.borderLeftWidth); } if (isDefined(style.borderRightWidth)) { yogaNode.setBorder(yoga.EDGE_RIGHT, style.borderRightWidth); } if (isDefined(style.borderWidth)) { yogaNode.setBorder(yoga.EDGE_ALL, style.borderWidth); } // Flex if (isDefined(style.flex)) { yogaNode.setFlex(style.flex); } if (isDefined(style.flexGrow)) { yogaNode.setFlexGrow(style.flexGrow); } if (isDefined(style.flexShrink)) { yogaNode.setFlexShrink(style.flexShrink); } if (isDefined(style.flexBasis)) { yogaNode.setFlexBasis(style.flexBasis); } // Position if (style.position === 'absolute') { yogaNode.setPositionType(yoga.POSITION_TYPE_ABSOLUTE); } if (style.position === 'relative') { yogaNode.setPositionType(yoga.POSITION_TYPE_RELATIVE); } if (isDefined(style.top)) { yogaNode.setPosition(yoga.EDGE_TOP, style.top); } if (isDefined(style.left)) { yogaNode.setPosition(yoga.EDGE_LEFT, style.left); } if (isDefined(style.right)) { yogaNode.setPosition(yoga.EDGE_RIGHT, style.right); } if (isDefined(style.bottom)) { yogaNode.setPosition(yoga.EDGE_BOTTOM, style.bottom); } // Display if (style.display) { if (style.display === 'flex') { yogaNode.setDisplay(yoga.DISPLAY_FLEX); } if (style.display === 'none') { yogaNode.setDisplay(yoga.DISPLAY_NONE); } } // Overflow if (style.overflow) { if (style.overflow === 'visible') { yogaNode.setOverflow(yoga.OVERFLOW_VISIBLE); } if (style.overflow === 'scroll') { yogaNode.setOverflow(yoga.OVERFLOW_SCROLL); } if (style.overflow === 'hidden') { yogaNode.setOverflow(yoga.OVERFLOW_HIDDEN); } } // Flex direction if (style.flexDirection) { if (style.flexDirection === 'row') { yogaNode.setFlexDirection(yoga.FLEX_DIRECTION_ROW); } if (style.flexDirection === 'column') { yogaNode.setFlexDirection(yoga.FLEX_DIRECTION_COLUMN); } if (style.flexDirection === 'row-reverse') { yogaNode.setFlexDirection(yoga.FLEX_DIRECTION_ROW_REVERSE); } if (style.flexDirection === 'column-reverse') { yogaNode.setFlexDirection(yoga.FLEX_DIRECTION_COLUMN_REVERSE); } } // Justify Content if (style.justifyContent) { if (style.justifyContent === 'flex-start') { yogaNode.setJustifyContent(yoga.JUSTIFY_FLEX_START); } if (style.justifyContent === 'flex-end') { yogaNode.setJustifyContent(yoga.JUSTIFY_FLEX_END); } if (style.justifyContent === 'center') { yogaNode.setJustifyContent(yoga.JUSTIFY_CENTER); } if (style.justifyContent === 'space-between') { yogaNode.setJustifyContent(yoga.JUSTIFY_SPACE_BETWEEN); } if (style.justifyContent === 'space-around') { yogaNode.setJustifyContent(yoga.JUSTIFY_SPACE_AROUND); } } // Align Content if (style.alignContent) { if (style.alignContent === 'flex-start') { yogaNode.setAlignContent(yoga.ALIGN_FLEX_START); } if (style.alignContent === 'flex-end') { yogaNode.setAlignContent(yoga.ALIGN_FLEX_END); } if (style.alignContent === 'center') { yogaNode.setAlignContent(yoga.ALIGN_CENTER); } if (style.alignContent === 'stretch') { yogaNode.setAlignContent(yoga.ALIGN_STRETCH); } if (style.alignContent === 'baseline') { yogaNode.setAlignContent(yoga.ALIGN_BASELINE); } if (style.alignContent === 'space-between') { yogaNode.setAlignContent(yoga.ALIGN_SPACE_BETWEEN); } if (style.alignContent === 'space-around') { yogaNode.setAlignContent(yoga.ALIGN_SPACE_AROUND); } if (style.alignContent === 'auto') { yogaNode.setAlignContent(yoga.ALIGN_AUTO); } } // Align Items if (style.alignItems) { if (style.alignItems === 'flex-start') { yogaNode.setAlignItems(yoga.ALIGN_FLEX_START); } if (style.alignItems === 'flex-end') { yogaNode.setAlignItems(yoga.ALIGN_FLEX_END); } if (style.alignItems === 'center') { yogaNode.setAlignItems(yoga.ALIGN_CENTER); } if (style.alignItems === 'stretch') { yogaNode.setAlignItems(yoga.ALIGN_STRETCH); } if (style.alignItems === 'baseline') { yogaNode.setAlignItems(yoga.ALIGN_BASELINE); } } // Align Self if (style.alignSelf) { if (style.alignSelf === 'flex-start') { yogaNode.setAlignSelf(yoga.ALIGN_FLEX_START); } if (style.alignSelf === 'flex-end') { yogaNode.setAlignSelf(yoga.ALIGN_FLEX_END); } if (style.alignSelf === 'center') { yogaNode.setAlignSelf(yoga.ALIGN_CENTER); } if (style.alignSelf === 'stretch') { yogaNode.setAlignSelf(yoga.ALIGN_STRETCH); } if (style.alignSelf === 'baseline') { yogaNode.setAlignSelf(yoga.ALIGN_BASELINE); } } // Flex Wrap if (style.flexWrap) { if (style.flexWrap === 'nowrap') { yogaNode.setFlexWrap(yoga.WRAP_NO_WRAP); } if (style.flexWrap === 'wrap') { yogaNode.setFlexWrap(yoga.WRAP_WRAP); } if (style.flexWrap === 'wrap-reverse') { yogaNode.setFlexWrap(yoga.WRAP_WRAP_REVERSE); } } } if (typeof node === 'string' || node.type === 'sketch_text') { // If current node is a Text node, add text styles to Context to pass down to // child nodes. if ( typeof node !== 'string' && node.props && node.props.style && hasAnyDefined(style, INHERITABLE_FONT_STYLES) ) { // @ts-ignore const inheritableStyles = pick(style, INHERITABLE_FONT_STYLES); context.addInheritableStyles(inheritableStyles); } // Handle Text Children const textNodes = computeTextTree(node, context); yogaNode.setMeasureFunc(createStringMeasurer(bridge)(textNodes)); return { node: yogaNode, stop: true }; } return { node: yogaNode }; };
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { class OrganizationApi { /** * DynamicsCrm.DevKit OrganizationApi * @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; /** ACI Web Endpoint URL. */ ACIWebEndpointUrl: DevKit.WebApi.StringValue; /** Unique identifier of the template to be used for acknowledgement when a user unsubscribes. */ AcknowledgementTemplateId: DevKit.WebApi.LookupValue; /** Flag to indicate if the Advanced Lookup feature is enabled for lookup controls */ AdvancedLookupEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether background address book synchronization in Microsoft Office Outlook is allowed. */ AllowAddressBookSyncs: DevKit.WebApi.BooleanValue; /** Indicates whether automatic response creation is allowed. */ AllowAutoResponseCreation: DevKit.WebApi.BooleanValue; /** Indicates whether automatic unsubscribe is allowed. */ AllowAutoUnsubscribe: DevKit.WebApi.BooleanValue; /** Indicates whether automatic unsubscribe acknowledgement email is allowed to send. */ AllowAutoUnsubscribeAcknowledgement: DevKit.WebApi.BooleanValue; /** Indicates whether Outlook Client message bar advertisement is allowed. */ AllowClientMessageBarAd: DevKit.WebApi.BooleanValue; /** Indicates whether auditing of changes to entity is allowed when no attributes have changed. */ AllowEntityOnlyAudit: DevKit.WebApi.BooleanValue; /** Enable access to legacy web client UI */ AllowLegacyClientExperience: DevKit.WebApi.BooleanValue; /** Enable embedding of certain legacy dialogs in Unified Interface browser client */ AllowLegacyDialogsEmbedding: DevKit.WebApi.BooleanValue; /** Indicates whether marketing emails execution is allowed. */ AllowMarketingEmailExecution: DevKit.WebApi.BooleanValue; /** Indicates whether background offline synchronization in Microsoft Office Outlook is allowed. */ AllowOfflineScheduledSyncs: DevKit.WebApi.BooleanValue; /** Indicates whether scheduled synchronizations to Outlook are allowed. */ AllowOutlookScheduledSyncs: DevKit.WebApi.BooleanValue; /** Indicates whether users are allowed to send email to unresolved parties (parties must still have an email address). */ AllowUnresolvedPartiesOnEmailSend: DevKit.WebApi.BooleanValue; /** Indicates whether individuals can select their form mode preference in their personal options. */ AllowUserFormModePreference: DevKit.WebApi.BooleanValue; /** Indicates whether the showing tablet application notification bars in a browser is allowed. */ AllowUsersSeeAppdownloadMessage: DevKit.WebApi.BooleanValue; /** Indicates whether Web-based export of grids to Microsoft Office Excel is allowed. */ AllowWebExcelExport: DevKit.WebApi.BooleanValue; /** AM designator to use throughout Microsoft Dynamics CRM. */ AMDesignator: DevKit.WebApi.StringValue; /** Indicates whether the appDesignerExperience is enabled for the organization. */ AppDesignerExperienceEnabled: DevKit.WebApi.BooleanValue; /** Information on whether rich editing experience for Appointment is enabled. */ AppointmentRichEditorExperience: DevKit.WebApi.BooleanValue; /** Audit Retention Period settings stored in Organization Database. */ AuditRetentionPeriod: DevKit.WebApi.IntegerValue; /** Audit Retention Period settings stored in Organization Database. */ AuditRetentionPeriodV2: DevKit.WebApi.IntegerValue; /** Select whether to auto apply the default customer entitlement on case creation. */ AutoApplyDefaultonCaseCreate: DevKit.WebApi.BooleanValue; /** Select whether to auto apply the default customer entitlement on case update. */ AutoApplyDefaultonCaseUpdate: DevKit.WebApi.BooleanValue; /** Indicates whether to Auto-apply SLA on case record update after SLA was manually applied. */ AutoApplySLA: DevKit.WebApi.BooleanValue; /** For internal use only. */ AzureSchedulerJobCollectionName: DevKit.WebApi.StringValue; /** Unique identifier of the base currency of the organization. */ BaseCurrencyId: DevKit.WebApi.LookupValue; /** Number of decimal places that can be used for the base currency. */ BaseCurrencyPrecision: DevKit.WebApi.IntegerValueReadonly; /** Symbol used for the base currency. */ BaseCurrencySymbol: DevKit.WebApi.StringValueReadonly; BaseISOCurrencyCode: DevKit.WebApi.StringValueReadonly; /** Api Key to be used in requests to Bing Maps services. */ BingMapsApiKey: DevKit.WebApi.StringValue; /** Prevent upload or download of certain attachment types that are considered dangerous. */ BlockedAttachments: DevKit.WebApi.StringValue; /** Display cards in expanded state for interactive dashboard */ BoundDashboardDefaultCardExpanded: DevKit.WebApi.BooleanValue; /** Prefix used for bulk operation numbering. */ BulkOperationPrefix: DevKit.WebApi.StringValue; /** BusinessCardOptions */ BusinessCardOptions: DevKit.WebApi.StringValue; /** Unique identifier of the business closure calendar of organization. */ BusinessClosureCalendarId: DevKit.WebApi.GuidValue; /** Calendar type for the system. Set to Gregorian US by default. */ CalendarType: DevKit.WebApi.IntegerValue; /** Prefix used for campaign numbering. */ CampaignPrefix: DevKit.WebApi.StringValue; /** Indicates whether the organization can opt out of the new Relevance search experience (released in Oct 2020) */ CanOptOutNewSearchExperience: DevKit.WebApi.BooleanValue; /** Flag to cascade Update on incident. */ CascadeStatusUpdate: DevKit.WebApi.BooleanValue; /** Prefix to use for all cases throughout Microsoft Dynamics 365. */ CasePrefix: DevKit.WebApi.StringValue; /** Type the prefix to use for all categories in Microsoft Dynamics 365. */ CategoryPrefix: DevKit.WebApi.StringValue; /** Client Features to be enabled as an XML BLOB. */ ClientFeatureSet: DevKit.WebApi.StringValue; /** Policy configuration for CSP */ ContentSecurityPolicyConfiguration: DevKit.WebApi.StringValue; /** Prefix to use for all contracts throughout Microsoft Dynamics 365. */ ContractPrefix: DevKit.WebApi.StringValue; /** Indicates whether the feature CortanaProactiveExperience Flow processes should be enabled for the organization. */ CortanaProactiveExperienceEnabled: DevKit.WebApi.BooleanValue; /** Unique identifier of the user who created the organization. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the organization was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the organization. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enable Initial state of newly created products to be Active instead of Draft */ CreateProductsWithoutParentInActiveState: DevKit.WebApi.BooleanValue; /** Number of decimal places that can be used for currency. */ CurrencyDecimalPrecision: DevKit.WebApi.IntegerValue; /** Indicates whether to display money fields with currency code or currency symbol. */ CurrencyDisplayOption: DevKit.WebApi.OptionSetValue; /** Information about how currency symbols are placed throughout Microsoft Dynamics CRM. */ CurrencyFormatCode: DevKit.WebApi.OptionSetValue; /** Symbol used for currency throughout Microsoft Dynamics 365. */ CurrencySymbol: DevKit.WebApi.StringValue; /** Import sequence to use. */ CurrentImportSequenceNumber: DevKit.WebApi.IntegerValueReadonly; /** First parsed table number to use. */ CurrentParsedTableNumber: DevKit.WebApi.IntegerValueReadonly; /** Information about how the date is displayed throughout Microsoft CRM. */ DateFormatCode: DevKit.WebApi.OptionSetValue; /** String showing how the date is displayed throughout Microsoft CRM. */ DateFormatString: DevKit.WebApi.StringValue; /** Character used to separate the month, the day, and the year in dates throughout Microsoft Dynamics 365. */ DateSeparator: DevKit.WebApi.StringValue; /** The maximum value for the Mobile Offline setting Days since record last modified */ DaysSinceRecordLastModifiedMaxValue: DevKit.WebApi.IntegerValueReadonly; /** Symbol used for decimal in Microsoft Dynamics 365. */ DecimalSymbol: DevKit.WebApi.StringValue; /** Text area to enter default country code. */ DefaultCountryCode: DevKit.WebApi.StringValue; /** Name of the default crm custom. */ DefaultCrmCustomName: DevKit.WebApi.StringValue; /** Unique identifier of the default email server profile. */ DefaultEmailServerProfileId: DevKit.WebApi.LookupValue; /** XML string containing the default email settings that are applied when a user or queue is created. */ DefaultEmailSettings: DevKit.WebApi.StringValue; /** Unique identifier of the default mobile offline profile. */ DefaultMobileOfflineProfileId: DevKit.WebApi.LookupValue; /** Type of default recurrence end range date. */ DefaultRecurrenceEndRangeType: DevKit.WebApi.OptionSetValue; /** Default theme data for the organization. */ DefaultThemeData: DevKit.WebApi.StringValue; /** Unique identifier of the delegated admin user for the organization. */ DelegatedAdminUserId: DevKit.WebApi.GuidValue; /** Reason for disabling the organization. */ DisabledReason: DevKit.WebApi.StringValueReadonly; /** Indicates whether Social Care is disabled. */ DisableSocialCare: DevKit.WebApi.BooleanValue; /** Discount calculation method for the QOOI product. */ DiscountCalculationMethod: DevKit.WebApi.OptionSetValue; /** Indicates whether or not navigation tour is displayed. */ DisplayNavigationTour: DevKit.WebApi.BooleanValue; /** Select if you want to use the Email Router or server-side synchronization for email processing. */ EmailConnectionChannel: DevKit.WebApi.OptionSetValue; /** Flag to turn email correlation on or off. */ EmailCorrelationEnabled: DevKit.WebApi.BooleanValue; /** Normal polling frequency used for sending email in Microsoft Office Outlook. */ EmailSendPollingPeriod: DevKit.WebApi.IntegerValue; /** Enable Integration with Bing Maps */ EnableBingMapsIntegration: DevKit.WebApi.BooleanValue; /** Enable Integration with Immersive Skype */ EnableImmersiveSkypeIntegration: DevKit.WebApi.BooleanValue; /** Indicates whether the user has enabled or disabled Live Persona Card feature in UCI. */ EnableLivePersonaCardUCI: DevKit.WebApi.BooleanValue; /** Indicates whether the user has enabled or disabled LivePersonCardIntegration in Office. */ EnableLivePersonCardIntegrationInOffice: DevKit.WebApi.BooleanValue; /** Select to enable learning path auhtoring. */ EnableLPAuthoring: DevKit.WebApi.BooleanValue; /** Enable Integration with Microsoft Flow */ EnableMicrosoftFlowIntegration: DevKit.WebApi.BooleanValue; /** Enable pricing calculations on a Create call. */ EnablePricingOnCreate: DevKit.WebApi.BooleanValue; /** Use Smart Matching. */ EnableSmartMatching: DevKit.WebApi.BooleanValue; /** Enable site map and commanding update */ EnableUnifiedInterfaceShellRefresh: DevKit.WebApi.BooleanValue; /** Organization setting to enforce read only plugins. */ EnforceReadOnlyPlugins: DevKit.WebApi.BooleanValue; /** The default image for the entity. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Maximum number of days to keep change tracking deleted records */ ExpireChangeTrackingInDays: DevKit.WebApi.IntegerValue; /** Maximum number of days before deleting inactive subscriptions. */ ExpireSubscriptionsInDays: DevKit.WebApi.IntegerValue; /** Specify the base URL to use to look for external document suggestions. */ ExternalBaseUrl: DevKit.WebApi.StringValue; /** XML string containing the ExternalPartyEnabled entities correlation keys for association of existing External Party instance entities to newly created IsExternalPartyEnabled entities.For internal use only */ ExternalPartyCorrelationKeys: DevKit.WebApi.StringValue; /** XML string containing the ExternalPartyEnabled entities settings. */ ExternalPartyEntitySettings: DevKit.WebApi.StringValue; /** Features to be enabled as an XML BLOB. */ FeatureSet: DevKit.WebApi.StringValue; /** Start date for the fiscal period that is to be used throughout Microsoft CRM. */ FiscalCalendarStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Information that specifies how the name of the fiscal period is displayed throughout Microsoft CRM. */ FiscalPeriodFormat: DevKit.WebApi.StringValue; /** Format in which the fiscal period will be displayed. */ FiscalPeriodFormatPeriod: DevKit.WebApi.OptionSetValue; /** Type of fiscal period used throughout Microsoft CRM. */ FiscalPeriodType: DevKit.WebApi.IntegerValue; /** Information that specifies whether the fiscal year should be displayed based on the start date or the end date of the fiscal year. */ FiscalYearDisplayCode: DevKit.WebApi.IntegerValue; /** Information that specifies how the name of the fiscal year is displayed throughout Microsoft CRM. */ FiscalYearFormat: DevKit.WebApi.StringValue; /** Prefix for the display of the fiscal year. */ FiscalYearFormatPrefix: DevKit.WebApi.OptionSetValue; /** Suffix for the display of the fiscal year. */ FiscalYearFormatSuffix: DevKit.WebApi.OptionSetValue; /** Format for the year. */ FiscalYearFormatYear: DevKit.WebApi.OptionSetValue; /** Information that specifies how the names of the fiscal year and the fiscal period should be connected when displayed together. */ FiscalYearPeriodConnect: DevKit.WebApi.StringValue; /** Order in which names are to be displayed throughout Microsoft CRM. */ FullNameConventionCode: DevKit.WebApi.OptionSetValue; /** Specifies the maximum number of months in future for which the recurring activities can be created. */ FutureExpansionWindow: DevKit.WebApi.IntegerValue; /** Indicates whether alerts will be generated for errors. */ GenerateAlertsForErrors: DevKit.WebApi.BooleanValue; /** Indicates whether alerts will be generated for information. */ GenerateAlertsForInformation: DevKit.WebApi.BooleanValue; /** Indicates whether alerts will be generated for warnings. */ GenerateAlertsForWarnings: DevKit.WebApi.BooleanValue; /** Indicates whether Get Started content is enabled for this organization. */ GetStartedPaneContentEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the append URL parameters is enabled. */ GlobalAppendUrlParametersEnabled: DevKit.WebApi.BooleanValue; /** URL for the web page global help. */ GlobalHelpUrl: DevKit.WebApi.StringValue; /** Indicates whether the customizable global help is enabled. */ GlobalHelpUrlEnabled: DevKit.WebApi.BooleanValue; /** Number of days after the goal's end date after which the rollup of the goal stops automatically. */ GoalRollupExpiryTime: DevKit.WebApi.IntegerValue; /** Number of hours between automatic rollup jobs . */ GoalRollupFrequency: DevKit.WebApi.IntegerValue; /** For internal use only. */ GrantAccessToNetworkService: DevKit.WebApi.BooleanValue; /** Maximum difference allowed between subject keywords count of the email messaged to be correlated */ HashDeltaSubjectCount: DevKit.WebApi.IntegerValue; /** Filter Subject Keywords */ HashFilterKeywords: DevKit.WebApi.StringValue; /** Maximum number of subject keywords or recipients used for correlation */ HashMaxCount: DevKit.WebApi.IntegerValue; /** Minimum number of recipients required to match for email messaged to be correlated */ HashMinAddressCount: DevKit.WebApi.IntegerValue; /** High contrast theme data for the organization. */ HighContrastThemeData: DevKit.WebApi.StringValue; /** Indicates whether incoming email sent by internal Microsoft Dynamics 365 users or queues should be tracked. */ IgnoreInternalEmail: DevKit.WebApi.BooleanValue; /** Indicates whether an organization has consented to sharing search query data to help improve search results */ ImproveSearchLoggingEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether Inactivity timeout is enabled */ InactivityTimeoutEnabled: DevKit.WebApi.BooleanValue; /** Inactivity timeout in minutes */ InactivityTimeoutInMins: DevKit.WebApi.IntegerValue; /** Inactivity timeout reminder in minutes */ InactivityTimeoutReminderInMins: DevKit.WebApi.IntegerValue; /** Setting for the Async Service Mailbox Queue. Defines the retrieval batch size of exchange server. */ IncomingEmailExchangeEmailRetrievalBatchSize: DevKit.WebApi.IntegerValue; /** Initial version of the organization. */ InitialVersion: DevKit.WebApi.StringValue; /** Unique identifier of the integration user for the organization. */ IntegrationUserId: DevKit.WebApi.GuidValue; /** Prefix to use for all invoice numbers throughout Microsoft Dynamics 365. */ InvoicePrefix: DevKit.WebApi.StringValue; /** Indicates whether the feature Action Card should be enabled for the organization. */ IsActionCardEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether Action Support Feature is enabled */ IsActionSupportFeatureEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Relationship Analytics should be enabled for the organization. */ IsActivityAnalysisEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether all money attributes are converted to decimal. */ IsAllMoneyDecimal: DevKit.WebApi.BooleanValueReadonly; /** Indicates whether loading of Microsoft Dynamics 365 in a browser window that does not have address, tool, and menu bars is enabled. */ IsAppMode: DevKit.WebApi.BooleanValue; /** Enable or disable attachments sync for outlook and exchange. */ IsAppointmentAttachmentSyncEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable assigned tasks sync for outlook and exchange. */ IsAssignedTasksSyncEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable auditing of changes. */ IsAuditEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Auto Capture should be enabled for the organization. */ IsAutoDataCaptureEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the V2 feature of Auto Capture should be enabled for the organization. */ IsAutoDataCaptureV2Enabled: DevKit.WebApi.BooleanValue; /** Information on whether auto save is enabled. */ IsAutoSaveEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether BPF Entity Customization Feature is enabled */ IsBPFEntityCustomizationFeatureEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether conflict detection for mobile client is enabled. */ IsConflictDetectionEnabledForMobileClient: DevKit.WebApi.BooleanValue; /** Enable or disable mailing address sync for outlook and exchange. */ IsContactMailingAddressSyncEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Content Security Policy has been enabled for the organization. */ IsContentSecurityPolicyEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Contextual email experience is enabled on this organization */ IsContextualEmailEnabled: DevKit.WebApi.BooleanValue; /** Select to enable Contextual Help in UCI. */ IsContextualHelpEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Custom Controls in canvas PowerApps feature has been enabled for the organization. */ IsCustomControlsInCanvasAppsEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable country code selection. */ IsDefaultCountryCodeCheckEnabled: DevKit.WebApi.BooleanValue; /** Enable Delegation Access content */ IsDelegateAccessEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Action Hub should be enabled for the organization. */ IsDelveActionHubIntegrationEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether the organization is disabled. */ IsDisabled: DevKit.WebApi.BooleanValueReadonly; /** Indicates whether duplicate detection of records is enabled. */ IsDuplicateDetectionEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether duplicate detection of records during import is enabled. */ IsDuplicateDetectionEnabledForImport: DevKit.WebApi.BooleanValue; /** Indicates whether duplicate detection of records during offline synchronization is enabled. */ IsDuplicateDetectionEnabledForOfflineSync: DevKit.WebApi.BooleanValue; /** Indicates whether duplicate detection during online create or update is enabled. */ IsDuplicateDetectionEnabledForOnlineCreateUpdate: DevKit.WebApi.BooleanValue; /** Allow tracking recipient activity on sent emails. */ IsEmailMonitoringAllowed: DevKit.WebApi.BooleanValue; /** Enable Email Server Profile content filtering */ IsEmailServerProfileContentFilteringEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether appmodule is enabled for all roles */ IsEnabledForAllRoles: DevKit.WebApi.BooleanValue; /** Indicates whether the organization's files are being stored in Azure. */ IsExternalFileStorageEnabled: DevKit.WebApi.BooleanValue; /** Select whether data can be synchronized with an external search index. */ IsExternalSearchIndexEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the fiscal period is displayed as the month number. */ IsFiscalPeriodMonthBased: DevKit.WebApi.BooleanValue; /** Select whether folders should be automatically created on SharePoint. */ IsFolderAutoCreatedonSP: DevKit.WebApi.BooleanValue; /** Enable or disable folder based tracking for Server Side Sync. */ IsFolderBasedTrackingEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether full-text search for Quick Find entities should be enabled for the organization. */ IsFullTextSearchEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether geospatial capabilities leveraging Azure Maps are enabled. */ IsGeospatialAzureMapsIntegrationEnabled: DevKit.WebApi.BooleanValue; /** Enable Hierarchical Security Model */ IsHierarchicalSecurityModelEnabled: DevKit.WebApi.BooleanValue; /** Give Consent to use LUIS in Dynamics 365 Bot */ IsLUISEnabledforD365Bot: DevKit.WebApi.BooleanValue; /** Enable or disable forced unlocking for Server Side Sync mailboxes. */ IsMailboxForcedUnlockingEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable mailbox keep alive for Server Side Sync. */ IsMailboxInactiveBackoffEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Manual Sales Forecasting feature has been enabled for the organization. */ IsManualSalesForecastingEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies whether mobile client on demand sync is enabled. */ IsMobileClientOnDemandSyncEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature MobileOffline should be enabled for the organization. */ IsMobileOfflineEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Model Apps can be embedded within Microsoft Teams. This is a tenant admin controlled preview/experimental feature. */ IsModelDrivenAppsInMSTeamsEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Microsoft Teams Collaboration feature has been enabled for the organization. */ IsMSTeamsCollaborationEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Microsoft Teams integration has been enabled for the organization. */ IsMSTeamsEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the user has enabled or disabled Microsoft Teams integration. */ IsMSTeamsSettingChangedByUser: DevKit.WebApi.BooleanValue; /** Indicates whether Microsoft Teams User Sync feature has been enabled for the organization. */ IsMSTeamsUserSyncEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether new add product experience is enabled. */ IsNewAddProductExperienceEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Notes Analysis should be enabled for the organization. */ IsNotesAnalysisEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature OfficeGraph should be enabled for the organization. */ IsOfficeGraphEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature One Drive should be enabled for the organization. */ IsOneDriveEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether PAI feature has been enabled for the organization. */ IsPAIEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether PDF Generation feature has been enabled for the organization. */ IsPDFGenerationEnabled: DevKit.WebApi.StringValue; /** Indicates whether playbook feature has been enabled for the organization. */ IsPlaybookEnabled: DevKit.WebApi.BooleanValue; /** Information on whether IM presence is enabled. */ IsPresenceEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the Preview feature for Action Card should be enabled for the organization. */ IsPreviewEnabledForActionCard: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Auto Capture should be enabled for the organization at Preview Settings. */ IsPreviewForAutoCaptureEnabled: DevKit.WebApi.BooleanValue; /** Is Preview For Email Monitoring Allowed. */ IsPreviewForEmailMonitoringAllowed: DevKit.WebApi.BooleanValue; /** Indicates whether PriceList is mandatory for adding existing products to sales entities. */ IsPriceListMandatory: DevKit.WebApi.BooleanValue; /** Select whether to use the standard Out-of-box Opportunity Close experience or opt to for a customized experience. */ IsQuickCreateEnabledForOpportunityClose: DevKit.WebApi.BooleanValue; /** Enable or disable auditing of read operations. */ IsReadAuditEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether the feature Relationship Insights should be enabled for the organization. */ IsRelationshipInsightsEnabled: DevKit.WebApi.BooleanValue; /** Indicates if the synchronization of user resource booking with Exchange is enabled at organization level. */ IsResourceBookingExchangeSyncEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether rich text editor for notes experience is enabled on this organization */ IsRichTextNotesEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Sales Assistant mobile app has been enabled for the organization. */ IsSalesAssistantEnabled: DevKit.WebApi.BooleanValue; /** Enable sales order processing integration. */ IsSOPIntegrationEnabled: DevKit.WebApi.BooleanValue; /** Information on whether text wrap is enabled. */ IsTextWrapEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable auditing of user access. */ IsUserAccessAuditEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Write-in Products can be added to Opportunity/Quote/Order/Invoice or not. */ IsWriteInProductsAllowed: DevKit.WebApi.BooleanValue; /** Type the prefix to use for all knowledge articles in Microsoft Dynamics 365. */ KaPrefix: DevKit.WebApi.StringValue; /** Prefix to use for all articles in Microsoft Dynamics 365. */ KbPrefix: DevKit.WebApi.StringValue; /** XML string containing the Knowledge Management settings that are applied in Knowledge Management Wizard. */ KMSettings: DevKit.WebApi.StringValue; /** Preferred language for the organization. */ LanguageCode: DevKit.WebApi.IntegerValue; /** Unique identifier of the locale of the organization. */ LocaleId: DevKit.WebApi.IntegerValue; /** Information that specifies how the Long Date format is displayed in Microsoft Dynamics 365. */ LongDateFormatCode: DevKit.WebApi.IntegerValue; /** Minimum number of characters that should be entered in the lookup control before resolving for suggestions */ LookupCharacterCountBeforeResolve: DevKit.WebApi.IntegerValue; /** Minimum delay (in milliseconds) between consecutive inputs in a lookup control that will trigger a search for suggestions */ LookupResolveDelayMS: DevKit.WebApi.IntegerValue; /** Lower Threshold For Mailbox Intermittent Issue. */ MailboxIntermittentIssueMinRange: DevKit.WebApi.IntegerValue; /** Lower Threshold For Mailbox Permanent Issue. */ MailboxPermanentIssueMinRange: DevKit.WebApi.IntegerValue; /** Maximum number of actionsteps allowed in a BPF */ MaxActionStepsInBPF: DevKit.WebApi.IntegerValue; /** Maximum number of days an appointment can last. */ MaxAppointmentDurationDays: DevKit.WebApi.IntegerValue; /** Maximum number of conditions allowed for mobile offline filters */ MaxConditionsForMobileOfflineFilters: DevKit.WebApi.IntegerValue; /** Maximum depth for hierarchy security propagation. */ MaxDepthForHierarchicalSecurityModel: DevKit.WebApi.IntegerValue; /** Maximum number of Folder Based Tracking mappings user can add */ MaxFolderBasedTrackingMappings: DevKit.WebApi.IntegerValue; /** Maximum number of active business process flows allowed per entity */ MaximumActiveBusinessProcessFlowsAllowedPerEntity: DevKit.WebApi.IntegerValue; /** Restrict the maximum number of product properties for a product family/bundle */ MaximumDynamicPropertiesAllowed: DevKit.WebApi.IntegerValue; /** Maximum number of active SLA allowed per entity in online */ MaximumEntitiesWithActiveSLA: DevKit.WebApi.IntegerValue; /** Maximum number of SLA KPI per active SLA allowed for entity in online */ MaximumSLAKPIPerEntityWithActiveSLA: DevKit.WebApi.IntegerValue; /** Maximum tracking number before recycling takes place. */ MaximumTrackingNumber: DevKit.WebApi.IntegerValue; /** Restrict the maximum no of items in a bundle */ MaxProductsInBundle: DevKit.WebApi.IntegerValue; /** Maximum number of records that will be exported to a static Microsoft Office Excel worksheet when exporting from the grid. */ MaxRecordsForExportToExcel: DevKit.WebApi.IntegerValue; /** Maximum number of lookup and picklist records that can be selected by user for filtering. */ MaxRecordsForLookupFilters: DevKit.WebApi.IntegerValue; MaxSLAItemsPerSLA: DevKit.WebApi.IntegerValue; /** The maximum version of IE to run browser emulation for in Outlook client */ MaxSupportedInternetExplorerVersion: DevKit.WebApi.IntegerValueReadonly; /** Maximum allowed size of an attachment. */ MaxUploadFileSize: DevKit.WebApi.IntegerValue; /** Maximum number of mailboxes that can be toggled for verbose logging */ MaxVerboseLoggingMailbox: DevKit.WebApi.IntegerValueReadonly; /** Maximum number of sync cycles for which verbose logging will be enabled by default */ MaxVerboseLoggingSyncCycles: DevKit.WebApi.IntegerValueReadonly; /** What is the last date/time where there are metadata tracking deleted objects that have never been outside of the expiration period. */ MetadataSyncLastTimeOfNeverExpiredDeletedObjects_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** (Deprecated) Environment selected for Integration with Microsoft Flow */ MicrosoftFlowEnvironment: DevKit.WebApi.StringValue; /** Normal polling frequency used for address book synchronization in Microsoft Office Outlook. */ MinAddressBookSyncInterval: DevKit.WebApi.IntegerValue; /** Normal polling frequency used for background offline synchronization in Microsoft Office Outlook. */ MinOfflineSyncInterval: DevKit.WebApi.IntegerValue; /** Minimum allowed time between scheduled Outlook synchronizations. */ MinOutlookSyncInterval: DevKit.WebApi.IntegerValue; /** Minimum number of user license required for mobile offline service by production/preview organization */ MobileOfflineMinLicenseProd: DevKit.WebApi.IntegerValueReadonly; /** Minimum number of user license required for mobile offline service by trial organization */ MobileOfflineMinLicenseTrial: DevKit.WebApi.IntegerValueReadonly; /** Sync interval for mobile offline. */ MobileOfflineSyncInterval: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who last modified the organization. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the organization was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the organization. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the organization. The name is set when Microsoft CRM is installed and should not be changed. */ Name: DevKit.WebApi.StringValue; /** Information that specifies how negative currency numbers are displayed throughout Microsoft Dynamics 365. */ NegativeCurrencyFormatCode: DevKit.WebApi.IntegerValue; /** Information that specifies how negative numbers are displayed throughout Microsoft CRM. */ NegativeFormatCode: DevKit.WebApi.OptionSetValue; /** Indicates whether an organization has enabled the new Relevance search experience (released in Oct 2020) for the organization */ NewSearchExperienceEnabled: DevKit.WebApi.BooleanValue; /** Next entity type code to use for custom entities. */ NextCustomObjectTypeCode: DevKit.WebApi.IntegerValueReadonly; /** Next token to be placed on the subject line of an email message. */ NextTrackingNumber: DevKit.WebApi.IntegerValue; /** Indicates whether mailbox owners will be notified of email server profile level alerts. */ NotifyMailboxOwnerOfEmailServerLevelAlerts: DevKit.WebApi.BooleanValue; /** Specification of how numbers are displayed throughout Microsoft CRM. */ NumberFormat: DevKit.WebApi.StringValue; /** Specifies how numbers are grouped in Microsoft Dynamics 365. */ NumberGroupFormat: DevKit.WebApi.StringValue; /** Symbol used for number separation in Microsoft Dynamics 365. */ NumberSeparator: DevKit.WebApi.StringValue; /** Indicates whether the Office Apps auto deployment is enabled for the organization. */ OfficeAppsAutoDeploymentEnabled: DevKit.WebApi.BooleanValue; /** The url to open the Delve for the organization. */ OfficeGraphDelveUrl: DevKit.WebApi.StringValue; /** Enable OOB pricing calculation logic for Opportunity, Quote, Order and Invoice entities. */ OOBPriceCalculationEnabled: DevKit.WebApi.BooleanValue; /** Prefix to use for all orders throughout Microsoft Dynamics 365. */ OrderPrefix: DevKit.WebApi.StringValue; /** Unique identifier of the organization. */ OrganizationId: DevKit.WebApi.GuidValueReadonly; /** Indicates the organization lifecycle state */ OrganizationState: DevKit.WebApi.OptionSetValueReadonly; /** Organization settings stored in Organization Database. */ OrgDbOrgSettings: DevKit.WebApi.StringValue; /** Select whether to turn on OrgInsights for the organization. */ OrgInsightsEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether Preview feature has been enabled for the organization. */ PaiPreviewScenarioEnabled: DevKit.WebApi.BooleanValue; /** Prefix used for parsed table columns. */ ParsedTableColumnPrefix: DevKit.WebApi.StringValueReadonly; /** Prefix used for parsed tables. */ ParsedTablePrefix: DevKit.WebApi.StringValueReadonly; /** Specifies the maximum number of months in past for which the recurring activities can be created. */ PastExpansionWindow: DevKit.WebApi.IntegerValue; /** For internal use only. */ Picture: DevKit.WebApi.StringValue; PinpointLanguageCode: DevKit.WebApi.IntegerValue; /** Plug-in Trace Log Setting for the Organization. */ PluginTraceLogSetting: DevKit.WebApi.OptionSetValue; /** PM designator to use throughout Microsoft Dynamics 365. */ PMDesignator: DevKit.WebApi.StringValue; /** For internal use only. */ PostMessageWhitelistDomains: DevKit.WebApi.StringValue; /** Indicates whether the Power BI feature should be enabled for the organization. */ PowerBiFeatureEnabled: DevKit.WebApi.BooleanValue; /** Number of decimal places that can be used for prices. */ PricingDecimalPrecision: DevKit.WebApi.IntegerValue; /** Privacy Statement URL */ PrivacyStatementUrl: DevKit.WebApi.StringValue; /** Unique identifier of the default privilege for users in the organization. */ PrivilegeUserGroupId: DevKit.WebApi.GuidValue; /** For internal use only. */ PrivReportingGroupId: DevKit.WebApi.GuidValue; /** For internal use only. */ PrivReportingGroupName: DevKit.WebApi.StringValue; /** Select whether to turn on product recommendations for the organization. */ ProductRecommendationsEnabled: DevKit.WebApi.BooleanValue; /** Indicates whether prompt should be shown for new Qualify Lead Experience */ QualifyLeadAdditionalOptions: DevKit.WebApi.StringValue; /** Indicates whether a quick find record limit should be enabled for this organization (allows for faster Quick Find queries but prevents overly broad searches). */ QuickFindRecordLimitEnabled: DevKit.WebApi.BooleanValue; /** Prefix to use for all quotes throughout Microsoft Dynamics 365. */ QuotePrefix: DevKit.WebApi.StringValue; /** Specifies the default value for number of occurrences field in the recurrence dialog. */ RecurrenceDefaultNumberOfOccurrences: DevKit.WebApi.IntegerValue; /** Specifies the interval (in seconds) for pausing expansion job. */ RecurrenceExpansionJobBatchInterval: DevKit.WebApi.IntegerValue; /** Specifies the value for number of instances created in on demand job in one shot. */ RecurrenceExpansionJobBatchSize: DevKit.WebApi.IntegerValue; /** Specifies the maximum number of instances to be created synchronously after creating a recurring appointment. */ RecurrenceExpansionSynchCreateMax: DevKit.WebApi.IntegerValue; /** Indicates whether relevance search was enabled for the environment as part of Dataverse's relevance search on-by-default sweep */ RelevanceSearchEnabledByPlatform: DevKit.WebApi.BooleanValue; /** Flag to render the body of email in the Web form in an IFRAME with the security='restricted' attribute set. This is additional security but can cause a credentials prompt. */ RenderSecureIFrameForEmail: DevKit.WebApi.BooleanValue; /** For internal use only. */ ReportingGroupId: DevKit.WebApi.GuidValue; /** For internal use only. */ ReportingGroupName: DevKit.WebApi.StringValue; /** Picklist for selecting the organization preference for reporting scripting errors. */ ReportScriptErrors: DevKit.WebApi.OptionSetValue; /** Indicates whether Send As Other User privilege is enabled. */ RequireApprovalForQueueEmail: DevKit.WebApi.BooleanValue; /** Indicates whether Send As Other User privilege is enabled. */ RequireApprovalForUserEmail: DevKit.WebApi.BooleanValue; /** Apply same email address to all unresolved matches when you manually resolve it for one */ ResolveSimilarUnresolvedEmailAddress: DevKit.WebApi.BooleanValue; /** Flag to restrict Update on incident. */ RestrictStatusUpdate: DevKit.WebApi.BooleanValue; /** Error status of Relationship Insights provisioning. */ RiErrorStatus: DevKit.WebApi.IntegerValue; /** Unique identifier of the sample data import job. */ SampleDataImportId: DevKit.WebApi.GuidValue; /** Prefix used for custom entities and attributes. */ SchemaNamePrefix: DevKit.WebApi.StringValue; /** Indicates whether Send Bulk Email in UCI is enabled for the org. */ SendBulkEmailInUCI: DevKit.WebApi.BooleanValue; /** Serve Static Content From CDN */ ServeStaticResourcesFromAzureCDN: DevKit.WebApi.BooleanValue; /** Information that specifies whether session timeout is enabled */ SessionTimeoutEnabled: DevKit.WebApi.BooleanValue; /** Session timeout in minutes */ SessionTimeoutInMins: DevKit.WebApi.IntegerValue; /** Session timeout reminder in minutes */ SessionTimeoutReminderInMins: DevKit.WebApi.IntegerValue; /** Indicates which SharePoint deployment type is configured for Server to Server. (Online or On-Premises) */ SharePointDeploymentType: DevKit.WebApi.OptionSetValue; /** Information that specifies whether to share to previous owner on assign. */ ShareToPreviousOwnerOnAssign: DevKit.WebApi.BooleanValue; /** Select whether to display a KB article deprecation notification to the user. */ ShowKBArticleDeprecationNotification: DevKit.WebApi.BooleanValue; /** Information that specifies whether to display the week number in calendar displays throughout Microsoft CRM. */ ShowWeekNumber: DevKit.WebApi.BooleanValue; /** CRM for Outlook Download URL */ SignupOutlookDownloadFWLink: DevKit.WebApi.StringValue; /** Contains the on hold case status values. */ SlaPauseStates: DevKit.WebApi.StringValue; /** Flag for whether the organization is using Social Insights. */ SocialInsightsEnabled: DevKit.WebApi.BooleanValue; /** Identifier for the Social Insights instance for the organization. */ SocialInsightsInstance: DevKit.WebApi.StringValue; /** Flag for whether the organization has accepted the Social Insights terms of use. */ SocialInsightsTermsAccepted: DevKit.WebApi.BooleanValue; /** For internal use only. */ SortId: DevKit.WebApi.IntegerValue; /** For internal use only. */ SqlAccessGroupId: DevKit.WebApi.GuidValue; /** For internal use only. */ SqlAccessGroupName: DevKit.WebApi.StringValue; /** Setting for SQM data collection, 0 no, 1 yes enabled */ SQMEnabled: DevKit.WebApi.BooleanValue; /** Unique identifier of the support user for the organization. */ SupportUserId: DevKit.WebApi.GuidValue; /** Indicates whether SLA is suppressed. */ SuppressSLA: DevKit.WebApi.BooleanValue; /** Number of records to update per operation in Sync Bulk Pause/Resume/Cancel */ SyncBulkOperationBatchSize: DevKit.WebApi.IntegerValue; /** Max total number of records to update in database for Sync Bulk Pause/Resume/Cancel */ SyncBulkOperationMaxLimit: DevKit.WebApi.IntegerValue; /** Indicates the selection to use the dynamics 365 azure sync framework or server side sync. */ SyncOptInSelection: DevKit.WebApi.BooleanValue; /** Indicates the status of the opt-in or opt-out operation for dynamics 365 azure sync. */ SyncOptInSelectionStatus: DevKit.WebApi.OptionSetValue; /** Unique identifier of the system user for the organization. */ SystemUserId: DevKit.WebApi.GuidValue; /** Maximum number of aggressive polling cycles executed for email auto-tagging when a new email is received. */ TagMaxAggressiveCycles: DevKit.WebApi.IntegerValue; /** Normal polling frequency used for email receive auto-tagging in outlook. */ TagPollingPeriod: DevKit.WebApi.IntegerValue; /** Select whether to turn on task flows for the organization. */ TaskBasedFlowEnabled: DevKit.WebApi.BooleanValue; /** Instrumentation key for Application Insights used to log plugins telemetry. */ TelemetryInstrumentationKey: DevKit.WebApi.StringValue; /** Select whether to turn on text analytics for the organization. */ TextAnalyticsEnabled: DevKit.WebApi.BooleanValue; /** Information that specifies how the time is displayed throughout Microsoft CRM. */ TimeFormatCode: DevKit.WebApi.OptionSetValue; /** Text for how time is displayed in Microsoft Dynamics 365. */ TimeFormatString: DevKit.WebApi.StringValue; /** Text for how the time separator is displayed throughout Microsoft Dynamics 365. */ TimeSeparator: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Duration used for token expiration. */ TokenExpiry: DevKit.WebApi.IntegerValue; /** Token key. */ TokenKey: DevKit.WebApi.StringValue; /** Tracelog record maximum age in days */ TraceLogMaximumAgeInDays: DevKit.WebApi.IntegerValue; /** History list of tracking token prefixes. */ TrackingPrefix: DevKit.WebApi.StringValue; /** Base number used to provide separate tracking token identifiers to users belonging to different deployments. */ TrackingTokenIdBase: DevKit.WebApi.IntegerValue; /** Number of digits used to represent a tracking token identifier. */ TrackingTokenIdDigits: DevKit.WebApi.IntegerValue; /** Number of characters appended to invoice, quote, and order numbers. */ UniqueSpecifierLength: DevKit.WebApi.IntegerValue; /** Indicates whether email address should be unresolved if multiple matches are found */ UnresolveEmailAddressIfMultipleMatch: DevKit.WebApi.BooleanValue; /** Flag indicates whether to Use Inbuilt Rule For DefaultPricelist. */ UseInbuiltRuleForDefaultPricelistSelection: DevKit.WebApi.BooleanValue; /** Select whether to use legacy form rendering. */ UseLegacyRendering: DevKit.WebApi.BooleanValue; /** Use position hierarchy */ UsePositionHierarchy: DevKit.WebApi.BooleanValue; /** Indicates whether searching in a grid should use the Quick Find view for the entity. */ UseQuickFindViewForGridSearch: DevKit.WebApi.BooleanValue; /** The interval at which user access is checked for auditing. */ UserAccessAuditingInterval: DevKit.WebApi.IntegerValue; /** Indicates whether the read-optimized form should be enabled for this organization. */ UseReadForm: DevKit.WebApi.BooleanValue; /** Unique identifier of the default group of users in the organization. */ UserGroupId: DevKit.WebApi.GuidValue; /** Indicates default protocol selected for organization. */ UseSkypeProtocol: DevKit.WebApi.BooleanValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Hash of the V3 callout configuration file. */ V3CalloutConfigHash: DevKit.WebApi.StringValueReadonly; /** Version number of the organization. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Hash value of web resources. */ WebResourceHash: DevKit.WebApi.StringValue; /** Designated first day of the week throughout Microsoft Dynamics 365. */ WeekStartDayCode: DevKit.WebApi.OptionSetValue; /** For Internal use only. */ WidgetProperties: DevKit.WebApi.StringValue; /** Denotes the Yammer group ID */ YammerGroupId: DevKit.WebApi.IntegerValue; /** Denotes the Yammer network permalink */ YammerNetworkPermalink: DevKit.WebApi.StringValue; /** Denotes whether the OAuth access token for Yammer network has expired */ YammerOAuthAccessTokenExpired: DevKit.WebApi.BooleanValue; /** Internal Use Only */ YammerPostMethod: DevKit.WebApi.OptionSetValue; /** Information that specifies how the first week of the year is specified in Microsoft Dynamics 365. */ YearStartWeekCode: DevKit.WebApi.IntegerValue; } } declare namespace OptionSet { namespace Organization { enum CurrencyDisplayOption { /** 1 */ Currency_code, /** 0 */ Currency_symbol } enum CurrencyFormatCode { /** 3 */ _123_, /** 0 */ _123_0, /** 1 */ _123_1, /** 2 */ _123_2 } enum DateFormatCode { } enum DefaultRecurrenceEndRangeType { /** 3 */ End_By_Date, /** 1 */ No_End_Date, /** 2 */ Number_of_Occurrences } enum DiscountCalculationMethod { /** 0 */ Line_item, /** 1 */ Per_unit } enum EmailConnectionChannel { /** 1 */ Microsoft_Dynamics_365_Email_Router, /** 0 */ Server_Side_Synchronization } enum FiscalPeriodFormatPeriod { /** 5 */ M0, /** 4 */ Month_0, /** 7 */ Month_Name, /** 3 */ P0, /** 2 */ Q0, /** 1 */ Quarter_0, /** 6 */ Semester_0 } enum FiscalYearFormatPrefix { /** 2 */ _, /** 1 */ FY } enum FiscalYearFormatSuffix { /** 3 */ _, /** 2 */ _Fiscal_Year, /** 1 */ FY } enum FiscalYearFormatYear { /** 3 */ GGYY, /** 2 */ YY, /** 1 */ YYYY } enum FullNameConventionCode { /** 1 */ First_Name, /** 3 */ First_Name_Middle_Initial_Last_Name, /** 5 */ First_Name_Middle_Name_Last_Name, /** 0 */ Last_Name_First_Name, /** 2 */ Last_Name_First_Name_Middle_Initial, /** 4 */ Last_Name_First_Name_Middle_Name, /** 7 */ Last_Name_no_space_First_Name, /** 6 */ Last_Name_space_First_Name } enum ISVIntegrationCode { /** 7 */ All, /** 0 */ None, /** 6 */ Outlook, /** 4 */ Outlook_Laptop_Client, /** 2 */ Outlook_Workstation_Client, /** 1 */ Web, /** 5 */ Web_Outlook_Laptop_Client, /** 3 */ Web_Outlook_Workstation_Client } enum NegativeFormatCode { /** 0 */ Brackets, /** 1 */ Dash, /** 2 */ Dash_plus_Space, /** 4 */ Space_plus_Trailing_Dash, /** 3 */ Trailing_Dash } enum OrganizationState { /** 3 */ Active, /** 0 */ Creating, /** 2 */ Updating, /** 1 */ Upgrading } enum PluginTraceLogSetting { /** 2 */ All, /** 1 */ Exception, /** 0 */ Off } enum ReportScriptErrors { /** 1 */ Ask_me_for_permission_to_send_an_error_report_to_Microsoft, /** 2 */ Automatically_send_an_error_report_to_Microsoft_without_asking_me_for_permission, /** 3 */ Never_send_an_error_report_to_Microsoft_about_Microsoft_Dynamics_365, /** 0 */ No_preference_for_sending_an_error_report_to_Microsoft_about_Microsoft_Dynamics_365 } enum SharePointDeploymentType { /** 1 */ On_Premises, /** 0 */ Online } enum SyncOptInSelectionStatus { /** 3 */ Failed, /** 2 */ Passed, /** 1 */ Processing } enum TimeFormatCode { } enum WeekStartDayCode { } enum YammerPostMethod { /** 1 */ Private, /** 0 */ Public } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { RawHttpHeaders } from "@azure/core-rest-pipeline"; import { HttpResponse } from "@azure-rest/core-client"; import { ProductOutput, CloudErrorOutput, SkuOutput, SubProductOutput } from "./outputModels"; /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. */ export interface LROsPut200Succeeded200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. */ export interface LROsPut200Succeeded204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. */ export interface LROsPut200SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPatch200SucceededIgnoreHeaders200Headers { /** This header should be ignored in this case */ "azure-asyncoperation"?: string; } /** Long running put request, service returns a 200 to the initial request with location header. We should not have any subsequent calls after receiving this first response. */ export interface LROsPatch200SucceededIgnoreHeaders200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsPatch200SucceededIgnoreHeaders200Headers; } /** Long running put request, service returns a 200 to the initial request with location header. We should not have any subsequent calls after receiving this first response. */ export interface LROsPatch200SucceededIgnoreHeadersdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. */ export interface LROsPut201Succeeded201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Succeeded’. */ export interface LROsPut201SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 202 with empty body to first request, returns a 200 with body [{ 'id': '100', 'name': 'foo' }]. */ export interface LROsPost202List200Response extends HttpResponse { status: "200"; body: Array<ProductOutput>; } export interface LROsPost202List202Headers { /** Location to poll for result status: will be set to /lro/list/pollingGet */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/list/finalGet */ location?: string; } /** Long running put request, service returns a 202 with empty body to first request, returns a 200 with body [{ 'id': '100', 'name': 'foo' }]. */ export interface LROsPost202List202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPost202List202Headers; } /** Long running put request, service returns a 202 with empty body to first request, returns a 200 with body [{ 'id': '100', 'name': 'foo' }]. */ export interface LROsPost202ListdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 200 to the initial request, with an entity that does not contain ProvisioningState=’Succeeded’. */ export interface LROsPut200SucceededNoState200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 200 to the initial request, with an entity that does not contain ProvisioningState=’Succeeded’. */ export interface LROsPut200SucceededNoStatedefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 202 to the initial request, with a location header that points to a polling URL that returns a 200 and an entity that doesn't contains ProvisioningState */ export interface LROsPut202Retry200202Response extends HttpResponse { status: "202"; body: ProductOutput; } /** Long running put request, service returns a 202 to the initial request, with a location header that points to a polling URL that returns a 200 and an entity that doesn't contains ProvisioningState */ export interface LROsPut202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsPut201CreatingSucceeded200200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsPut201CreatingSucceeded200201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsPut201CreatingSucceeded200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsPut200UpdatingSucceeded204200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsPut200UpdatingSucceeded204defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsPut201CreatingFailed200200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsPut201CreatingFailed200201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Created’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsPut201CreatingFailed200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’ */ export interface LROsPut200Acceptedcanceled200200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’ */ export interface LROsPut200Acceptedcanceled200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutNoHeaderInRetry202Headers { /** Location to poll for result status: will be set to /lro/putasync/noheader/202/200/operationResults */ location?: string; } /** Long running put request, service returns a 202 to the initial request with location header. Subsequent calls to operation status do not contain location header. */ export interface LROsPutNoHeaderInRetry202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LROsPutNoHeaderInRetry202Headers; } /** Long running put request, service returns a 202 to the initial request with location header. Subsequent calls to operation status do not contain location header. */ export interface LROsPutNoHeaderInRetrydefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutAsyncRetrySucceeded200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsPutAsyncRetrySucceeded200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutAsyncNoRetrySucceeded200Headers { /** Location to poll for result status: will be set to /lro/putasync/noretry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/noretry/succeeded/operationResults/200 */ location?: string; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncNoRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsPutAsyncNoRetrySucceeded200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncNoRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutAsyncRetryFailed200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncRetryFailed200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsPutAsyncRetryFailed200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncRetryFaileddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutAsyncNoRetrycanceled200Headers { /** Location to poll for result status: will be set to /lro/putasync/noretry/canceled/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/noretry/canceled/operationResults/200 */ location?: string; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncNoRetrycanceled200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsPutAsyncNoRetrycanceled200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPutAsyncNoRetrycanceleddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPutAsyncNoHeaderInRetry201Headers { "azure-asyncoperation"?: string; } /** Long running put request, service returns a 202 to the initial request with Azure-AsyncOperation header. Subsequent calls to operation status do not contain Azure-AsyncOperation header. */ export interface LROsPutAsyncNoHeaderInRetry201Response extends HttpResponse { status: "201"; body: ProductOutput; headers: RawHttpHeaders & LROsPutAsyncNoHeaderInRetry201Headers; } /** Long running put request, service returns a 202 to the initial request with Azure-AsyncOperation header. Subsequent calls to operation status do not contain Azure-AsyncOperation header. */ export interface LROsPutAsyncNoHeaderInRetrydefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request with non resource. */ export interface LROsPutNonResource202Response extends HttpResponse { status: "202"; body: SkuOutput; } /** Long running put request with non resource. */ export interface LROsPutNonResourcedefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request with non resource. */ export interface LROsPutAsyncNonResource202Response extends HttpResponse { status: "202"; body: SkuOutput; } /** Long running put request with non resource. */ export interface LROsPutAsyncNonResourcedefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request with sub resource. */ export interface LROsPutSubResource202Response extends HttpResponse { status: "202"; body: SubProductOutput; } /** Long running put request with sub resource. */ export interface LROsPutSubResourcedefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request with sub resource. */ export interface LROsPutAsyncSubResource202Response extends HttpResponse { status: "202"; body: SubProductOutput; } /** Long running put request with sub resource. */ export interface LROsPutAsyncSubResourcedefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDeleteProvisioning202Accepted200Succeeded200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsDeleteProvisioning202Accepted200Succeeded202Headers { /** Location to poll for result status: will be set to /lro/delete/provisioning/202/accepted/200/succeeded */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDeleteProvisioning202Accepted200Succeeded202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LROsDeleteProvisioning202Accepted200Succeeded202Headers; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDeleteProvisioning202Accepted200SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsDeleteProvisioning202DeletingFailed200200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsDeleteProvisioning202DeletingFailed200202Headers { /** Location to poll for result status: will be set to /lro/delete/provisioning/202/deleting/200/failed */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsDeleteProvisioning202DeletingFailed200202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LROsDeleteProvisioning202DeletingFailed200202Headers; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Failed’ */ export interface LROsDeleteProvisioning202DeletingFailed200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’ */ export interface LROsDeleteProvisioning202Deletingcanceled200200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsDeleteProvisioning202Deletingcanceled200202Headers { /** Location to poll for result status: will be set to /lro/delete/provisioning/202/deleting/200/canceled */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’ */ export interface LROsDeleteProvisioning202Deletingcanceled200202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LROsDeleteProvisioning202Deletingcanceled200202Headers; } /** Long running delete request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Canceled’ */ export interface LROsDeleteProvisioning202Deletingcanceled200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete succeeds and returns right away */ export interface LROsDelete204Succeeded204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running delete succeeds and returns right away */ export interface LROsDelete204SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202Retry200200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsDelete202Retry200202Headers { /** Location to poll for result status: will be set to /lro/delete/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202Retry200202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDelete202Retry200202Headers; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202NoRetry204200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsDelete202NoRetry204202Headers { /** Location to poll for result status: will be set to /lro/delete/202/noretry/204 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202NoRetry204202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDelete202NoRetry204202Headers; } /** Long running delete request, service returns a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsDelete202NoRetry204defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteNoHeaderInRetry202Headers { /** Location to poll for result status: will be set to /lro/put/noheader/202/204/operationresults */ location?: string; } /** Long running delete request, service returns a location header in the initial request. Subsequent calls to operation status do not contain location header. */ export interface LROsDeleteNoHeaderInRetry202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteNoHeaderInRetry202Headers; } /** Long running delete request, service returns a location header in the initial request. Subsequent calls to operation status do not contain location header. */ export interface LROsDeleteNoHeaderInRetry204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running delete request, service returns a location header in the initial request. Subsequent calls to operation status do not contain location header. */ export interface LROsDeleteNoHeaderInRetrydefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteAsyncNoHeaderInRetry202Headers { /** Location to poll for result status: will be set to /lro/put/noheader/202/204/operationresults */ location?: string; } /** Long running delete request, service returns an Azure-AsyncOperation header in the initial request. Subsequent calls to operation status do not contain Azure-AsyncOperation header. */ export interface LROsDeleteAsyncNoHeaderInRetry202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteAsyncNoHeaderInRetry202Headers; } /** Long running delete request, service returns an Azure-AsyncOperation header in the initial request. Subsequent calls to operation status do not contain Azure-AsyncOperation header. */ export interface LROsDeleteAsyncNoHeaderInRetry204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running delete request, service returns an Azure-AsyncOperation header in the initial request. Subsequent calls to operation status do not contain Azure-AsyncOperation header. */ export interface LROsDeleteAsyncNoHeaderInRetrydefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteAsyncRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/deleteasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/deleteasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteAsyncRetrySucceeded202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteAsyncNoRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/deleteasync/noretry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/deleteasync/noretry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncNoRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteAsyncNoRetrySucceeded202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncNoRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteAsyncRetryFailed202Headers { /** Location to poll for result status: will be set to /lro/deleteasync/retry/failed/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/deleteasync/retry/failed/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetryFailed202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteAsyncRetryFailed202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetryFaileddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsDeleteAsyncRetrycanceled202Headers { /** Location to poll for result status: will be set to /lro/deleteasync/retry/canceled/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/deleteasync/retry/canceled/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetrycanceled202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsDeleteAsyncRetrycanceled202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsDeleteAsyncRetrycanceleddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request, with 'Location' header. Poll returns a 200 with a response body after success. */ export interface LROsPost200WithPayload200Response extends HttpResponse { status: "200"; body: SkuOutput; } /** Long running post request, service returns a 202 to the initial request, with 'Location' header. Poll returns a 200 with a response body after success. */ export interface LROsPost200WithPayload202Response extends HttpResponse { status: "202"; body: SkuOutput; } /** Long running post request, service returns a 202 to the initial request, with 'Location' header. Poll returns a 200 with a response body after success. */ export interface LROsPost200WithPayloaddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPost202Retry200202Headers { /** Location to poll for result status: will be set to /lro/post/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LROsPost202Retry200202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPost202Retry200202Headers; } /** Long running post request, service returns a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LROsPost202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPost202NoRetry204202Headers { /** Location to poll for result status: will be set to /lro/post/202/noretry/204 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with 'Location' header, 204 with noresponse body after success */ export interface LROsPost202NoRetry204202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LROsPost202NoRetry204202Headers; } /** Long running post request, service returns a 202 to the initial request, with 'Location' header, 204 with noresponse body after success */ export interface LROsPost202NoRetry204defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should poll Location to get the final object */ export interface LROsPostDoubleHeadersFinalLocationGet202Response extends HttpResponse { status: "202"; body: ProductOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should poll Location to get the final object */ export interface LROsPostDoubleHeadersFinalLocationGetdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the final object */ export interface LROsPostDoubleHeadersFinalAzureHeaderGet202Response extends HttpResponse { status: "202"; body: ProductOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the final object */ export interface LROsPostDoubleHeadersFinalAzureHeaderGetdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the final object if you support initial Autorest behavior. */ export interface LROsPostDoubleHeadersFinalAzureHeaderGetDefault202Response extends HttpResponse { status: "202"; body: ProductOutput; } /** Long running post request, service returns a 202 to the initial request with both Location and Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the final object if you support initial Autorest behavior. */ export interface LROsPostDoubleHeadersFinalAzureHeaderGetDefaultdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsPostAsyncRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPostAsyncRetrySucceeded202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncNoRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LROsPostAsyncNoRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncNoRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPostAsyncNoRetrySucceeded202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncNoRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPostAsyncRetryFailed202Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetryFailed202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPostAsyncRetryFailed202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetryFaileddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsPostAsyncRetrycanceled202Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/canceled/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/canceled/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetrycanceled202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsPostAsyncRetrycanceled202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsPostAsyncRetrycanceleddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 500, then a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysPut201CreatingSucceeded200200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 500, then a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysPut201CreatingSucceeded200201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 500, then a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysPut201CreatingSucceeded200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LRORetrysPutAsyncRelativeRetrySucceeded200Headers { /** Location to poll for result status: will be set to /lro/retryerror/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/retryerror/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 500, then a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysPutAsyncRelativeRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LRORetrysPutAsyncRelativeRetrySucceeded200Headers; } /** Long running put request, service returns a 500, then a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysPutAsyncRelativeRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysDeleteProvisioning202Accepted200Succeeded200Response extends HttpResponse { status: "200"; body: ProductOutput; } export interface LRORetrysDeleteProvisioning202Accepted200Succeeded202Headers { /** Location to poll for result status: will be set to /lro/retryerror/delete/provisioning/202/accepted/200/succeeded */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysDeleteProvisioning202Accepted200Succeeded202Response extends HttpResponse { status: "202"; body: ProductOutput; headers: RawHttpHeaders & LRORetrysDeleteProvisioning202Accepted200Succeeded202Headers; } /** Long running delete request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysDeleteProvisioning202Accepted200SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LRORetrysDelete202Retry200202Headers { /** Location to poll for result status: will be set to /lro/retryerror/delete/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 500, then a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysDelete202Retry200202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LRORetrysDelete202Retry200202Headers; } /** Long running delete request, service returns a 500, then a 202 to the initial request. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LRORetrysDelete202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LRORetrysDeleteAsyncRelativeRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/retryerror/deleteasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/retryerror/deleteasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 500, then a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysDeleteAsyncRelativeRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LRORetrysDeleteAsyncRelativeRetrySucceeded202Headers; } /** Long running delete request, service returns a 500, then a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysDeleteAsyncRelativeRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LRORetrysPost202Retry200202Headers { /** Location to poll for result status: will be set to /lro/retryerror/post/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 500, then a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LRORetrysPost202Retry200202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LRORetrysPost202Retry200202Headers; } /** Long running post request, service returns a 500, then a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LRORetrysPost202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LRORetrysPostAsyncRelativeRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/retryerror/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/retryerror/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysPostAsyncRelativeRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LRORetrysPostAsyncRelativeRetrySucceeded202Headers; } /** Long running post request, service returns a 500, then a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LRORetrysPostAsyncRelativeRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 400 to the initial request */ export interface LrosaDsPutNonRetry400200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 400 to the initial request */ export interface LrosaDsPutNonRetry400201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 400 to the initial request */ export interface LrosaDsPutNonRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400InvalidJson200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400InvalidJson201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code */ export interface LrosaDsPutNonRetry201Creating400InvalidJsondefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPutAsyncRelativeRetry400200Headers { /** Location to poll for result status: will be set to /lro/nonretryerror/putasync/retry/operationResults/400 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/nonretryerror/putasync/retry/operationResults/400 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetry400200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LrosaDsPutAsyncRelativeRetry400200Headers; } /** Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDeleteNonRetry400202Headers { /** Location to poll for result status: will be set to /lro/retryerror/delete/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 400 with an error body */ export interface LrosaDsDeleteNonRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDeleteNonRetry400202Headers; } /** Long running delete request, service returns a 400 with an error body */ export interface LrosaDsDeleteNonRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDelete202NonRetry400202Headers { /** Location to poll for result status: will be set to /lro/retryerror/delete/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 with a location header */ export interface LrosaDsDelete202NonRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDelete202NonRetry400202Headers; } /** Long running delete request, service returns a 202 with a location header */ export interface LrosaDsDelete202NonRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDeleteAsyncRelativeRetry400202Headers { /** Location to poll for result status: will be set to /lro/nonretryerror/deleteasync/retry/operationResults/400 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/nonretryerror/deleteasync/retry/operationResults/400 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDeleteAsyncRelativeRetry400202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPostNonRetry400202Headers { /** Location to poll for result status: will be set to /lro/retryerror/post/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 400 with no error body */ export interface LrosaDsPostNonRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPostNonRetry400202Headers; } /** Long running post request, service returns a 400 with no error body */ export interface LrosaDsPostNonRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPost202NonRetry400202Headers { /** Location to poll for result status: will be set to /lro/retryerror/post/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 with a location header */ export interface LrosaDsPost202NonRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPost202NonRetry400202Headers; } /** Long running post request, service returns a 202 with a location header */ export interface LrosaDsPost202NonRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPostAsyncRelativeRetry400202Headers { /** Location to poll for result status: will be set to /lro/nonretryerror/putasync/retry/operationResults/400 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/nonretryerror/putasync/retry/operationResults/400 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetry400202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPostAsyncRelativeRetry400202Headers; } /** Long running post request, service returns a 202 to the initial request Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetry400defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 201 to the initial request with no payload */ export interface LrosaDsPutError201NoProvisioningStatePayload200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request with no payload */ export interface LrosaDsPutError201NoProvisioningStatePayload201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** Long running put request, service returns a 201 to the initial request with no payload */ export interface LrosaDsPutError201NoProvisioningStatePayloaddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPutAsyncRelativeRetryNoStatus200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryNoStatus200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LrosaDsPutAsyncRelativeRetryNoStatus200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryNoStatusdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPutAsyncRelativeRetryNoStatusPayload200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryNoStatusPayload200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LrosaDsPutAsyncRelativeRetryNoStatusPayload200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryNoStatusPayloaddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running delete request, service returns a 204 to the initial request, indicating success. */ export interface LrosaDsDelete204Succeeded204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running delete request, service returns a 204 to the initial request, indicating success. */ export interface LrosaDsDelete204SucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDeleteAsyncRelativeRetryNoStatus202Headers { /** Location to poll for result status: will be set to /lro/deleteasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/deleteasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetryNoStatus202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDeleteAsyncRelativeRetryNoStatus202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetryNoStatusdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPost202NoLocation202Headers { /** Location to poll for result status: will not be set */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, without a location header. */ export interface LrosaDsPost202NoLocation202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPost202NoLocation202Headers; } /** Long running post request, service returns a 202 to the initial request, without a location header. */ export interface LrosaDsPost202NoLocationdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPostAsyncRelativeRetryNoPayload202Headers { /** Location to poll for result status: will be set to /lro/error/putasync/retry/failed/operationResults/nopayload */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/error/putasync/retry/failed/operationResults/nopayload */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetryNoPayload202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPostAsyncRelativeRetryNoPayload202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetryNoPayloaddefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** Long running put request, service returns a 200 to the initial request, with an entity that is not a valid json */ export interface LrosaDsPut200InvalidJson200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** Long running put request, service returns a 200 to the initial request, with an entity that is not a valid json */ export interface LrosaDsPut200InvalidJson204Response extends HttpResponse { status: "204"; body: Record<string, unknown>; } /** Long running put request, service returns a 200 to the initial request, with an entity that is not a valid json */ export interface LrosaDsPut200InvalidJsondefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPutAsyncRelativeRetryInvalidHeader200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. */ export interface LrosaDsPutAsyncRelativeRetryInvalidHeader200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LrosaDsPutAsyncRelativeRetryInvalidHeader200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. */ export interface LrosaDsPutAsyncRelativeRetryInvalidHeaderdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPutAsyncRelativeRetryInvalidJsonPolling200Headers { /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryInvalidJsonPolling200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LrosaDsPutAsyncRelativeRetryInvalidJsonPolling200Headers; } /** Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPutAsyncRelativeRetryInvalidJsonPollingdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDelete202RetryInvalidHeader202Headers { /** Location to poll for result status: will be set to /foo */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to /bar */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request receing a reponse with an invalid 'Location' and 'Retry-After' headers */ export interface LrosaDsDelete202RetryInvalidHeader202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDelete202RetryInvalidHeader202Headers; } /** Long running delete request, service returns a 202 to the initial request receing a reponse with an invalid 'Location' and 'Retry-After' headers */ export interface LrosaDsDelete202RetryInvalidHeaderdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDeleteAsyncRelativeRetryInvalidHeader202Headers { /** Location to poll for result status: will be set to /foo */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /foo */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to /bar */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. The endpoint indicated in the Azure-AsyncOperation header is invalid */ export interface LrosaDsDeleteAsyncRelativeRetryInvalidHeader202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDeleteAsyncRelativeRetryInvalidHeader202Headers; } /** Long running delete request, service returns a 202 to the initial request. The endpoint indicated in the Azure-AsyncOperation header is invalid */ export interface LrosaDsDeleteAsyncRelativeRetryInvalidHeaderdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsDeleteAsyncRelativeRetryInvalidJsonPolling202Headers { /** Location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetryInvalidJsonPolling202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsDeleteAsyncRelativeRetryInvalidJsonPolling202Headers; } /** Long running delete request, service returns a 202 to the initial request. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsDeleteAsyncRelativeRetryInvalidJsonPollingdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPost202RetryInvalidHeader202Headers { /** Location to poll for result status: will be set to /foo */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to /bar */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with invalid 'Location' and 'Retry-After' headers. */ export interface LrosaDsPost202RetryInvalidHeader202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPost202RetryInvalidHeader202Headers; } /** Long running post request, service returns a 202 to the initial request, with invalid 'Location' and 'Retry-After' headers. */ export interface LrosaDsPost202RetryInvalidHeaderdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPostAsyncRelativeRetryInvalidHeader202Headers { /** Location to poll for result status: will be set to foo */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to foo */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to /bar */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. */ export interface LrosaDsPostAsyncRelativeRetryInvalidHeader202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPostAsyncRelativeRetryInvalidHeader202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation header is invalid. */ export interface LrosaDsPostAsyncRelativeRetryInvalidHeaderdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LrosaDsPostAsyncRelativeRetryInvalidJsonPolling202Headers { /** Location to poll for result status: will be set to /lro/error/postasync/retry/failed/operationResults/invalidjsonpolling */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/error/postasync/retry/failed/operationResults/invalidjsonpolling */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetryInvalidJsonPolling202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LrosaDsPostAsyncRelativeRetryInvalidJsonPolling202Headers; } /** Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LrosaDsPostAsyncRelativeRetryInvalidJsonPollingdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsCustomHeaderPutAsyncRetrySucceeded200Headers { /** Location to poll for result status: will be set to /lro/customheader/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/customheader/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsCustomHeaderPutAsyncRetrySucceeded200Response extends HttpResponse { status: "200"; body: ProductOutput; headers: RawHttpHeaders & LROsCustomHeaderPutAsyncRetrySucceeded200Headers; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running put request, service returns a 200 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsCustomHeaderPutAsyncRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsCustomHeaderPut201CreatingSucceeded200200Response extends HttpResponse { status: "200"; body: ProductOutput; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsCustomHeaderPut201CreatingSucceeded200201Response extends HttpResponse { status: "201"; body: ProductOutput; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running put request, service returns a 201 to the initial request, with an entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’ */ export interface LROsCustomHeaderPut201CreatingSucceeded200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsCustomHeaderPost202Retry200202Headers { /** Location to poll for result status: will be set to /lro/customheader/post/202/retry/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running post request, service returns a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LROsCustomHeaderPost202Retry200202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsCustomHeaderPost202Retry200202Headers; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running post request, service returns a 202 to the initial request, with 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success */ export interface LROsCustomHeaderPost202Retry200defaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; } export interface LROsCustomHeaderPostAsyncRetrySucceeded202Headers { /** Location to poll for result status: will be set to /lro/customheader/putasync/retry/succeeded/operationResults/200 */ "azure-asyncoperation"?: string; /** Location to poll for result status: will be set to /lro/customheader/putasync/retry/succeeded/operationResults/200 */ location?: string; /** Number of milliseconds until the next poll should be sent, will be set to zero */ "retry-after"?: number; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsCustomHeaderPostAsyncRetrySucceeded202Response extends HttpResponse { status: "202"; body: Record<string, unknown>; headers: RawHttpHeaders & LROsCustomHeaderPostAsyncRetrySucceeded202Headers; } /** x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for all requests. Long running post request, service returns a 202 to the initial request, with an entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation header for operation status */ export interface LROsCustomHeaderPostAsyncRetrySucceededdefaultResponse extends HttpResponse { status: "500"; body: CloudErrorOutput; }
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import { angularCollectionName } from '../defaults'; import { FileSystem, Output, Terminals } from '../utils'; import { WorkspaceFolderConfig } from '../workspace'; import { Schematic } from '../workspace/schematics'; import { CliCommandOptions, formatCliCommandOptions } from './cli-options'; interface ContextPath { /** Eg. `src/app/some-module` */ relativeToWorkspaceFolder: string; /** Eg. `some-module` */ relativeToProjectFolder: string; } export class CliCommand { /* Path details of the right-clicked file or directory */ private contextPath: ContextPath = { relativeToWorkspaceFolder: '', relativeToProjectFolder: '', }; private baseCommand = 'ng g'; private projectName = ''; private collectionName = angularCollectionName; private schematicName = ''; private schematic!: Schematic; private nameAsFirstArg = ''; private options: CliCommandOptions = new Map<string, string | string[]>(); constructor( private workspaceFolder: WorkspaceFolderConfig, contextUri?: vscode.Uri, ) { this.setContextPathAndProject(contextUri); } /** * Get the full generation command, in the shortest form possible. */ getCommand(): string { return [ this.baseCommand, this.formatSchematicNameForCommand(), this.nameAsFirstArg, formatCliCommandOptions(this.options), ].join(' ').trim(); } /** * Set collection's name */ setCollectionName(name: string): void { this.collectionName = name; } /** * Set schematic, and project if relevant. */ setSchematic(schematic: Schematic): void { this.schematicName = schematic.getName(); this.schematic = schematic; } /** * Get project (can be an empty string, in which case the command will be for the root project) */ getProjectName(): string { return this.projectName; } /** * Get project's source Uri, or defaut to `src/app` */ getProjectSourceUri(): vscode.Uri { return vscode.Uri.joinPath(this.workspaceFolder.uri, this.getRelativeProjectSourcePath()); } /** * Set the project's name */ setProjectName(name: string): void { this.projectName = name; } /** * Add the project in command if available and relevant, or try to find "app.module.ts" path */ async validateProject(): Promise<boolean> { // TODO: `@ngxs/schematics` has an issue, it's guessing just `src` path instead of `src/app` /* If a project was detected or chosen by the user */ if (this.projectName) { /* We only need to add it to options if the schematic supports it and it's not the root project */ if (this.schematic.hasOption('project') && !this.workspaceFolder.isRootAngularProject(this.projectName)) { this.options.set('project', this.projectName); } } /* Otherwise try to find the path of "app.module.ts" */ else { const pattern = new vscode.RelativePattern(this.workspaceFolder, '**/app.module.ts'); const appModulePossibleUris = await vscode.workspace.findFiles(pattern, '**/node_modules/**', 1); if (appModulePossibleUris.length > 0) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const pathRelativeToWorkspace = FileSystem.relative(this.workspaceFolder.uri, appModulePossibleUris[0]!); const commandPath = path.posix.dirname(pathRelativeToWorkspace); this.options.set('path', commandPath); Output.logInfo(`"app.module.ts" detected in: ${commandPath}`); } else { Output.logWarning(`No Angular project or "app.module.ts" detected.`); return false; } } return true; } /** * Get context path with a trailing slash to prefill first argument option. * With a trailing slash so the user can just write the name directly. */ getContextForNameAsFirstArg(): string { /* Some schematics do not need a path */ if ((this.collectionName === angularCollectionName) && ['application', 'library'].includes(this.schematicName)) { return ''; } /* `ngx-spec` schematics works on a file, and thus need the file part */ else if ((this.collectionName === 'ngx-spec') && (this.schematicName === 'spec')) { return this.contextPath.relativeToProjectFolder; } else if (this.collectionName === 'ngx-spec') { return ''; } /* Otherwise we remove the file part */ const context = FileSystem.removeFilename(this.contextPath.relativeToProjectFolder); /* Add trailing slash so the user can just write the name directly */ const contextWithTrailingSlash = !(['', '.'].includes(context)) ? `${context}/` : ''; return contextWithTrailingSlash; } /** * Get route name from module's path */ getRouteFromFirstArg(): string { return path.posix.basename(this.nameAsFirstArg); } /** * Set name as first argument of the command line, eg. `path/to/some-component` */ setNameAsFirstArg(pathToName: string): void { this.nameAsFirstArg = pathToName; } /** * Add options */ addOptions(options: CliCommandOptions | [string, string | string[]][]): void { for (const [name, option] of options) { /* Check they exist in schematic */ if (this.schematic.hasOption(name)) { this.options.set(name, option); } else { Output.logWarning(`"--${name}" option has been chosen but does not exist in this schematic, so it won't be used.`); } } } /** * Launch command in a terminal */ launchCommand({ dryRun = false } = {}): void { Output.logInfo(`Launching this command: ${this.getCommand()}`); const command = `${this.getCommand()}${dryRun ? ` --dry-run` : ''}`; Terminals.send(this.workspaceFolder, command); } /** * Try to resolve the generated file fs path */ guessGereratedFileUri(): vscode.Uri | undefined { /* Try to resolve the path of the generated file */ let possibleUri: vscode.Uri | undefined = undefined; /* Without a default argument, we cannot know the possible path */ if (this.nameAsFirstArg) { /* Get the project path, or defaut to `src/app` */ const projectSourceUri = this.getProjectSourceUri(); /* Default file's suffix is the schematic name (eg. `service`) */ let suffix = `.${this.schematicName}`; /* Official Angular schematics have some special cases */ if (this.collectionName === angularCollectionName) { /* Component can have a custom suffix via `--type` option */ if (['component', 'class', 'interface'].includes(this.schematicName) && this.options.has('type')) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion suffix = `.${this.options.get('type')! as string}`; } /* Classes and interfaces do not have suffix */ else if (['class', 'interface'].includes(this.schematicName)) { suffix = ''; } /* Web workers have not the same suffix as the schematic's name */ else if (this.schematicName === 'webWorker') { suffix = '.worker'; } } /* All Material schematics have a component suffix */ else if (['@angular/material', '@angular/cdk'].includes(this.collectionName)) { suffix = '.component'; } else if (this.collectionName === '@ngrx/schematics') { if (['action', 'effect', 'selector'].includes(this.schematicName)) { suffix = `.${this.schematicName}s`; } else if (this.schematicName === 'entity') { suffix = '.model'; } else if (this.schematicName === 'container') { suffix = '.component'; } else if (this.schematicName === 'data') { suffix = '.service'; } } /* `posix` here as it was typed by the user in Linux format (ie. with slashes) */ const folderName = path.posix.dirname(this.nameAsFirstArg); const fileName = path.posix.basename(this.nameAsFirstArg); const fileWithSuffixName = `${fileName}${suffix}.ts`; /* Schematics are created with or without an intermediate folder */ let isFlat = true; /* Priority 1: user has explicitly set it during the generation journey */ if (this.options.has('flat')) { /* User values are registered as strings */ isFlat = (this.options.get('flat') === 'false') ? false : true; } else { /* Priority 2: user has set a default in angular.json */ const isUserDefaultFlat = this.workspaceFolder.getSchematicsOptionDefaultValue(this.projectName, this.getFullSchematicName(), 'flat'); if (isUserDefaultFlat !== undefined) { isFlat = isUserDefaultFlat; } else { /* Priority 3: the schematic schema has a default */ const isSchematicDefaultFlat = this.schematic.getOptionDefaultValue('flat') as boolean | undefined; if (isSchematicDefaultFlat !== undefined) { isFlat = isSchematicDefaultFlat; } /* Priority 4: use hard defaults known for some schematics */ else if ((this.collectionName === angularCollectionName) && ['component', 'module'].includes(this.schematicName)) { isFlat = false; } else if (this.collectionName === '@ngxs/schematics') { isFlat = false; } } } /* If not flat, add a intermediate folder, which name is the same as the generated file */ const generatedFolderUri = isFlat ? vscode.Uri.joinPath(projectSourceUri, folderName) : vscode.Uri.joinPath(projectSourceUri, folderName, fileName); possibleUri = vscode.Uri.joinPath(generatedFolderUri, fileWithSuffixName); Output.logInfo(`Guessed generated file path: ${possibleUri.path}`); } return possibleUri; } /** * Get project's relative source path, or defaut to `src/app` */ private getRelativeProjectSourcePath(): string { const project = this.workspaceFolder.getAngularProject(this.projectName); return (this.projectName && project) ? project.getAppOrLibPath() : (this.options.get('path') as string | undefined) ?? 'src/app'; } /** * Get full schematic name (eg. `@schematics/angular:component`) */ private getFullSchematicName(): string { return `${this.collectionName}:${this.schematicName}`; } /** * Format collection and schematic name for the generation command: * - just the schematic name if the collection is already the user default's one (eg. `component`) * - otherwise the full scheme (eg. `@schematics/angular:component`) */ private formatSchematicNameForCommand(): string { return (this.collectionName !== this.workspaceFolder.getDefaultUserCollection()) ? this.getFullSchematicName() : this.schematicName; } /** * Set context path and prject. */ private setContextPathAndProject(contextUri?: vscode.Uri): void { if (!contextUri) { Output.logInfo(`No context path detected.`); return; } Output.logInfo(`Full context fsPath detected: ${contextUri.path}`); if ((this.workspaceFolder.uri.scheme === 'file') && (contextUri.scheme === 'file')) { /* Remove workspace folder path from full path, * eg. `/Users/Elmo/angular-project/src/app/some-module` => `src/app/some-module` * While we need a Posix path, for now we need to start from OS-specific fsPaths because of * https://github.com/microsoft/vscode/issues/116298 */ const relativeToWorkspacePath = path.relative(this.workspaceFolder.uri.fsPath, contextUri.fsPath); /* Convert an OS-specific fsPath to a relative Posix path. */ this.contextPath.relativeToWorkspaceFolder = (path.sep !== path.posix.sep) ? relativeToWorkspacePath.split(path.sep).join(path.posix.sep) : relativeToWorkspacePath; } else { this.contextPath.relativeToWorkspaceFolder = FileSystem.relative(this.workspaceFolder.uri, contextUri); } Output.logInfo(`Workspace folder-relative context path detected: ${this.contextPath.relativeToWorkspaceFolder}`); /* First try by matching projects *source* path */ for (const [projectName, projectConfig] of this.workspaceFolder.getAngularProjects()) { const appOrLibPath = projectConfig.getAppOrLibPath(); /* If the relative path starts with the project path */ if (this.contextPath.relativeToWorkspaceFolder.startsWith(appOrLibPath)) { this.projectName = projectName; /* Remove source path from workspace folder relative path, * eg. `src/app/some-module` => `some-module` */ this.contextPath.relativeToProjectFolder = path.posix.relative(appOrLibPath, this.contextPath.relativeToWorkspaceFolder); break; } } /* Second try by matching projects *source* path */ if (!this.projectName) { for (const [projectName, projectConfig] of this.workspaceFolder.getAngularProjects()) { /* If the relative path starts with the project path */ if (this.contextPath.relativeToWorkspaceFolder.startsWith(projectConfig.getSourcePath())) { this.projectName = projectName; break; } } } /* Third try by matching projects *root* path */ if (!this.projectName) { for (const [projectName, projectConfig] of this.workspaceFolder.getAngularProjects()) { /* If the relative path starts with the project path (but not empty) */ if ((projectConfig.getRootPath() !== '') && this.contextPath.relativeToWorkspaceFolder.startsWith(projectConfig.getRootPath())) { this.projectName = projectName; break; } } } if (this.projectName) { Output.logInfo(`Source-relative context path detected: ${this.contextPath.relativeToProjectFolder}`); Output.logInfo(`Angular project detected from context path: "${this.projectName}"`); } else { Output.logInfo(`No Angular project detected from context path.`); } } }
the_stack
import Quaternion from './Quaternion'; import Vector3 from './Vector3'; /** * Matrix4 */ class Matrix4 { public _el: Float32Array = new Float32Array(16); get el() { return this._el; } constructor() { this.identity(); } public identity() { this._el[0] = 1; this._el[1] = 0; this._el[2] = 0; this._el[3] = 0; this._el[4] = 0; this._el[5] = 1; this._el[6] = 0; this._el[7] = 0; this._el[8] = 0; this._el[9] = 0; this._el[10] = 1; this._el[11] = 0; this._el[12] = 0; this._el[13] = 0; this._el[14] = 0; this._el[15] = 1; return this; } public multiply(mat: Matrix4): Matrix4 { this.multiplyMatrices(this, mat); return this; } public multiplyMatrices(aMat: Matrix4, bMat: Matrix4): Matrix4 { const aEl = aMat.el; const bEl = bMat.el; const a = aEl[0], b = aEl[1], c = aEl[2], d = aEl[3], e = aEl[4], f = aEl[5], g = aEl[6], h = aEl[7], i = aEl[8], j = aEl[9], k = aEl[10], l = aEl[11], m = aEl[12], n = aEl[13], o = aEl[14], p = aEl[15]; const A = bEl[0], B = bEl[1], C = bEl[2], D = bEl[3], E = bEl[4], F = bEl[5], G = bEl[6], H = bEl[7], I = bEl[8], J = bEl[9], K = bEl[10], L = bEl[11], M = bEl[12], N = bEl[13], O = bEl[14], P = bEl[15]; this._el[0] = A * a + B * e + C * i + D * m; this._el[1] = A * b + B * f + C * j + D * n; this._el[2] = A * c + B * g + C * k + D * o; this._el[3] = A * d + B * h + C * l + D * p; this._el[4] = E * a + F * e + G * i + H * m; this._el[5] = E * b + F * f + G * j + H * n; this._el[6] = E * c + F * g + G * k + H * o; this._el[7] = E * d + F * h + G * l + H * p; this._el[8] = I * a + J * e + K * i + L * m; this._el[9] = I * b + J * f + K * j + L * n; this._el[10] = I * c + J * g + K * k + L * o; this._el[11] = I * d + J * h + K * l + L * p; this._el[12] = M * a + N * e + O * i + P * m; this._el[13] = M * b + N * f + O * j + P * n; this._el[14] = M * c + N * g + O * k + P * o; this._el[15] = M * d + N * h + O * l + P * p; return this; } /** * 渡されたベクトル分拡大縮小する */ public scale(vec: number[]) { this._el[0] = this._el[0] * vec[0]; this._el[1] = this._el[1] * vec[0]; this._el[2] = this._el[2] * vec[0]; this._el[3] = this._el[3] * vec[0]; this._el[4] = this._el[4] * vec[1]; this._el[5] = this._el[5] * vec[1]; this._el[6] = this._el[6] * vec[1]; this._el[7] = this._el[7] * vec[1]; this._el[8] = this._el[8] * vec[2]; this._el[9] = this._el[9] * vec[2]; this._el[10] = this._el[10] * vec[2]; this._el[11] = this._el[11] * vec[2]; return this; } public translate(vec3: number[]) { this._el[12] = this._el[0] * vec3[0] + this._el[4] * vec3[1] + this._el[8] * vec3[2] + this._el[12]; this._el[13] = this._el[1] * vec3[0] + this._el[5] * vec3[1] + this._el[9] * vec3[2] + this._el[13]; this._el[14] = this._el[2] * vec3[0] + this._el[6] * vec3[1] + this._el[10] * vec3[2] + this._el[14]; this._el[15] = this._el[3] * vec3[0] + this._el[7] * vec3[1] + this._el[11] * vec3[2] + this._el[15]; return this; } public rotate(angle: number, axis: number[]) { let sq = Math.sqrt( axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2] ); if (!sq) { return; } let a = axis[0], b = axis[1], c = axis[2]; if (sq !== 1) { sq = 1 / sq; a *= sq; b *= sq; c *= sq; } const d = Math.sin(angle), e = Math.cos(angle), f = 1 - e, g = this._el[0], h = this._el[1], i = this._el[2], j = this._el[3], k = this._el[4], l = this._el[5], m = this._el[6], n = this._el[7], o = this._el[8], p = this._el[9], q = this._el[10], r = this._el[11], s = a * a * f + e, t = b * a * f + c * d, u = c * a * f - b * d, v = a * b * f - c * d, w = b * b * f + e, x = c * b * f + a * d, y = a * c * f + b * d, z = b * c * f - a * d, A = c * c * f + e; this._el[0] = g * s + k * t + o * u; this._el[1] = h * s + l * t + p * u; this._el[2] = i * s + m * t + q * u; this._el[3] = j * s + n * t + r * u; this._el[4] = g * v + k * w + o * x; this._el[5] = h * v + l * w + p * x; this._el[6] = i * v + m * w + q * x; this._el[7] = j * v + n * w + r * x; this._el[8] = g * y + k * z + o * A; this._el[9] = h * y + l * z + p * A; this._el[10] = i * y + m * z + q * A; this._el[11] = j * y + n * z + r * A; return this; } /** * ビュー変換行列を生成する */ public lookAt(eye: Vector3, center: Vector3, up: Vector3) { const eyeX = eye.x, eyeY = eye.y, eyeZ = eye.z, upX = up.x, upY = up.y, upZ = up.z, centerX = center.x, centerY = center.y, centerZ = center.z; if (eyeX === centerX && eyeY === centerY && eyeZ === centerZ) { this.identity(); return; } let x0, x1, x2, y0, y1, y2, z0, z1, z2, l; z0 = eyeX - center.x; z1 = eyeY - center.y; z2 = eyeZ - center.z; l = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= l; z1 *= l; z2 *= l; x0 = upY * z2 - upZ * z1; x1 = upZ * z0 - upX * z2; x2 = upX * z1 - upY * z0; l = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (!l) { x0 = 0; x1 = 0; x2 = 0; } else { l = 1 / l; x0 *= l; x1 *= l; x2 *= l; } y0 = z1 * x2 - z2 * x1; y1 = z2 * x0 - z0 * x2; y2 = z0 * x1 - z1 * x0; l = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (!l) { y0 = 0; y1 = 0; y2 = 0; } else { l = 1 / l; y0 *= l; y1 *= l; y2 *= l; } this._el[0] = x0; this._el[1] = y0; this._el[2] = z0; this._el[3] = 0; this._el[4] = x1; this._el[5] = y1; this._el[6] = z1; this._el[7] = 0; this._el[8] = x2; this._el[9] = y2; this._el[10] = z2; this._el[11] = 0; this._el[12] = -(x0 * eyeX + x1 * eyeY + x2 * eyeZ); this._el[13] = -(y0 * eyeX + y1 * eyeY + y2 * eyeZ); this._el[14] = -(z0 * eyeX + z1 * eyeY + z2 * eyeZ); this._el[15] = 1; return this; } /** * プロジェクション変換行列を生成する */ public perspective(fovy: number, aspect: number, near: number, far: number) { const t = near * Math.tan((fovy * Math.PI) / 360); const r = t * aspect; const a = r * 2, b = t * 2, c = far - near; this._el[0] = (near * 2) / a; this._el[1] = 0; this._el[2] = 0; this._el[3] = 0; this._el[4] = 0; this._el[5] = (near * 2) / b; this._el[6] = 0; this._el[7] = 0; this._el[8] = 0; this._el[9] = 0; this._el[10] = -(far + near) / c; this._el[11] = -1; this._el[12] = 0; this._el[13] = 0; this._el[14] = -(far * near * 2) / c; this._el[15] = 0; return this; } /** * 行列を転置する */ public transpose() { const a = this._el[0], b = this._el[1], c = this._el[2], d = this._el[3], e = this._el[4], f = this._el[5], g = this._el[6], h = this._el[7], i = this._el[8], j = this._el[9], k = this._el[10], l = this._el[11], m = this._el[12], n = this._el[13], o = this._el[14], p = this._el[15]; this._el[0] = a; this._el[1] = e; this._el[2] = i; this._el[3] = m; this._el[4] = b; this._el[5] = f; this._el[6] = j; this._el[7] = n; this._el[8] = c; this._el[9] = g; this._el[10] = k; this._el[11] = o; this._el[12] = d; this._el[13] = h; this._el[14] = l; this._el[15] = p; return this; } /** * 逆行列を生成する */ public inverse() { const a = this._el[0], b = this._el[1], c = this._el[2], d = this._el[3], e = this._el[4], f = this._el[5], g = this._el[6], h = this._el[7], i = this._el[8], j = this._el[9], k = this._el[10], l = this._el[11], m = this._el[12], n = this._el[13], o = this._el[14], p = this._el[15]; const q = a * f - b * e, r = a * g - c * e, s = a * h - d * e, t = b * g - c * f, u = b * h - d * f, v = c * h - d * g, w = i * n - j * m, x = i * o - k * m, y = i * p - l * m, z = j * o - k * n, A = j * p - l * n, B = k * p - l * o, ivd = 1 / (q * B - r * A + s * z + t * y - u * x + v * w); this._el[0] = (f * B - g * A + h * z) * ivd; this._el[1] = (-b * B + c * A - d * z) * ivd; this._el[2] = (n * v - o * u + p * t) * ivd; this._el[3] = (-j * v + k * u - l * t) * ivd; this._el[4] = (-e * B + g * y - h * x) * ivd; this._el[5] = (a * B - c * y + d * x) * ivd; this._el[6] = (-m * v + o * s - p * r) * ivd; this._el[7] = (i * v - k * s + l * r) * ivd; this._el[8] = (e * A - f * y + h * w) * ivd; this._el[9] = (-a * A + b * y - d * w) * ivd; this._el[10] = (m * u - n * s + p * q) * ivd; this._el[11] = (-i * u + j * s - l * q) * ivd; this._el[12] = (-e * z + f * x - g * w) * ivd; this._el[13] = (a * z - b * x + c * w) * ivd; this._el[14] = (-m * t + n * r - o * q) * ivd; this._el[15] = (i * t - j * r + k * q) * ivd; return this; } /** * 複製する */ public clone() { const newMat = new Matrix4(); const a = this._el[0], b = this._el[1], c = this._el[2], d = this._el[3], e = this._el[4], f = this._el[5], g = this._el[6], h = this._el[7], i = this._el[8], j = this._el[9], k = this._el[10], l = this._el[11], m = this._el[12], n = this._el[13], o = this._el[14], p = this._el[15]; newMat.el[0] = a; newMat.el[1] = b; newMat.el[2] = c; newMat.el[3] = d; newMat.el[4] = e; newMat.el[5] = f; newMat.el[6] = g; newMat.el[7] = h; newMat.el[8] = i; newMat.el[9] = j; newMat.el[10] = k; newMat.el[11] = l; newMat.el[12] = m; newMat.el[13] = n; newMat.el[14] = o; newMat.el[15] = p; return newMat; } /** * 渡されたMatrix4の値を自分へコピーする */ public copy(mat: Matrix4) { this._el[0] = mat.el[0]; this._el[1] = mat.el[1]; this._el[2] = mat.el[2]; this._el[3] = mat.el[3]; this._el[4] = mat.el[4]; this._el[5] = mat.el[5]; this._el[6] = mat.el[6]; this._el[7] = mat.el[7]; this._el[8] = mat.el[8]; this._el[9] = mat.el[9]; this._el[10] = mat.el[10]; this._el[11] = mat.el[11]; this._el[12] = mat.el[12]; this._el[13] = mat.el[13]; this._el[14] = mat.el[14]; this._el[15] = mat.el[15]; return this; } public compose(position: Vector3, quaternion: Quaternion, scale: Vector3) { const x = quaternion.x, y = quaternion.y, z = quaternion.z, w = quaternion.w; const x2 = x + x, y2 = y + y, z2 = z + z; const xx = x * x2, xy = x * y2, xz = x * z2; const yy = y * y2, yz = y * z2, zz = z * z2; const wx = w * x2, wy = w * y2, wz = w * z2; const sx = scale.x, sy = scale.y, sz = scale.z; this._el[0] = (1 - (yy + zz)) * sx; this._el[1] = (xy + wz) * sx; this._el[2] = (xz - wy) * sx; this._el[3] = 0; this._el[4] = (xy - wz) * sy; this._el[5] = (1 - (xx + zz)) * sy; this._el[6] = (yz + wx) * sy; this._el[7] = 0; this._el[8] = (xz + wy) * sz; this._el[9] = (yz - wx) * sz; this._el[10] = (1 - (xx + yy)) * sz; this._el[11] = 0; this._el[12] = position.x; this._el[13] = position.y; this._el[14] = position.z; this._el[15] = 1; return this; } public getInverse(mat: Matrix4) { const a = mat.el[0], b = mat.el[1], c = mat.el[2], d = mat.el[3], e = mat.el[4], f = mat.el[5], g = mat.el[6], h = mat.el[7], i = mat.el[8], j = mat.el[9], k = mat.el[10], l = mat.el[11], m = mat.el[12], n = mat.el[13], o = mat.el[14], p = mat.el[15], q = a * f - b * e, r = a * g - c * e, s = a * h - d * e, t = b * g - c * f, u = b * h - d * f, v = c * h - d * g, w = i * n - j * m, x = i * o - k * m, y = i * p - l * m, z = j * o - k * n, A = j * p - l * n, B = k * p - l * o, ivd = 1 / (q * B - r * A + s * z + t * y - u * x + v * w); this._el[0] = (f * B - g * A + h * z) * ivd; this._el[1] = (-b * B + c * A - d * z) * ivd; this._el[2] = (n * v - o * u + p * t) * ivd; this._el[3] = (-j * v + k * u - l * t) * ivd; this._el[4] = (-e * B + g * y - h * x) * ivd; this._el[5] = (a * B - c * y + d * x) * ivd; this._el[6] = (-m * v + o * s - p * r) * ivd; this._el[7] = (i * v - k * s + l * r) * ivd; this._el[8] = (e * A - f * y + h * w) * ivd; this._el[9] = (-a * A + b * y - d * w) * ivd; this._el[10] = (m * u - n * s + p * q) * ivd; this._el[11] = (-i * u + j * s - l * q) * ivd; this._el[12] = (-e * z + f * x - g * w) * ivd; this._el[13] = (a * z - b * x + c * w) * ivd; this._el[14] = (-m * t + n * r - o * q) * ivd; this._el[15] = (i * t - j * r + k * q) * ivd; return this; } } export default Matrix4;
the_stack
import { expect } from 'chai'; import { render, act, RenderResult } from '@testing-library/react'; import * as sinon from 'sinon'; import { ArcView } from '../../../src/ts/components/ArcBase'; import { MapBase, WebBase } from '../../../src/ts/components/ArcComposites'; function renderMapBase({ scriptUri = ['foo', 'bar'], ...restProps }: Partial<React.ComponentProps<typeof MapBase>> = {}): RenderResult { return render(<MapBase scriptUri={scriptUri} {...restProps} />); }; function renderWebBase({ id = "foobar", scriptUri = ['foo', 'bar'], ...restProps }: Partial<React.ComponentProps<typeof WebBase>> = {}): RenderResult { return render(<WebBase id={id} scriptUri={scriptUri} {...restProps} />); }; export const MapBaseTests = () => ( describe('MapBase', () => { describe('as a shallow component', () => { it('should exist', async () => { const { container } = renderMapBase(); await act(async () => { expect(container.querySelector('#base-container')).to.exist; }); }); }); describe('as a mounted component', () => { beforeEach(() => { sinon.spy(ArcView.prototype, 'componentDidMount'); }); it('should call componentDidMount', async () => { renderMapBase(); await act(async () => { expect(ArcView.prototype.componentDidMount['callCount']).to.equal(1); }); }); describe('esriPromise succeeds', () => { describe('loadMap successfully creates the map and view', () => { before(() => { global['asyncSuccess'] = true; global['generateMap'] = true; }); it('should display the loaded state of the application', async () => { const mapBase = renderMapBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = mapBase; expect(container.querySelector('#react-arcgis-fail-text')).to.not.exist; expect(container.querySelector('#react-arcgis-loading-text')).to.not.exist; }); describe('the user has included custom event handlers', () => { const handler = () => 'foobar'; it('should display the loaded state of the application', async () => { const mapBase = renderMapBase({ onMouseWheel: handler }); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = mapBase; expect(container.querySelector('#react-arcgis-fail-text')).to.not.exist; expect(container.querySelector('#react-arcgis-loading-text')).to.not.exist; }); it('should pass the event handler to the ArcGIS JS API', (done) => { setTimeout(() => { done(); }, 1); }); }); after(() => { global['asyncSuccess'] = false; global['generateMap'] = false; }); }); describe('loadMap returns a map which fails to load', () => { before(() => { global['asyncSuccess'] = true; global['generateMap'] = false; global['generateBrokenMap'] = true; }); it('should display the failed state of the application', async () => { const mapBase = renderMapBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = mapBase; expect(container.querySelector('#react-arcgis-fail-text')).to.exist; expect(container.querySelector('#react-arcgis-loading-text')).to.not.exist; }); after(() => { global['asyncSuccess'] = false; global['generateMap'] = false; global['generateBrokenMap'] = false; }); }); describe('loadMap fails before the view is instantiated', () => { before(() => { global['asyncSuccess'] = true; global['generateMap'] = false; }); it('should display the failed state for the application', async () => { const mapBase = renderMapBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = mapBase; expect(container.querySelector('#react-arcgis-fail-text')).to.exist; }); after(() => { global['asyncSuccess'] = false; global['generateMap'] = false; }); }); }); afterEach(() => { ArcView.prototype.componentDidMount['restore'](); }); }); }) ); export const WebBaseTests = () => ( describe('WebBase', () => { describe('as a shallow component', () => { it('should exist', async () => { const { container } = renderWebBase(); await act(async () => { expect(container.querySelector('#base-container')).to.exist; }); }); }); describe('as a mounted component', () => { beforeEach(() => { sinon.spy(ArcView.prototype, 'componentDidMount'); }); it('should call componentDidMount', async () => { renderWebBase(); await act(async () => { expect(ArcView.prototype.componentDidMount['callCount']).to.equal(1); }); }); describe('loadMap successfully creates the map and view', () => { before(() => { global['asyncSuccess'] = true; global['generateWebMap'] = true; }); it('should display the loaded state of the application', async () => { const webBase = renderWebBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = webBase; expect(container.querySelector('#react-arcgis-fail-text')).to.not.exist; expect(container.querySelector('#react-arcgis-loading-text')).to.not.exist; }); describe('the user has included custom event handlers', () => { const handler = () => 'foobar'; it('should display the loaded state of the application', async () => { const webBase = renderWebBase({ onMouseWheel: handler }); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container } = webBase; expect(container.querySelector('#react-arcgis-fail-text')).to.not.exist; expect(container.querySelector('#react-arcgis-loading-text')).to.not.exist; }); it('should pass the event handler to the ArcGIS JS API', (done) => { setTimeout(() => { done(); }, 1); }); }); after(() => { global['asyncSuccess'] = false; global['generateWebMap'] = false; }); }); describe('loadMap returns a map which fails to load', () => { before(() => { global['asyncSuccess'] = true; global['generateBadWebMap'] = true; }); it('should display the failed state for the application', async () => { const webBase = renderWebBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container} = webBase; expect(container.querySelector('#react-arcgis-fail-text')).to.exist; }); after(() => { global['asyncSuccess'] = false; global['generateBadWebMap'] = false; }); }); describe('loadMap fails before the view is instantiated', () => { before(() => { global['asyncSuccess'] = true; global['generateMap'] = false; }); it('should display the failed state for the application', async () => { const webBase = renderWebBase(); // Wait for implicit async state update in componentDidUpdate await act(async () => {}); const { container} = webBase; expect(container.querySelector('#react-arcgis-fail-text')).to.exist; }); after(() => { global['asyncSuccess'] = false; global['generateMap'] = false; }); }); afterEach(() => { ArcView.prototype.componentDidMount['restore'](); }); }); }) );
the_stack
import { isPlatform, modalController, alertController, popoverController, actionSheetController, menuController, useBackButton } from '@ionic/vue'; import { App } from '@capacitor/app'; import { Clipboard } from '@capacitor/clipboard'; import { Toast } from '@capacitor/toast'; import { ScreenReader } from '@capacitor/screen-reader'; import { StatusBar, Style } from '@capacitor/status-bar'; import { UserSettings } from "./UserSettings"; import { Locale } from "./Locale"; import Autolinker from 'autolinker'; import Moment from "moment"; import { Shortcuts } from './Shortcuts'; import { Emitter } from './Emitter'; declare global { interface Window { Titlebar: any; } interface Navigator { registerProtocolHandler : (scheme: string, url: string, title: string) => void; unregisterProtocolHandler : (scheme: string, url: string) => void; } } const ipToCountryList: Record<string,any> = {}; let ipToCountryLimit = 45; let ipToCountryWaitUntil: any; export const Utils = { formatBytes(bytes: number, decimals = 2, speed = false): string|void{ if(bytes===undefined||bytes<0) return; const useSpeed = speed && UserSettings.state.useBits; const k = useSpeed ? 1000 : 1024; let unit = useSpeed ? Locale.units.bit : Locale.units.byte; if(speed){ unit += Locale.units.perSecond } const dm = decimals < 0 ? 0 : decimals; const sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; if (bytes === 0) return '0 ' + unit; const val = (useSpeed) ? bytes*8 : bytes const i = Math.floor(Math.log(val) / Math.log(k)); return (val / Math.pow(k, i)).toLocaleString(UserSettings.getLanguage(), {maximumFractionDigits:dm}) + ' ' + sizes[i] + unit; }, getPercent(percentDone=0): string { return (percentDone*100).toLocaleString(UserSettings.getLanguage(), {maximumFractionDigits:2})+'%' }, getRatio(ratio=0, decimal=3): string { return ratio.toLocaleString(UserSettings.getLanguage(), {maximumFractionDigits:decimal}); }, durationToString(seconds: number): string{ if(seconds<0) return "∞"; Moment.locale(UserSettings.getLanguage()) const duration = Moment.duration(seconds) return duration.humanize(); }, secondsToDate(seconds: number, timeSince=false, hourOnly=false): string{ if(seconds === 0) return Locale.never; Moment.locale(UserSettings.getLanguage()) const data = Moment(seconds*1000); let result = data.format(hourOnly && data.isSame(Date.now(), 'day') ? 'LT' : 'L LT'); if(timeSince){ result += " (" + this.timeSince(seconds) + ")"; } return result }, timeSince(seconds: number): string{ Moment.locale(UserSettings.getLanguage()) const since = Moment.duration(Date.now()-seconds*1000); return Locale.formatString(Locale.ago,since.humanize()) as string; }, autoLink(unsafe: string): string { return Autolinker.link(unsafe,{ stripPrefix:false, stripTrailingSlash:false, sanitizeHtml:true }) }, async clipboardCopy(text: string): Promise<any> { let promise; if(isPlatform("capacitor")){ promise = Clipboard.write({string: text}) } else if(navigator.clipboard && navigator.clipboard.writeText) { promise = navigator.clipboard.writeText(text) } else { const input = document.createElement('input'); document.body.appendChild(input); input.value = text; input.focus(); input.select(); const result = document.execCommand('copy'); input.remove(); if (!result) { throw Error('Failed to copy text.') } } return promise; }, async ipToCountry(ip: string): Promise<any>{ const wait = (ipToCountryWaitUntil && Date.now() < ipToCountryWaitUntil)||false; const found = (ipToCountryList[ip]!=null); const limited = (ipToCountryLimit<=0); if(found && ipToCountryList[ip]!="loading"){ return ipToCountryList[ip]; } else if(!found && (!limited || !wait)) { ipToCountryLimit--; ipToCountryList[ip]="loading"; ipToCountryWaitUntil=undefined; ipToCountryList[ip] = await fetch('http://ip-api.com/json/'+ip+'?fields=16387&lang='+UserSettings.getLanguage()) .then(this.readIpApi) if(ipToCountryList[ip]==null){ ipToCountryWaitUntil = Date.now() + 60000; } else { return ipToCountryList[ip]; } } }, async readIpApi(response: Record<string,any>): Promise<any> { // Read the number of requests remaining in the current rate limit window const limit = response.headers.get('X-Rl'); ipToCountryLimit = limit ? parseInt(limit) : ipToCountryLimit; if(ipToCountryLimit==0){ const wait = response.headers.get('X-Ttl'); ipToCountryWaitUntil = wait ? Date.now() + parseInt(wait)*1000 : Date.now() + 60000 } if(response.ok){ const details = await response.json(); if(details.status=="success"){ return details; } } }, trackerDomain(host: string): Record<string,any>{ let result={}; //eslint-disable-next-line const regex = /^([\w]+):\/\/([\w\d\.-]+):?(\d+)?/; const matchs = host.match(regex); if(matchs){ result = { protocol:matchs[1], domain:matchs[2], port:matchs[3] || 80 } } return result; }, actionStatusResult(action: string, current: number, percentDone: number): number{ // Predict what will be the status of a torrent after an action switch (action) { case "start": case "start-now": return (percentDone==1) ? 6 : 4; case "verify": return 2; case "stop": return 0; default: return current; } }, setTheme(theme: string): void { const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches || window.navigator.userAgent.includes('AndroidDarkMode'); let dark: boolean; switch (theme) { case "light": dark=false; break; case "dark": dark=true; break; default: dark=prefersDark break; } document.body.classList.toggle('dark', dark); this.setStatusBarColor(dark); }, async responseToast(result: string): Promise<void> { let text; switch (result) { case "success": text = Locale.success break; case "": text = Locale.error.error break; default: text = this.localizeError(result); break; } await Toast.show({text}); try { if(await ScreenReader.isEnabled()){ await ScreenReader.speak({ value: text, language: UserSettings.getLanguage() }); } } catch (e) { return; } }, localizeError(error: string): string{ let result; let str = error ? error.toLowerCase() : ""; const electronError = str.match(/net::[a-z_]+/) str = electronError ? electronError[0] : str; switch (str) { case "unable to reach host (timeout)": case "net::err_connection_timed_out": result = Locale.error.timeout; break; case "net::err_internet_disconnected": result = "No internet connection"; break; case "unable to reach host": case "net::err_connection_refused": result = Locale.error.hostUnreachable; break; case "unable to reach transmission daemon": result = Locale.error.daemonUnreachable; break; case "invalid token": result = Locale.error.invalidToken; break; case "authentication error": result = Locale.error.authenticationError; break; case "torrent not found": result = Locale.error.torrentNotFound; break; case "invalid argument": result = Locale.error.invalidArgument; break; case "http -1": result = Locale.error.requestAborted; break; case "connection failed": result = Locale.error.connectionFailed; break; case "could not connect to tracker": result = Locale.error.trackerConnectionError; break; case "no data found! ensure your drives are connected or use \"set location\". to re-download, remove the torrent and re-add it.": result = Locale.error.noDataFound; break; case "download directory path is not absolute": result = Locale.error.pathNotAbsolute; break; case "tracker did not respond": result = Locale.error.trackerDidNotRespond; break; case "not found": result = Locale.error.notFound; break; case "no response": result = Locale.error.noResponse; break; default: result = error; break; } if(result){ const trackerError = result.match(/Tracker gave HTTP response code (\d+) \(([\w\s]+)\)/); if(trackerError){ result = Locale.formatString(Locale.error.trackerResponseCode, trackerError[1], this.localizeError(trackerError[2])).toString(); } } return result; }, customScrollbar(el: unknown, shadowRoot=true, padding=true): void{ if(el && isPlatform("desktop")){ let content; if((el as any).$el){ content = (el as any).$el as Element; } else{ content = el as Element; } const styles = document.createElement('style'); styles.textContent = ` ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-track { background:transparent; } ::-webkit-scrollbar-thumb { background:rgba(127,127,127,.2); border-radius:3px; } ::-webkit-scrollbar-thumb:hover { background:rgba(127,127,127,.5); } `; if(padding){ styles.textContent+= ` ::-webkit-scrollbar-button:increment { height:var(--offset-bottom); } ::-webkit-scrollbar-button:decrement { height:var(--offset-top); } `; } if(shadowRoot && content.shadowRoot){ content.shadowRoot.appendChild(styles); } else { content.appendChild(styles); } } }, customTitlebar(): void { if(window.Titlebar){ window.Titlebar.new(); window.Titlebar.shortcuts((shortcut: string) => { Shortcuts.call(shortcut); }); } }, setStatusBarColor(isDark: boolean): void { const statusBarColor = getComputedStyle(document.body).getPropertyValue('--ion-toolbar-background') || getComputedStyle(document.body).getPropertyValue('--ion-color-light') // --ion-color-primary if(isPlatform("capacitor") && (isPlatform("android") || isPlatform("ios"))){ StatusBar.setStyle({style: isDark ? Style.Dark : Style.Light}); StatusBar.setBackgroundColor({color:statusBarColor}); } else if(isPlatform("electron")){ if(window.Titlebar){ window.Titlebar.updateBackground(statusBarColor) } } }, customDirectives(app: Record<string, any>): void { app.directive('longpress', { beforeMount(el: any, binding: any) { let pressTimer: any = null const handler = () => { binding.value(parseInt(el.getAttribute("attr-id"))) } const start = (e: any) => { if (e.type === 'click' && e.button !== 0) { return; } if (pressTimer === null) { binding.value(); // Init fallback pressTimer = setTimeout(() => { handler() }, 600) } } const cancel = () => { if (pressTimer !== null) { clearTimeout(pressTimer) pressTimer = null } } el.addEventListener("mousedown", start); el.addEventListener("touchstart", start, {passive: true}); el.addEventListener("click", cancel); el.addEventListener("mouseout", cancel); el.addEventListener("mouseup", cancel); el.addEventListener("touchend", cancel); el.addEventListener("touchcancel", cancel); el.addEventListener("touchmove", cancel, {passive: true}); } }) }, backButtonHandle(): void { Emitter.on('back', () => { this.popState() }); if(isPlatform('capacitor')){ useBackButton(-1, async () => { const top = await this.getTop(); if(!top.hasTop){ App.exitApp(); } }); } else { window.addEventListener('popstate', (e: any) => { if (e.origin && e.origin !== window.location.origin) return; this.popState(e) }); } }, async popState(e: Event|null=null): Promise<void> { const top = await this.getTop(); if(top.hasTop){ e?.preventDefault(); history.go(1); } if(top.actionsheet){ top.actionsheet.dismiss(); } else if(top.popover){ top.popover.dismiss(); } else if(top.alert){ top.alert.dismiss(); } else if(top.modal){ top.modal.dismiss(); } else if(top.menu){ menuController.close(); } }, pushState(): void { if (!window.history.state.modal) { const modalState = { modal: true }; history.pushState(modalState, ""); } }, async getTop(): Promise<Record<string,any>> { const menu = await menuController.isOpen(); const modal = await modalController.getTop(); const alert = await alertController.getTop(); const popover = await popoverController.getTop(); const actionsheet = await actionSheetController.getTop(); return { menu, modal, alert, popover, actionsheet, hasTop:(menu || modal || alert || popover || actionsheet) } }, async loadAppleTouchIcon(): Promise<void> { // Workaround to prevent authentication error on iOS, see https://trac.transmissionbt.com/ticket/5329 const data: string = await fetch("./assets/icon/apple-touch-icon.png") .then(response => response.blob()) .then(blob => new Promise((resolve, reject) => { const reader = new FileReader() reader.onloadend = () => resolve(reader.result as string) reader.onerror = reject reader.readAsDataURL(blob) })) document.querySelector("link[title=ATI]")?.setAttribute("href",data); }, registerMagnetLinkProtocol(): void { if(!isPlatform("electron") && !isPlatform("capacitor")){ const href = window.location.href.replace(window.location.hash,""); if(UserSettings.state.openMagnetLinks){ if(navigator.registerProtocolHandler){ navigator.registerProtocolHandler("magnet", `${href}#%s`, "Transmissionic Magnet Handler" ); } } else if(navigator.unregisterProtocolHandler){ navigator.unregisterProtocolHandler("magnet", `${href}#%s`); } } } }
the_stack
import { binToHex, flattenBinArray, numberToBinUint16LE, numberToBinUint32LE, } from '../../format/format'; import { createCompilerCommonSynchronous } from '../../template/compiler'; import { AuthenticationProgramStateCommon } from '../vm-types'; import { AuthenticationErrorBCH, OpcodesBCH } from './bch/bch'; import { OpcodesBTC } from './btc/btc'; import { AuthenticationInstruction, AuthenticationInstructionPush, ParsedAuthenticationInstruction, ParsedAuthenticationInstructionMalformed, ParsedAuthenticationInstructionPushMalformedLength, ParsedAuthenticationInstructions, } from './instruction-sets-types'; /** * A type-guard which checks if the provided instruction is malformed. * @param instruction - the instruction to check */ export const authenticationInstructionIsMalformed = <Opcodes>( instruction: ParsedAuthenticationInstruction<Opcodes> ): instruction is ParsedAuthenticationInstructionMalformed<Opcodes> => 'malformed' in instruction; /** * A type-guard which checks if the final instruction in the provided array of * instructions is malformed. (Only the final instruction can be malformed.) * @param instruction - the array of instructions to check */ export const authenticationInstructionsAreMalformed = <Opcodes>( instructions: ParsedAuthenticationInstructions<Opcodes> ): instructions is ParsedAuthenticationInstructionMalformed<Opcodes>[] => instructions.length > 0 && authenticationInstructionIsMalformed(instructions[instructions.length - 1]); /** * A type-guard which confirms that the final instruction in the provided array * is not malformed. (Only the final instruction can be malformed.) * @param instruction - the array of instructions to check */ export const authenticationInstructionsAreNotMalformed = <Opcodes>( instructions: ParsedAuthenticationInstructions<Opcodes> ): instructions is AuthenticationInstruction<Opcodes>[] => !authenticationInstructionsAreMalformed(instructions); enum CommonPushOpcodes { OP_0 = 0x00, OP_PUSHDATA_1 = 0x4c, OP_PUSHDATA_2 = 0x4d, OP_PUSHDATA_4 = 0x4e, } const uint8Bytes = 1; const uint16Bytes = 2; const uint32Bytes = 4; const readLittleEndianNumber = ( script: Uint8Array, index: number, length: typeof uint8Bytes | typeof uint16Bytes | typeof uint32Bytes ) => { const view = new DataView(script.buffer, index, length); const readAsLittleEndian = true; return length === uint8Bytes ? view.getUint8(0) : length === uint16Bytes ? view.getUint16(0, readAsLittleEndian) : view.getUint32(0, readAsLittleEndian); }; /** * Returns the number of bytes used to indicate the length of the push in this * operation. * @param opcode - an opcode between 0x00 and 0x4e */ export const lengthBytesForPushOpcode = (opcode: number) => opcode < CommonPushOpcodes.OP_PUSHDATA_1 ? 0 : opcode === CommonPushOpcodes.OP_PUSHDATA_1 ? uint8Bytes : opcode === CommonPushOpcodes.OP_PUSHDATA_2 ? uint16Bytes : uint32Bytes; /** * Parse one instruction from the provided script. * * Returns an object with an `instruction` referencing a * `ParsedAuthenticationInstruction`, and a `nextIndex` indicating the next * index from which to read. If the next index is greater than or equal to the * length of the script, the script has been fully parsed. * * The final `ParsedAuthenticationInstruction` from a serialized script may be * malformed if 1) the final operation is a push and 2) too few bytes remain for * the push operation to complete. * * @param script - the script from which to read the next instruction * @param index - the offset from which to begin reading */ // eslint-disable-next-line complexity export const readAuthenticationInstruction = <Opcodes = number>( script: Uint8Array, index: number ): { instruction: ParsedAuthenticationInstruction<Opcodes>; nextIndex: number; } => { const opcode = script[index]; if (opcode > CommonPushOpcodes.OP_PUSHDATA_4) { return { instruction: { opcode: (opcode as unknown) as Opcodes, }, nextIndex: index + 1, }; } const lengthBytes = lengthBytesForPushOpcode(opcode); if (lengthBytes !== 0 && index + lengthBytes >= script.length) { const sliceStart = index + 1; const sliceEnd = sliceStart + lengthBytes; return { instruction: { expectedLengthBytes: lengthBytes, length: script.slice(sliceStart, sliceEnd), malformed: true, opcode: (opcode as unknown) as Opcodes, }, nextIndex: sliceEnd, }; } const dataBytes = lengthBytes === 0 ? opcode : readLittleEndianNumber(script, index + 1, lengthBytes); const dataStart = index + 1 + lengthBytes; const dataEnd = dataStart + dataBytes; return { instruction: { data: script.slice(dataStart, dataEnd), ...(dataEnd > script.length ? { expectedDataBytes: dataEnd - dataStart, malformed: true, } : undefined), opcode: (opcode as unknown) as Opcodes, }, nextIndex: dataEnd, }; }; /** * Parse authentication bytecode (`lockingBytecode` or `unlockingBytecode`) * into `ParsedAuthenticationInstructions`. The method * `authenticationInstructionsAreMalformed` can be used to check if these * instructions include a malformed instruction. If not, they are valid * `AuthenticationInstructions`. * * This implementation is common to most bitcoin forks, but the type parameter * can be used to strongly type the resulting instructions. For example: * * ```js * const instructions = parseAuthenticationBytecode<OpcodesBCH>(script); * ``` * * @param script - the serialized script to parse */ export const parseBytecode = <Opcodes = number>(script: Uint8Array) => { const instructions: ParsedAuthenticationInstructions<Opcodes> = []; // eslint-disable-next-line functional/no-let let i = 0; // eslint-disable-next-line functional/no-loop-statement while (i < script.length) { const { instruction, nextIndex } = readAuthenticationInstruction<Opcodes>( script, i ); // eslint-disable-next-line functional/no-expression-statement i = nextIndex; // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data instructions.push(instruction); } return instructions; }; /** * OP_0 is the only single-word push. All other push instructions will * disassemble to multiple ASM words. (OP_1-OP_16 are handled like normal * operations.) */ const isMultiWordPush = (opcode: number) => opcode !== CommonPushOpcodes.OP_0; const formatAsmPushHex = (data: Uint8Array) => data.length > 0 ? `0x${binToHex(data)}` : ''; const formatMissingBytesAsm = (missing: number) => `[missing ${missing} byte${missing === 1 ? '' : 's'}]`; const hasMalformedLength = <Opcodes>( instruction: ParsedAuthenticationInstructionMalformed<Opcodes> ): instruction is ParsedAuthenticationInstructionPushMalformedLength<Opcodes> => 'length' in instruction; const isPushData = (pushOpcode: number) => pushOpcode >= CommonPushOpcodes.OP_PUSHDATA_1; /** * Disassemble a malformed authentication instruction into a string description. * @param opcodes - a mapping of possible opcodes to their string representation * @param instruction - the malformed instruction to disassemble */ export const disassembleParsedAuthenticationInstructionMalformed = < Opcodes = number >( opcodes: { readonly [opcode: number]: string }, instruction: ParsedAuthenticationInstructionMalformed<Opcodes> ): string => `${opcodes[(instruction.opcode as unknown) as number]} ${ hasMalformedLength(instruction) ? `${formatAsmPushHex(instruction.length)}${formatMissingBytesAsm( instruction.expectedLengthBytes - instruction.length.length )}` : `${ isPushData((instruction.opcode as unknown) as number) ? `${instruction.expectedDataBytes} ` : '' }${formatAsmPushHex(instruction.data)}${formatMissingBytesAsm( instruction.expectedDataBytes - instruction.data.length )}` }`; /** * Disassemble a properly-formed authentication instruction into a string * description. * @param opcodes - a mapping of possible opcodes to their string representation * @param instruction - the instruction to disassemble */ export const disassembleAuthenticationInstruction = <Opcodes = number>( opcodes: { readonly [opcode: number]: string }, instruction: AuthenticationInstruction<Opcodes> ): string => `${opcodes[(instruction.opcode as unknown) as number]}${ 'data' in instruction && isMultiWordPush((instruction.opcode as unknown) as number) ? ` ${ isPushData((instruction.opcode as unknown) as number) ? `${instruction.data.length} ` : '' }${formatAsmPushHex(instruction.data)}` : '' }`; /** * Disassemble a single `ParsedAuthenticationInstruction` (includes potentially * malformed instructions) into its ASM representation. * * @param script - the instruction to disassemble */ export const disassembleParsedAuthenticationInstruction = <Opcodes = number>( opcodes: { readonly [opcode: number]: string }, instruction: ParsedAuthenticationInstruction<Opcodes> ): string => authenticationInstructionIsMalformed(instruction) ? disassembleParsedAuthenticationInstructionMalformed<Opcodes>( opcodes, instruction ) : disassembleAuthenticationInstruction<Opcodes>(opcodes, instruction); /** * Disassemble an array of `ParsedAuthenticationInstructions` (including * potentially malformed instructions) into its ASM representation. * * @param script - the array of instructions to disassemble */ export const disassembleParsedAuthenticationInstructions = <Opcodes = number>( opcodes: { readonly [opcode: number]: string }, instructions: readonly ParsedAuthenticationInstruction<Opcodes>[] ): string => instructions .map((instruction) => disassembleParsedAuthenticationInstruction<Opcodes>(opcodes, instruction) ) .join(' '); /** * Disassemble authentication bytecode into a lossless ASM representation. (All * push operations are represented with the same opcodes used in the bytecode, * even when non-minimally encoded.) * * @param opcodes - the set to use when determining the name of opcodes, e.g. `OpcodesBCH` * @param bytecode - the authentication bytecode to disassemble */ export const disassembleBytecode = <Opcode = number>( opcodes: { readonly [opcode: number]: string }, bytecode: Uint8Array ) => disassembleParsedAuthenticationInstructions( opcodes, parseBytecode<Opcode>(bytecode) ); /** * Disassemble BCH authentication bytecode into its ASM representation. * @param bytecode - the authentication bytecode to disassemble */ export const disassembleBytecodeBCH = (bytecode: Uint8Array) => disassembleParsedAuthenticationInstructions( OpcodesBCH, parseBytecode<OpcodesBCH>(bytecode) ); /** * Disassemble BTC authentication bytecode into its ASM representation. * @param bytecode - the authentication bytecode to disassemble */ export const disassembleBytecodeBTC = (bytecode: Uint8Array) => disassembleParsedAuthenticationInstructions( OpcodesBTC, parseBytecode<OpcodesBTC>(bytecode) ); /** * Create an object where each key is an opcode identifier and each value is * the bytecode value (`Uint8Array`) it represents. * @param opcodes - An opcode enum, e.g. `OpcodesBCH` */ export const generateBytecodeMap = (opcodes: Record<string, unknown>) => Object.entries(opcodes) .filter<[string, number]>( (entry): entry is [string, number] => typeof entry[1] === 'number' ) .reduce<{ [opcode: string]: Uint8Array; }>( (identifiers, pair) => ({ ...identifiers, [pair[0]]: Uint8Array.of(pair[1]), }), {} ); /** * Re-assemble a string of disassembled bytecode (see `disassembleBytecode`). * * @param opcodes - a mapping of opcodes to their respective Uint8Array * representation * @param disassembledBytecode - the disassembled bytecode to re-assemble */ export const assembleBytecode = < Opcodes extends number = OpcodesBCH, Errors = AuthenticationErrorBCH >( opcodes: { readonly [opcode: string]: Uint8Array }, disassembledBytecode: string ) => { const environment = { opcodes, scripts: { asm: disassembledBytecode }, }; return createCompilerCommonSynchronous< typeof environment, AuthenticationProgramStateCommon<Opcodes, Errors>, Opcodes, Errors >(environment).generateBytecode('asm', {}); }; /** * Re-assemble a string of disassembled BCH bytecode (see * `disassembleBytecodeBCH`). * * Note, this method performs automatic minimization of push instructions. * * @param disassembledBytecode - the disassembled BCH bytecode to re-assemble */ export const assembleBytecodeBCH = (disassembledBytecode: string) => assembleBytecode(generateBytecodeMap(OpcodesBCH), disassembledBytecode); /** * Re-assemble a string of disassembled BCH bytecode (see * `disassembleBytecodeBTC`). * * Note, this method performs automatic minimization of push instructions. * * @param disassembledBytecode - the disassembled BTC bytecode to re-assemble */ export const assembleBytecodeBTC = (disassembledBytecode: string) => assembleBytecode<OpcodesBTC>( generateBytecodeMap(OpcodesBTC), disassembledBytecode ); const getInstructionLengthBytes = <Opcodes>( instruction: AuthenticationInstructionPush<Opcodes> ) => { const opcode = (instruction.opcode as unknown) as number; const expectedLength = lengthBytesForPushOpcode(opcode); return expectedLength === uint8Bytes ? Uint8Array.of(instruction.data.length) : expectedLength === uint16Bytes ? numberToBinUint16LE(instruction.data.length) : numberToBinUint32LE(instruction.data.length); }; /** * Re-serialize a valid authentication instruction. * @param instruction - the instruction to serialize */ export const serializeAuthenticationInstruction = <Opcodes = number>( instruction: AuthenticationInstruction<Opcodes> ) => Uint8Array.from([ (instruction.opcode as unknown) as number, ...('data' in instruction ? [ ...(isPushData((instruction.opcode as unknown) as number) ? getInstructionLengthBytes(instruction) : []), ...instruction.data, ] : []), ]); /** * Re-serialize a malformed authentication instruction. * @param instruction - the malformed instruction to serialize */ export const serializeParsedAuthenticationInstructionMalformed = < Opcodes = number >( instruction: ParsedAuthenticationInstructionMalformed<Opcodes> ) => { const opcode = (instruction.opcode as unknown) as number; if (hasMalformedLength(instruction)) { return Uint8Array.from([opcode, ...instruction.length]); } if (isPushData(opcode)) { return Uint8Array.from([ opcode, ...(opcode === CommonPushOpcodes.OP_PUSHDATA_1 ? Uint8Array.of(instruction.expectedDataBytes) : opcode === CommonPushOpcodes.OP_PUSHDATA_2 ? numberToBinUint16LE(instruction.expectedDataBytes) : numberToBinUint32LE(instruction.expectedDataBytes)), ...instruction.data, ]); } return Uint8Array.from([opcode, ...instruction.data]); }; /** * Re-serialize a potentially-malformed authentication instruction. * @param instruction - the potentially-malformed instruction to serialize */ export const serializeParsedAuthenticationInstruction = <Opcodes = number>( instruction: ParsedAuthenticationInstruction<Opcodes> ): Uint8Array => authenticationInstructionIsMalformed(instruction) ? serializeParsedAuthenticationInstructionMalformed(instruction) : serializeAuthenticationInstruction(instruction); /** * Re-serialize an array of valid authentication instructions. * @param instructions - the array of valid instructions to serialize */ export const serializeAuthenticationInstructions = <Opcodes = number>( instructions: readonly AuthenticationInstruction<Opcodes>[] ) => flattenBinArray(instructions.map(serializeAuthenticationInstruction)); /** * Re-serialize an array of potentially-malformed authentication instructions. * @param instructions - the array of instructions to serialize */ export const serializeParsedAuthenticationInstructions = <Opcodes = number>( instructions: readonly ParsedAuthenticationInstruction<Opcodes>[] ) => flattenBinArray(instructions.map(serializeParsedAuthenticationInstruction));
the_stack
import { spawn } from 'child_process'; import { promises as fs } from 'fs'; import * as path from 'path'; import * as byline from 'byline'; import { rgPath } from '@vscode/ripgrep'; import * as Parser from 'tree-sitter'; import fetch from 'node-fetch'; const { typescript } = require('tree-sitter-typescript'); const product = require('../../product.json'); type NlsString = { value: string; nlsKey: string }; function isNlsString(value: string | NlsString | undefined): value is NlsString { return value ? typeof value !== 'string' : false; } function isStringArray(value: (string | NlsString)[]): value is string[] { return !value.some(s => isNlsString(s)); } function isNlsStringArray(value: (string | NlsString)[]): value is NlsString[] { return value.every(s => isNlsString(s)); } interface Category { readonly moduleName: string; readonly name: NlsString; } enum PolicyType { StringEnum } interface Policy { readonly category: Category; readonly minimumVersion: string; renderADMX(regKey: string): string[]; renderADMLStrings(translations?: LanguageTranslations): string[]; renderADMLPresentation(): string; } function renderADMLString(prefix: string, moduleName: string, nlsString: NlsString, translations?: LanguageTranslations): string { let value: string | undefined; if (translations) { const moduleTranslations = translations[moduleName]; if (moduleTranslations) { value = moduleTranslations[nlsString.nlsKey]; } } if (!value) { value = nlsString.value; } return `<string id="${prefix}_${nlsString.nlsKey}">${value}</string>`; } abstract class BasePolicy implements Policy { constructor( protected policyType: PolicyType, protected name: string, readonly category: Category, readonly minimumVersion: string, protected description: NlsString, protected moduleName: string, ) { } protected renderADMLString(nlsString: NlsString, translations?: LanguageTranslations): string { return renderADMLString(this.name, this.moduleName, nlsString, translations); } renderADMX(regKey: string) { return [ `<policy name="${this.name}" class="Both" displayName="$(string.${this.name})" explainText="$(string.${this.name}_${this.description.nlsKey})" key="Software\\Policies\\Microsoft\\${regKey}" presentation="$(presentation.${this.name})">`, ` <parentCategory ref="${this.category.name.nlsKey}" />`, ` <supportedOn ref="Supported_${this.minimumVersion.replace(/\./g, '_')}" />`, ` <elements>`, ...this.renderADMXElements(), ` </elements>`, `</policy>` ]; } protected abstract renderADMXElements(): string[]; renderADMLStrings(translations?: LanguageTranslations) { return [ `<string id="${this.name}">${this.name}</string>`, this.renderADMLString(this.description, translations) ]; } renderADMLPresentation(): string { return `<presentation id="${this.name}">${this.renderADMLPresentationContents()}</presentation>`; } protected abstract renderADMLPresentationContents(): string; } class BooleanPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): BooleanPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'boolean') { return undefined; } return new BooleanPolicy(name, category, minimumVersion, description, moduleName); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<boolean id="${this.name}" valueName="${this.name}">`, ` <trueValue><decimal value="1" /></trueValue><falseValue><decimal value="0" /></falseValue>`, `</boolean>` ]; } renderADMLPresentationContents() { return `<checkBox refId="${this.name}">${this.name}</checkBox>`; } } class IntPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): IntPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'number') { return undefined; } const defaultValue = getIntProperty(settingNode, 'default'); if (typeof defaultValue === 'undefined') { throw new Error(`Missing required 'default' property.`); } return new IntPolicy(name, category, minimumVersion, description, moduleName, defaultValue); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, protected readonly defaultValue: number, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<decimal id="${this.name}" valueName="${this.name}" />` // `<decimal id="Quarantine_PurgeItemsAfterDelay" valueName="PurgeItemsAfterDelay" minValue="0" maxValue="10000000" />` ]; } renderADMLPresentationContents() { return `<decimalTextBox refId="${this.name}" defaultValue="${this.defaultValue}">${this.name}</decimalTextBox>`; } } class StringPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): StringPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } return new StringPolicy(name, category, minimumVersion, description, moduleName); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [`<text id="${this.name}" valueName="${this.name}" required="true" />`]; } renderADMLPresentationContents() { return `<textBox refId="${this.name}"><label>${this.name}:</label></textBox>`; } } class StringEnumPolicy extends BasePolicy { static from( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, settingNode: Parser.SyntaxNode ): StringEnumPolicy | undefined { const type = getStringProperty(settingNode, 'type'); if (type !== 'string') { return undefined; } const enum_ = getStringArrayProperty(settingNode, 'enum'); if (!enum_) { return undefined; } if (!isStringArray(enum_)) { throw new Error(`Property 'enum' should not be localized.`); } const enumDescriptions = getStringArrayProperty(settingNode, 'enumDescriptions'); if (!enumDescriptions) { throw new Error(`Missing required 'enumDescriptions' property.`); } else if (!isNlsStringArray(enumDescriptions)) { throw new Error(`Property 'enumDescriptions' should be localized.`); } return new StringEnumPolicy(name, category, minimumVersion, description, moduleName, enum_, enumDescriptions); } private constructor( name: string, category: Category, minimumVersion: string, description: NlsString, moduleName: string, protected enum_: string[], protected enumDescriptions: NlsString[], ) { super(PolicyType.StringEnum, name, category, minimumVersion, description, moduleName); } protected renderADMXElements(): string[] { return [ `<enum id="${this.name}" valueName="${this.name}">`, ...this.enum_.map((value, index) => ` <item displayName="$(string.${this.name}_${this.enumDescriptions[index].nlsKey})"><value><string>${value}</string></value></item>`), `</enum>` ]; } renderADMLStrings(translations?: LanguageTranslations) { return [ ...super.renderADMLStrings(translations), ...this.enumDescriptions.map(e => this.renderADMLString(e, translations)) ]; } renderADMLPresentationContents() { return `<dropdownList refId="${this.name}" />`; } } interface QType<T> { Q: string; value(matches: Parser.QueryMatch[]): T | undefined; } const IntQ: QType<number> = { Q: `(number) @value`, value(matches: Parser.QueryMatch[]): number | undefined { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } return parseInt(value); } }; const StringQ: QType<string | NlsString> = { Q: `[ (string (string_fragment) @value) (call_expression function: (identifier) @localizeFn arguments: (arguments (string (string_fragment) @nlsKey) (string (string_fragment) @value)) (#eq? @localizeFn localize)) ]`, value(matches: Parser.QueryMatch[]): string | NlsString | undefined { const match = matches[0]; if (!match) { return undefined; } const value = match.captures.filter(c => c.name === 'value')[0]?.node.text; if (!value) { throw new Error(`Missing required 'value' property.`); } const nlsKey = match.captures.filter(c => c.name === 'nlsKey')[0]?.node.text; if (nlsKey) { return { value, nlsKey }; } else { return value; } } }; const StringArrayQ: QType<(string | NlsString)[]> = { Q: `(array ${StringQ.Q})`, value(matches: Parser.QueryMatch[]): (string | NlsString)[] | undefined { if (matches.length === 0) { return undefined; } return matches.map(match => { return StringQ.value([match]) as string | NlsString; }); } }; function getProperty<T>(qtype: QType<T>, node: Parser.SyntaxNode, key: string): T | undefined { const query = new Parser.Query( typescript, `( (pair key: [(property_identifier)(string)] @key value: ${qtype.Q} ) (#eq? @key ${key}) )` ); return qtype.value(query.matches(node)); } function getIntProperty(node: Parser.SyntaxNode, key: string): number | undefined { return getProperty(IntQ, node, key); } function getStringProperty(node: Parser.SyntaxNode, key: string): string | NlsString | undefined { return getProperty(StringQ, node, key); } function getStringArrayProperty(node: Parser.SyntaxNode, key: string): (string | NlsString)[] | undefined { return getProperty(StringArrayQ, node, key); } // TODO: add more policy types const PolicyTypes = [ BooleanPolicy, IntPolicy, StringEnumPolicy, StringPolicy, ]; function getPolicy( moduleName: string, configurationNode: Parser.SyntaxNode, settingNode: Parser.SyntaxNode, policyNode: Parser.SyntaxNode, categories: Map<string, Category> ): Policy { const name = getStringProperty(policyNode, 'name'); if (!name) { throw new Error(`Missing required 'name' property.`); } else if (isNlsString(name)) { throw new Error(`Property 'name' should be a literal string.`); } const categoryName = getStringProperty(configurationNode, 'title'); if (!categoryName) { throw new Error(`Missing required 'title' property.`); } else if (!isNlsString(categoryName)) { throw new Error(`Property 'title' should be localized.`); } const categoryKey = `${categoryName.nlsKey}:${categoryName.value}`; let category = categories.get(categoryKey); if (!category) { category = { moduleName, name: categoryName }; categories.set(categoryKey, category); } const minimumVersion = getStringProperty(policyNode, 'minimumVersion'); if (!minimumVersion) { throw new Error(`Missing required 'minimumVersion' property.`); } else if (isNlsString(minimumVersion)) { throw new Error(`Property 'minimumVersion' should be a literal string.`); } const description = getStringProperty(settingNode, 'description'); if (!description) { throw new Error(`Missing required 'description' property.`); } if (!isNlsString(description)) { throw new Error(`Property 'description' should be localized.`); } let result: Policy | undefined; for (const policyType of PolicyTypes) { if (result = policyType.from(name, category, minimumVersion, description, moduleName, settingNode)) { break; } } if (!result) { throw new Error(`Failed to parse policy '${name}'.`); } return result; } function getPolicies(moduleName: string, node: Parser.SyntaxNode): Policy[] { const query = new Parser.Query(typescript, ` ( (call_expression function: (member_expression property: (property_identifier) @registerConfigurationFn) (#eq? @registerConfigurationFn registerConfiguration) arguments: (arguments (object (pair key: [(property_identifier)(string)] @propertiesKey (#eq? @propertiesKey properties) value: (object (pair key: [(property_identifier)(string)] value: (object (pair key: [(property_identifier)(string)] @policyKey (#eq? @policyKey policy) value: (object) @policy )) @setting )) )) @configuration) ) ) `); const categories = new Map<string, Category>(); return query.matches(node).map(m => { const configurationNode = m.captures.filter(c => c.name === 'configuration')[0].node; const settingNode = m.captures.filter(c => c.name === 'setting')[0].node; const policyNode = m.captures.filter(c => c.name === 'policy')[0].node; return getPolicy(moduleName, configurationNode, settingNode, policyNode, categories); }); } async function getFiles(root: string): Promise<string[]> { return new Promise((c, e) => { const result: string[] = []; const rg = spawn(rgPath, ['-l', 'registerConfiguration\\(', '-g', 'src/**/*.ts', '-g', '!src/**/test/**', root]); const stream = byline(rg.stdout.setEncoding('utf8')); stream.on('data', path => result.push(path)); stream.on('error', err => e(err)); stream.on('end', () => c(result)); }); } function renderADMX(regKey: string, versions: string[], categories: Category[], policies: Policy[]) { versions = versions.map(v => v.replace(/\./g, '_')); return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitions revision="1.1" schemaVersion="1.0"> <policyNamespaces> <target prefix="${regKey}" namespace="Microsoft.Policies.${regKey}" /> </policyNamespaces> <resources minRequiredRevision="1.0" /> <supportedOn> <definitions> ${versions.map(v => `<definition name="Supported_${v}" displayName="$(string.Supported_${v})" />`).join(`\n `)} </definitions> </supportedOn> <categories> <category displayName="$(string.Application)" name="Application" /> ${categories.map(c => `<category displayName="$(string.Category_${c.name.nlsKey})" name="${c.name.nlsKey}"><parentCategory ref="Application" /></category>`).join(`\n `)} </categories> <policies> ${policies.map(p => p.renderADMX(regKey)).flat().join(`\n `)} </policies> </policyDefinitions> `; } function renderADML(appName: string, versions: string[], categories: Category[], policies: Policy[], translations?: LanguageTranslations) { return `<?xml version="1.0" encoding="utf-8"?> <policyDefinitionResources revision="1.0" schemaVersion="1.0"> <displayName /> <description /> <resources> <stringTable> <string id="Application">${appName}</string> ${versions.map(v => `<string id="Supported_${v.replace(/\./g, '_')}">${appName} &gt;= ${v}</string>`)} ${categories.map(c => renderADMLString('Category', c.moduleName, c.name, translations))} ${policies.map(p => p.renderADMLStrings(translations)).flat().join(`\n `)} </stringTable> <presentationTable> ${policies.map(p => p.renderADMLPresentation()).join(`\n `)} </presentationTable> </resources> </policyDefinitionResources> `; } function renderGP(policies: Policy[], translations: Translations) { const appName = product.nameLong; const regKey = product.win32RegValueName; const versions = [...new Set(policies.map(p => p.minimumVersion)).values()].sort(); const categories = [...new Set(policies.map(p => p.category))]; return { admx: renderADMX(regKey, versions, categories, policies), adml: [ { languageId: 'en-us', contents: renderADML(appName, versions, categories, policies) }, ...translations.map(({ languageId, languageTranslations }) => ({ languageId, contents: renderADML(appName, versions, categories, policies, languageTranslations) })) ] }; } const Languages = { 'fr': 'fr-fr', 'it': 'it-it', 'de': 'de-de', 'es': 'es-es', 'ru': 'ru-ru', 'zh-hans': 'zh-cn', 'zh-hant': 'zh-tw', 'ja': 'ja-jp', 'ko': 'ko-kr', 'cs': 'cs-cz', 'pt-br': 'pt-br', 'tr': 'tr-tr', 'pl': 'pl-pl', }; type LanguageTranslations = { [moduleName: string]: { [nlsKey: string]: string } }; type Translations = { languageId: string; languageTranslations: LanguageTranslations }[]; async function getLatestStableVersion(updateUrl: string) { const res = await fetch(`${updateUrl}/api/update/darwin/stable/latest`); const { name: version } = await res.json() as { name: string }; return version; } async function getNLS(resourceUrlTemplate: string, languageId: string, version: string) { const resource = { publisher: 'ms-ceintl', name: `vscode-language-pack-${languageId}`, version, path: 'extension/translations/main.i18n.json' }; const url = resourceUrlTemplate.replace(/\{([^}]+)\}/g, (_, key) => resource[key as keyof typeof resource]); const res = await fetch(url); const { contents: result } = await res.json() as { contents: LanguageTranslations }; return result; } async function parsePolicies(): Promise<Policy[]> { const parser = new Parser(); parser.setLanguage(typescript); const files = await getFiles(process.cwd()); const base = path.join(process.cwd(), 'src'); const policies = []; for (const file of files) { const moduleName = path.relative(base, file).replace(/\.ts$/i, '').replace(/\\/g, '/'); const contents = await fs.readFile(file, { encoding: 'utf8' }); const tree = parser.parse(contents); policies.push(...getPolicies(moduleName, tree.rootNode)); } return policies; } async function getTranslations(): Promise<Translations> { const updateUrl = product.updateUrl; if (!updateUrl) { console.warn(`Skipping policy localization: No 'updateUrl' found in 'product.json'.`); return []; } const resourceUrlTemplate = product.extensionsGallery?.resourceUrlTemplate; if (!resourceUrlTemplate) { console.warn(`Skipping policy localization: No 'resourceUrlTemplate' found in 'product.json'.`); return []; } const version = await getLatestStableVersion(updateUrl); const languageIds = Object.keys(Languages); return await Promise.all(languageIds.map( languageId => getNLS(resourceUrlTemplate, languageId, version) .then(languageTranslations => ({ languageId, languageTranslations })) )); } async function main() { const [policies, translations] = await Promise.all([parsePolicies(), getTranslations()]); const { admx, adml } = await renderGP(policies, translations); const root = '.build/policies/win32'; await fs.rm(root, { recursive: true, force: true }); await fs.mkdir(root, { recursive: true }); await fs.writeFile(path.join(root, `${product.win32RegValueName}.admx`), admx.replace(/\r?\n/g, '\n')); for (const { languageId, contents } of adml) { const languagePath = path.join(root, languageId === 'en-us' ? 'en-us' : Languages[languageId as keyof typeof Languages]); await fs.mkdir(languagePath, { recursive: true }); await fs.writeFile(path.join(languagePath, `${product.win32RegValueName}.adml`), contents.replace(/\r?\n/g, '\n')); } } if (require.main === module) { main().catch(err => { console.error(err); process.exit(1); }); }
the_stack
import * as parser from "jsonc-parser"; import * as vscode from "vscode"; import { DigitalTwinConstants } from "./digitalTwinConstants"; import { ClassNode, DigitalTwinGraph, PropertyNode, VersionNode } from "./digitalTwinGraph"; /** * Type of json node */ export enum JsonNodeType { Object = "object", Array = "array", String = "string", Number = "number", Boolean = "boolean", Property = "property" } /** * DigitalTwin model content */ export interface ModelContent { jsonNode: parser.Node; version: number; } /** * Property pair includes name and value */ export interface PropertyPair { name: parser.Node; value: parser.Node; } /** * Utility for IntelliSense */ export class IntelliSenseUtility { /** * init DigitalTwin graph * @param context extension context */ static async initGraph(context: vscode.ExtensionContext): Promise<void> { IntelliSenseUtility.graph = await DigitalTwinGraph.getInstance(context); } /** * check if IntelliSense has been enabled */ static enabled(): boolean { return IntelliSenseUtility.graph && IntelliSenseUtility.graph.initialized(); } /** * get entry node of DigitalTwin model */ static getEntryNode(): PropertyNode | undefined { return IntelliSenseUtility.graph.getPropertyNode(DigitalTwinConstants.ENTRY_NODE); } /** * get property node of DigitalTwin model by name * @param name property name */ static getPropertyNode(name: string): PropertyNode | undefined { return IntelliSenseUtility.graph.getPropertyNode(name); } /** * get class node of DigitalTwin model by name * @param name class name */ static getClasNode(name: string): ClassNode | undefined { return IntelliSenseUtility.graph.getClassNode(name); } /** * get class type of class node * @param classNode class node */ static getClassType(classNode: ClassNode): string { return classNode.label || classNode.id; } /** * get valid type names * @param propertyNode property node */ static getValidTypes(propertyNode: PropertyNode): string[] { if (!propertyNode.range) { return []; } return propertyNode.range.map(classNode => { if (classNode.label) { return classNode.label; } else { // get the name of XMLSchema const index: number = classNode.id.lastIndexOf(DigitalTwinConstants.SCHEMA_SEPARATOR); return index === -1 ? classNode.id : classNode.id.slice(index + 1); } }); } /** * parse the text, return DigitalTwin model content * @param text text */ static parseDigitalTwinModel(text: string): ModelContent | undefined { // skip checking errors in order to do IntelliSense at best effort const jsonNode: parser.Node = parser.parseTree(text); const contextPath: string[] = [DigitalTwinConstants.CONTEXT]; const contextNode: parser.Node | undefined = parser.findNodeAtLocation(jsonNode, contextPath); if (!contextNode) { return undefined; } const version = IntelliSenseUtility.getDigitalTwinVersion(contextNode); if (!version) { return undefined; } return { jsonNode, version }; } /** * get the version of DigitalTwin definition, * return 0 if it has no DigitalTwin context * @param node json node */ static getDigitalTwinVersion(node: parser.Node): number { if (!IntelliSenseUtility.graph) { return 0; } // @context accept both array and string if (node.type === JsonNodeType.String) { return IntelliSenseUtility.graph.getVersion(node.value as string); } else if (node.type === JsonNodeType.Array && node.children) { for (const child of node.children) { if (child.type !== JsonNodeType.String) { return 0; } const version: number = IntelliSenseUtility.graph.getVersion(child.value as string); if (version) { return version; } } } return 0; } /** * check if name is a reserved name * @param name name */ static isReservedName(name: string): boolean { return name.startsWith(DigitalTwinConstants.RESERVED); } /** * check if it is language node * @param classNode class node */ static isLanguageNode(classNode: ClassNode): boolean { return classNode.id === DigitalTwinConstants.LANGUAGE; } /** * check if class node is a object class, * which is not one of the following * 1. abstract class * 2. enum * 3. value schema * @param classNode class node */ static isObjectClass(classNode: ClassNode): boolean { if (classNode.isAbstract || classNode.enums || !classNode.label) { return false; } return true; } /** * parse json node, return property pair * @param node json node */ static parseProperty(node: parser.Node): PropertyPair | undefined { if (node.type !== JsonNodeType.Property || !node.children || node.children.length !== 2) { return undefined; } return { name: node.children[0], value: node.children[1] }; } /** * get the range of json node * @param document text document * @param node json node */ static getNodeRange(document: vscode.TextDocument, node: parser.Node): vscode.Range { return new vscode.Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length)); } /** * get enums by version * @param propertyNode property node * @param version target version */ static getEnums(propertyNode: PropertyNode, version: number): string[] { const enums: string[] = []; for (const classNode of IntelliSenseUtility.getRangeOfPropertyByVersion(propertyNode, version)) { // assume enum node can have different version, // but all enum value of one enum node share the same version if (classNode.enums) { enums.push(...classNode.enums); } else if (classNode.isAbstract) { for (const child of IntelliSenseUtility.getChildrenOfClassByVersion(classNode, version)) { if (child.enums) { enums.push(...child.enums); } } } } return enums; } /** * get object classes by version * @param propertyNode property node * @param version target version */ static getObjectClasses(propertyNode: PropertyNode, version: number): ClassNode[] { const classes: ClassNode[] = []; for (const classNode of IntelliSenseUtility.getRangeOfPropertyByVersion(propertyNode, version)) { if (IntelliSenseUtility.isObjectClass(classNode)) { classes.push(classNode); } else if (classNode.isAbstract) { for (const child of IntelliSenseUtility.getChildrenOfClassByVersion(classNode, version)) { if (!child.enums) { classes.push(child); } } } } return classes; } /** * get range of property node by version * @param propertyNode property node * @param version target version */ static getRangeOfPropertyByVersion(propertyNode: PropertyNode, version: number): ClassNode[] { if (!propertyNode.range) { return []; } return propertyNode.range.filter(node => IntelliSenseUtility.isAvailableByVersion(version, node.version)); } /** * get children of class node by version * @param classNode class node * @param version target version */ static getChildrenOfClassByVersion(classNode: ClassNode, version: number): ClassNode[] { if (!classNode.children) { return []; } return classNode.children.filter(node => IntelliSenseUtility.isAvailableByVersion(version, node.version)); } /** * get properties of class node by version * @param classNode class node * @param version target version */ static getPropertiesOfClassByVersion(classNode: ClassNode, version: number): ClassNode[] { if (!classNode.properties) { return []; } return classNode.properties.filter(node => IntelliSenseUtility.isAvailableByVersion(version, node.version)); } /** * check if node is available by version * @param version target version * @param versionNode version node */ static isAvailableByVersion(version: number, versionNode: VersionNode | undefined): boolean { if (!versionNode) { return true; } // assume definition is not allowed to be re-included if (versionNode.includeSince && versionNode.includeSince > version) { return false; } if (versionNode.excludeSince && versionNode.excludeSince <= version) { return false; } return true; } /** * resolve property name for schema and interfaceSchema * @param propertyPair property pair */ static resolvePropertyName(propertyPair: PropertyPair): string { let propertyName: string = propertyPair.name.value as string; if (propertyName !== DigitalTwinConstants.SCHEMA) { return propertyName; } const node: parser.Node = propertyPair.name; // get outer object node if (node.parent && node.parent.parent) { const outPropertyPair: PropertyPair | undefined = IntelliSenseUtility.getOuterPropertyPair(node.parent.parent); if (outPropertyPair) { const name: string = outPropertyPair.name.value as string; if (name === DigitalTwinConstants.IMPLEMENTS) { propertyName = DigitalTwinConstants.INTERFACE_SCHEMA; } } } return propertyName; } /** * get outer property pair from current node * @param node json node */ static getOuterPropertyPair(node: parser.Node): PropertyPair | undefined { if (node.type !== JsonNodeType.Object) { return undefined; } let outerProperty: parser.Node | undefined = node.parent; if (outerProperty && outerProperty.type === JsonNodeType.Array) { outerProperty = outerProperty.parent; } return outerProperty ? IntelliSenseUtility.parseProperty(outerProperty) : undefined; } /** * check if text document is a JSON file * @param document text document */ static isJsonFile(document: vscode.TextDocument): boolean { return document.languageId === DigitalTwinConstants.JSON_LANGUAGE_ID; } private static graph: DigitalTwinGraph; private constructor() {} }
the_stack
import { UploadPartCommandInput, CompletedPart, S3Client, UploadPartCommand, CompleteMultipartUploadCommand, Part, AbortMultipartUploadCommand, ListPartsCommand, CreateMultipartUploadCommand, PutObjectCommandInput, ListObjectsV2Command, } from '@aws-sdk/client-s3'; import * as events from 'events'; import axios, { Canceler, CancelTokenSource } from 'axios'; import { HttpHandlerOptions } from '@aws-sdk/types'; import { Logger } from '@aws-amplify/core'; import { UploadTask } from '../types/Provider'; import { byteLength, isFile } from '../common/StorageUtils'; import { AWSS3ProviderUploadErrorStrings } from '../common/StorageErrorStrings'; import { SET_CONTENT_LENGTH_HEADER, UPLOADS_STORAGE_KEY, } from '../common/StorageConstants'; import { StorageAccessLevel } from '..'; const logger = new Logger('AWSS3UploadTask'); export enum AWSS3UploadTaskState { INIT, IN_PROGRESS, PAUSED, CANCELLED, COMPLETED, } export enum TaskEvents { CANCEL = 'cancel', UPLOAD_COMPLETE = 'uploadComplete', UPLOAD_PROGRESS = 'uploadPartProgress', ERROR = 'error', } export interface AWSS3UploadTaskParams { s3Client: S3Client; file: Blob; storage: Storage; level: StorageAccessLevel; params: PutObjectCommandInput; prefixPromise: Promise<string>; emitter?: events.EventEmitter; } export interface InProgressRequest { uploadPartInput: UploadPartCommandInput; s3Request: Promise<any>; cancel: Canceler; } export interface UploadTaskCompleteEvent { key: string; } export interface UploadTaskProgressEvent { /** * bytes that has been sent to S3 so far */ loaded: number; /** * total bytes that needs to be sent to S3 */ total: number; } export interface FileMetadata { bucket: string; fileName: string; key: string; // Unix timestamp in ms lastTouched: number; uploadId: string; } // maximum number of parts per upload request according the S3 spec, // see: https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html const MAX_PARTS = 10000; // 5MB in bytes const PART_SIZE = 5 * 1024 * 1024; const DEFAULT_QUEUE_SIZE = 4; function comparePartNumber(a: CompletedPart, b: CompletedPart) { return a.PartNumber - b.PartNumber; } export class AWSS3UploadTask implements UploadTask { private readonly emitter: events.EventEmitter; private readonly file: Blob; private readonly partSize: number = PART_SIZE; private readonly queueSize = DEFAULT_QUEUE_SIZE; private readonly s3client: S3Client; private readonly storage: Storage; private readonly storageSync: Promise<any>; private readonly fileId: string; private readonly params: PutObjectCommandInput; private readonly prefixPromise: Promise<string>; private inProgress: InProgressRequest[] = []; private completedParts: CompletedPart[] = []; private queued: UploadPartCommandInput[] = []; private bytesUploaded: number = 0; private totalBytes: number = 0; private uploadId: string; public state: AWSS3UploadTaskState = AWSS3UploadTaskState.INIT; constructor({ s3Client, file, emitter, storage, params, level, prefixPromise, }: AWSS3UploadTaskParams) { this.prefixPromise = prefixPromise; this.s3client = s3Client; this.s3client.middlewareStack.remove(SET_CONTENT_LENGTH_HEADER); this.storage = storage; this.storageSync = Promise.resolve(); if (typeof this.storage['sync'] === 'function') { this.storageSync = this.storage['sync'](); } this.params = params; this.file = file; this.totalBytes = this.file.size; this.bytesUploaded = 0; this.emitter = emitter; this.queued = []; this.fileId = this._getFileId(level); this._validateParams(); // event emitter will re-throw an error if an event emits an error unless there's a listener, attaching a no-op // function to it unless user adds their own onError callback this.emitter.on(TaskEvents.ERROR, () => {}); } get percent() { return (this.bytesUploaded / this.totalBytes) * 100; } get isInProgress() { return this.state === AWSS3UploadTaskState.IN_PROGRESS; } private async _listSingleFile({ key, bucket, }: { key: string; bucket: string; }) { const listObjectRes = await this.s3client.send( new ListObjectsV2Command({ Bucket: bucket, Prefix: key, }) ); const { Contents = [] } = listObjectRes; const prefix = await this.prefixPromise; const obj = Contents.find(o => o.Key === `${prefix}${key}`); return obj; } private _getFileId(level: StorageAccessLevel): string { // We should check if it's a File first because File is also instance of a Blob if (isFile(this.file)) { return [ this.file.name, this.file.lastModified, this.file.size, this.file.type, this.params.Bucket, level, this.params.Key, ].join('-'); } else { return [ this.file.size, this.file.type, this.params.Bucket, level, this.params.Key, ].join('-'); } } private async _findCachedUploadParts(): Promise<{ parts: Part[]; uploadId: string; }> { const uploadRequests = await this._listCachedUploadTasks(); if ( Object.keys(uploadRequests).length === 0 || !Object.prototype.hasOwnProperty.call(uploadRequests, this.fileId) ) { return { parts: [], uploadId: null }; } const cachedUploadFileData = uploadRequests[this.fileId]; cachedUploadFileData.lastTouched = Date.now(); this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests)); const listPartsOutput = await this.s3client.send( new ListPartsCommand({ Bucket: this.params.Bucket, Key: this.params.Key, UploadId: cachedUploadFileData.uploadId, }) ); return { parts: listPartsOutput.Parts || [], uploadId: cachedUploadFileData.uploadId, }; } private _emitEvent<T = any>(event: string, payload: T) { this.emitter.emit(event, payload); } private _validateParams() { if (this.file.size / this.partSize > MAX_PARTS) { throw new Error( `Too many parts. Number of parts is ${this.file.size / this.partSize}, maximum is ${MAX_PARTS}.` ); } } private async _listCachedUploadTasks(): Promise< Record<string, FileMetadata> > { await this.storageSync; const tasks = this.storage.getItem(UPLOADS_STORAGE_KEY) || '{}'; return JSON.parse(tasks); } private async _cache(fileMetadata: FileMetadata): Promise<void> { const uploadRequests = await this._listCachedUploadTasks(); uploadRequests[this.fileId] = fileMetadata; this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests)); } private async _isCached(): Promise<boolean> { return Object.prototype.hasOwnProperty.call( await this._listCachedUploadTasks(), this.fileId ); } private async _removeFromCache(): Promise<void> { const uploadRequests = await this._listCachedUploadTasks(); delete uploadRequests[this.fileId]; this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests)); } private async _onPartUploadCompletion({ eTag, partNumber, chunk, }: { eTag: string; partNumber: number; chunk: UploadPartCommandInput['Body']; }) { this.completedParts.push({ ETag: eTag, PartNumber: partNumber, }); this.bytesUploaded += byteLength(chunk); this._emitEvent<UploadTaskProgressEvent>(TaskEvents.UPLOAD_PROGRESS, { loaded: this.bytesUploaded, total: this.totalBytes, }); // Remove the completed item from the inProgress array this.inProgress = this.inProgress.filter( job => job.uploadPartInput.PartNumber !== partNumber ); if (this.queued.length && this.state !== AWSS3UploadTaskState.PAUSED) this._startNextPart(); if (this._isDone()) this._completeUpload(); } private async _completeUpload() { try { await this.s3client.send( new CompleteMultipartUploadCommand({ Bucket: this.params.Bucket, Key: this.params.Key, UploadId: this.uploadId, MultipartUpload: { // Parts are not always completed in order, we need to manually sort them Parts: this.completedParts.sort(comparePartNumber), }, }) ); this._verifyFileSize(); this._emitEvent<UploadTaskCompleteEvent>(TaskEvents.UPLOAD_COMPLETE, { key: `${this.params.Bucket}/${this.params.Key}`, }); this._removeFromCache(); this.state = AWSS3UploadTaskState.COMPLETED; } catch (err) { logger.error('error completing upload', err); this._emitEvent(TaskEvents.ERROR, err); } } private async _makeUploadPartRequest( input: UploadPartCommandInput, cancelTokenSource: CancelTokenSource ) { try { const res = await this.s3client.send(new UploadPartCommand(input), { cancelTokenSource, } as HttpHandlerOptions); await this._onPartUploadCompletion({ eTag: res.ETag, partNumber: input.PartNumber, chunk: input.Body, }); } catch (err) { if (this.state === AWSS3UploadTaskState.PAUSED) { logger.log('upload paused'); } else if (this.state === AWSS3UploadTaskState.CANCELLED) { logger.log('upload aborted'); } else { logger.error('error starting next part of upload: ', err); } // axios' cancel will also throw an error, however we don't need to emit an event in that case as it's an // expected behavior if ( !axios.isCancel(err) && err.message !== AWSS3ProviderUploadErrorStrings.UPLOAD_PAUSED_MESSAGE ) { this._emitEvent(TaskEvents.ERROR, err); this.pause(); } } } private _startNextPart() { if (this.queued.length > 0 && this.state !== AWSS3UploadTaskState.PAUSED) { const cancelTokenSource = axios.CancelToken.source(); const nextPart = this.queued.shift(); this.inProgress.push({ uploadPartInput: nextPart, s3Request: this._makeUploadPartRequest(nextPart, cancelTokenSource), cancel: cancelTokenSource.cancel, }); } } /** * Verify on S3 side that the file size matches the one on the client side. * * @async * @throws throws an error if the file size does not match between local copy of the file and the file on s3. */ private async _verifyFileSize() { const obj = await this._listSingleFile({ key: this.params.Key, bucket: this.params.Bucket, }); const valid = Boolean(obj && obj.Size === this.file.size); if (!valid) { throw new Error( 'File size does not match between local file and file on s3' ); } return valid; } private _isDone() { return ( !this.queued.length && !this.inProgress.length && this.bytesUploaded === this.totalBytes ); } private _createParts() { const size = this.file.size; const parts: UploadPartCommandInput[] = []; for (let bodyStart = 0; bodyStart < size; ) { const bodyEnd = Math.min(bodyStart + this.partSize, size); parts.push({ Body: this.file.slice(bodyStart, bodyEnd), Key: this.params.Key, Bucket: this.params.Bucket, PartNumber: parts.length + 1, UploadId: this.uploadId, }); bodyStart += this.partSize; } return parts; } private _initCachedUploadParts(cachedParts: Part[]) { this.bytesUploaded += cachedParts.reduce((acc, part) => acc + part.Size, 0); // Find the set of part numbers that have already been uploaded const uploadedPartNumSet = new Set( cachedParts.map(part => part.PartNumber) ); this.queued = this.queued.filter( part => !uploadedPartNumSet.has(part.PartNumber) ); this.completedParts = cachedParts.map(part => ({ PartNumber: part.PartNumber, ETag: part.ETag, })); this._emitEvent<UploadTaskProgressEvent>(TaskEvents.UPLOAD_PROGRESS, { loaded: this.bytesUploaded, total: this.totalBytes, }); } private async _initMultipartUpload() { const res = await this.s3client.send( new CreateMultipartUploadCommand(this.params) ); this._cache({ uploadId: res.UploadId, lastTouched: Date.now(), bucket: this.params.Bucket, key: this.params.Key, fileName: this.file instanceof File ? this.file.name : '', }); return res.UploadId; } private async _initializeUploadTask() { this.state = AWSS3UploadTaskState.IN_PROGRESS; try { if (await this._isCached()) { const { parts, uploadId } = await this._findCachedUploadParts(); this.uploadId = uploadId; this.queued = this._createParts(); this._initCachedUploadParts(parts); this._startUpload(); } else { if (!this.uploadId) { const uploadId = await this._initMultipartUpload(); this.uploadId = uploadId; this.queued = this._createParts(); this._startUpload(); } } } catch (err) { if (!axios.isCancel(err)) { logger.error('Error initializing the upload task', err); } } } public resume(): void { if (this.state === AWSS3UploadTaskState.CANCELLED) { logger.warn('This task has already been cancelled'); } else if (this.state === AWSS3UploadTaskState.COMPLETED) { logger.warn('This task has already been completed'); } else if (this.state === AWSS3UploadTaskState.IN_PROGRESS) { logger.warn('Upload task already in progress'); // first time running resume, find any cached parts on s3 or start a new multipart upload request before // starting the upload } else if (!this.uploadId) { this._initializeUploadTask(); } else { this._startUpload(); } } private _startUpload() { this.state = AWSS3UploadTaskState.IN_PROGRESS; for (let i = 0; i < this.queueSize; i++) { this._startNextPart(); } } async _cancel(): Promise<boolean> { if (this.state === AWSS3UploadTaskState.CANCELLED) { logger.warn('This task has already been cancelled'); return false; } else if (this.state === AWSS3UploadTaskState.COMPLETED) { logger.warn('This task has already been completed'); return false; } else { this.pause(); this.queued = []; this.completedParts = []; this.bytesUploaded = 0; this.state = AWSS3UploadTaskState.CANCELLED; try { await this.s3client.send( new AbortMultipartUploadCommand({ Bucket: this.params.Bucket, Key: this.params.Key, UploadId: this.uploadId, }) ); await this._removeFromCache(); return true; } catch (err) { logger.error('Error cancelling upload task', err); return false; } } } /** * pause this particular upload task **/ public pause(): void { if (this.state === AWSS3UploadTaskState.CANCELLED) { logger.warn('This task has already been cancelled'); } else if (this.state === AWSS3UploadTaskState.COMPLETED) { logger.warn('This task has already been completed'); } else if (this.state === AWSS3UploadTaskState.PAUSED) { logger.warn('This task is already paused'); } this.state = AWSS3UploadTaskState.PAUSED; // Use axios cancel token to abort the part request immediately // Add the inProgress parts back to pending const removedInProgressReq = this.inProgress.splice( 0, this.inProgress.length ); removedInProgressReq.forEach(req => { req.cancel(AWSS3ProviderUploadErrorStrings.UPLOAD_PAUSED_MESSAGE); }); // Put all removed in progress parts back into the queue this.queued.unshift( ...removedInProgressReq.map(req => req.uploadPartInput) ); } }
the_stack
import { SpecPage } from '@stencil/core/testing'; import { flushTransitions, asyncForEach } from './unit-test-utils'; import { rgb } from 'd3-color'; import Utils from '@visa/visa-charts-utils'; const { visaColors, propDefaultValues, getAccessibleStrokes } = Utils; const DEFAULTHOVEROPACITY = propDefaultValues.hoverOpacity; const CUSTOMHOVEROPACITY = 0.5; const DEFAULTCLICKSTYLE = propDefaultValues.clickStyle; const DEFAULTSYMBOLCLICKSTYLE = propDefaultValues.symbolClickStyle; const CUSTOMCLICKSTYLE = { color: visaColors.categorical_light_purple, strokeWidth: 4 }; const DEFAULTHOVERSTYLE = propDefaultValues.hoverStyle; const DEFAULTSYMBOLHOVERSTYLE = propDefaultValues.symbolHoverStyle; const checkRGB = element => element.getAttribute('fill').substr(0, 3) === 'rgb' || element.style.getPropertyValue('fill').substr(0, 3) === 'rgb'; const checkURL = element => element.getAttribute('fill') ? element.getAttribute('fill').substr(0, 4) === 'url(' : false; // this is only needed for parsing the complex style object // no longer needed after flushTransition() was added // but a useful piece of code so leaving it commented for now // const getStyleObject = styleString => { // const styleObject = {}; // styleString // .replace(/[\n\r]+/g, '') // .replace(/\s{2,10}/g, '') // .split(';') // .forEach(style => (styleObject[style.split(':')[0]] = style.split(':')[1])); // return styleObject; // }; export const interaction_cursor_default_load = { prop: 'cursor', group: 'interaction', name: 'should render default(arrow) pointer on mark when cursor type is default', testProps: { cursor: 'default' }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDCURSOR = 'default'; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp !== 'cursor') { component[testProp] = testProps[testProp]; } }); } // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const marker = await page.doc.querySelector(testSelector); expect(marker).toEqualAttribute('cursor', EXPECTEDCURSOR); } }; export const interaction_cursor_pointer_load = { prop: 'cursor', group: 'interaction', name: 'should render link pointer on mark when cursor type is pointer on load', testProps: { cursor: 'pointer' }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDCURSOR = 'pointer'; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp !== 'cursor') { component[testProp] = testProps[testProp]; } }); } component.cursor = EXPECTEDCURSOR; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT const marker = await page.doc.querySelector(testSelector); expect(marker).toEqualAttribute('cursor', EXPECTEDCURSOR); } }; export const interaction_cursor_pointer_update = { prop: 'cursor', group: 'interaction', name: 'should render link pointer on mark when cursor type is pointer on update', testProps: { cursor: 'pointer' }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDCURSOR = 'pointer'; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp !== 'cursor') { component[testProp] = testProps[testProp]; } }); } // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); // ACT UPDATE component.cursor = EXPECTEDCURSOR; await page.waitForChanges(); // ASSERT const marker = await page.doc.querySelector(testSelector); expect(marker).toEqualAttribute('cursor', EXPECTEDCURSOR); } }; export const interaction_clickStyle_default_load = { prop: 'clickStyle', group: 'interaction', name: 'on click the selected mark should be default clickStyle and others should have hoverOpacity', testProps: {}, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let runJestTimers = false; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp !== 'clickHighlight') { component[testProp] = testProps[testProp]; } }); } component.clickHighlight = [component.data[0]]; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], 1 + customRadiusModifier[2], DEFAULTCLICKSTYLE.strokeWidth + 1 + customRadiusModifier[3], DEFAULTCLICKSTYLE.strokeWidth + 2 + customRadiusModifier[4] ]; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (!transitionEndAllSelector) { if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } } else { if (applyFlushTransitions) { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async (element, i) => { // since we have a timeout in the transitionEndAll we need to advance timers // if (i === elements.length - 1 && runJestTimers) jest.runOnlyPendingTimers(); flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const notSelectedMarkColor = checkURL(notSelectedMark) ? page.doc .querySelector( selectedMark .getAttribute('fill') .replace('url(', '') .replace(')', '') ) .querySelector('rect') .getAttribute('fill') : selectedMark.getAttribute('fill') === 'none' ? selectedMark.getAttribute('stroke') : selectedMark.getAttribute('fill'); const expectedStrokeColor = selectedMark.getAttribute('fill') === 'none' ? selectedMark.getAttribute('stroke') : getAccessibleStrokes(notSelectedMarkColor)[0]; const expectedScatterStrokeWidth = DEFAULTSYMBOLCLICKSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkFilterPrimaryColorFlood = selectedMarkFilter.querySelector('feFlood[result=primary-color]'); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); // STROKE COLOR TEST expect(selectedMarkFilterPrimaryColorFlood).toEqualAttribute('flood-color', expectedStrokeColor); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : DEFAULTCLICKSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', DEFAULTHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', DEFAULTHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', DEFAULTHOVEROPACITY); } } }; export const interaction_clickStyle_custom_load = { prop: 'clickStyle', group: 'interaction', name: 'on click (load) the selected mark should be custom clickStyle and others should have hoverOpacity', testProps: { hoverOpacity: CUSTOMHOVEROPACITY, clickStyle: CUSTOMCLICKSTYLE }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDCLICKSTYLE = testProps['clickStyle'] ? testProps['clickStyle'] : CUSTOMCLICKSTYLE; const EXPECTEDHOVEROPACITY = testProps['hoverOpacity'] ? testProps['hoverOpacity'] : CUSTOMHOVEROPACITY; let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; let runJestTimers = false; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp !== 'clickStyle' && testProp !== 'hoverOpacity') { component[testProp] = testProps[testProp]; } }); } component.clickHighlight = [component.data[0]]; component.clickStyle = EXPECTEDCLICKSTYLE; component.hoverOpacity = EXPECTEDHOVEROPACITY; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], EXPECTEDCLICKSTYLE.strokeWidth + customRadiusModifier[2], EXPECTEDCLICKSTYLE.strokeWidth + 1 + customRadiusModifier[3] ]; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (!transitionEndAllSelector) { if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } } else { if (applyFlushTransitions) { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const expectedStrokeColor = getAccessibleStrokes(EXPECTEDCLICKSTYLE.color)[0]; const expectedScatterStrokeWidth = EXPECTEDCLICKSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkFilterPrimaryColorFlood = selectedMarkFilter.querySelector('feFlood[result=primary-color]'); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); // STROKE COLOR TEST expect(selectedMarkFilterPrimaryColorFlood).toEqualAttribute('flood-color', expectedStrokeColor); // FILL COLOR TEST expect(selectedMark).toEqualAttribute('fill', EXPECTEDCLICKSTYLE.color); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : EXPECTEDCLICKSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); // FILL COLOR TEST if (!(selectedMark.getAttribute('fill') === 'none')) { expect(selectedMark).toEqualAttribute('fill', EXPECTEDCLICKSTYLE.color); } } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', EXPECTEDHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', EXPECTEDHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', EXPECTEDHOVEROPACITY); } } }; export const interaction_clickStyle_custom_update = { prop: 'clickStyle', group: 'interaction', name: 'on click (update) the selected mark should be custom clickStyle and others should have hoverOpacity', testProps: { hoverOpacity: CUSTOMHOVEROPACITY, clickStyle: CUSTOMCLICKSTYLE }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDCLICKSTYLE = testProps['clickStyle'] ? testProps['clickStyle'] : CUSTOMCLICKSTYLE; const EXPECTEDHOVEROPACITY = testProps['hoverOpacity'] ? testProps['hoverOpacity'] : CUSTOMHOVEROPACITY; let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let runJestTimers = false; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp !== 'clickStyle' && testProp !== 'hoverOpacity') { component[testProp] = testProps[testProp]; } }); } component.clickStyle = EXPECTEDCLICKSTYLE; component.hoverOpacity = EXPECTEDHOVEROPACITY; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], EXPECTEDCLICKSTYLE.strokeWidth + customRadiusModifier[2], EXPECTEDCLICKSTYLE.strokeWidth + 1 + customRadiusModifier[3] ]; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (applyFlushTransitions) { if (!transitionEndAllSelector) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } else { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // ACT UPDATE component.clickHighlight = [component.data[0]]; await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const expectedStrokeColor = getAccessibleStrokes(EXPECTEDCLICKSTYLE.color)[0]; const expectedScatterStrokeWidth = EXPECTEDCLICKSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkFilterPrimaryColorFlood = selectedMarkFilter.querySelector('feFlood[result=primary-color]'); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); // STROKE COLOR TEST expect(selectedMarkFilterPrimaryColorFlood).toEqualAttribute('flood-color', expectedStrokeColor); // FILL COLOR TEST expect(selectedMark).toEqualAttribute('fill', EXPECTEDCLICKSTYLE.color); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : EXPECTEDCLICKSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); // FILL COLOR TEST if (!(selectedMark.getAttribute('fill') === 'none')) { if (checkRGB(selectedMark)) { expect(selectedMark).toEqualAttribute('fill', rgb(EXPECTEDCLICKSTYLE.color)); } else { expect(selectedMark).toEqualAttribute('fill', EXPECTEDCLICKSTYLE.color); } } } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', EXPECTEDHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', EXPECTEDHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', EXPECTEDHOVEROPACITY); } } }; export const interaction_hoverStyle_default_load = { prop: 'hoverStyle', group: 'interaction', name: 'on hover the mark should be default hoverStyle and others should have hoverOpacity', testProps: { hoverOpacity: DEFAULTHOVEROPACITY, hoverStyle: DEFAULTHOVERSTYLE }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; let runJestTimers = false; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp !== 'hoverHighlight') { component[testProp] = testProps[testProp]; } }); } component.hoverHighlight = component.data[0]; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], 1 + customRadiusModifier[2], DEFAULTHOVERSTYLE.strokeWidth + 1 + customRadiusModifier[3], DEFAULTHOVERSTYLE.strokeWidth + 2 + customRadiusModifier[4] ]; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (!transitionEndAllSelector) { if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } } else { if (applyFlushTransitions) { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const notSelectedMarkColor = checkURL(notSelectedMark) && !DEFAULTHOVERSTYLE.color ? page.doc .querySelector( selectedMark .getAttribute('fill') .replace('url(', '') .replace(')', '') ) .querySelector('rect') .getAttribute('fill') : selectedMark.getAttribute('fill') === 'none' ? selectedMark.getAttribute('stroke') : selectedMark.getAttribute('fill'); const expectedStrokeColor = selectedMark.getAttribute('fill') === 'none' ? selectedMark.getAttribute('stroke') : getAccessibleStrokes(notSelectedMarkColor)[0]; const expectedScatterStrokeWidth = DEFAULTSYMBOLHOVERSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); const selectedMarkHighlightContainer = page.doc.querySelector('.vcl-accessibility-focus-highlight'); const selectedMarkHighlightClip = selectedMarkHighlightContainer.childNodes[0]; const selectedMarkHighlightElement = selectedMarkHighlightContainer.childNodes[1]; const isRGB = checkRGB(selectedMarkHighlightElement); const clipID = `url(#${selectedMarkHighlightClip['getAttribute']('id')})`; // SOURCE MARK TESTS expect(selectedMark).toHaveClass('vcl-accessibility-focus-hoverSource'); expect(selectedMark.getAttribute('filter').indexOf('-hover-')).toBeGreaterThan(0); // TEST THAT FOCUS HIGHLIGHT ELEMENTS ARE CREATED expect(selectedMarkHighlightContainer).toBeTruthy(); expect(selectedMarkHighlightClip).toBeTruthy(); expect(selectedMarkHighlightClip.nodeName).toEqual('clipPath'); expect(selectedMarkHighlightElement).toBeTruthy(); expect(selectedMarkHighlightElement.nodeName).not.toEqual('clipPath'); expect(selectedMarkHighlightElement).toEqualAttribute('clip-path', clipID); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke-width')).toEqual( `${2 + DEFAULTHOVERSTYLE.strokeWidth * 2}px` ); // STROKE COLOR TEST expect(selectedMarkHighlightElement['style'].getPropertyValue('fill')).toEqual('none'); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke')).toEqual( isRGB ? rgb(DEFAULTHOVERSTYLE.color || expectedStrokeColor) : DEFAULTHOVERSTYLE.color || expectedStrokeColor ); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : DEFAULTCLICKSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); // FILL COLOR TEST // DEFAULT HOVER STYLE DOES NOT HAVE FILL PROPERTY // expect(selectedMark).toEqualAttribute('fill', EXPECTEDCLICKSTYLE.color); } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', DEFAULTHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', DEFAULTHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', DEFAULTHOVEROPACITY); } } }; export const interaction_hoverStyle_custom_load = { prop: 'hoverStyle', group: 'interaction', name: 'on hover (load) the mark should be custom hoverStyle and others should have hoverOpacity', testProps: { hoverOpacity: CUSTOMHOVEROPACITY, hoverStyle: CUSTOMCLICKSTYLE }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDHOVERSTYLE = testProps['hoverStyle'] ? testProps['hoverStyle'] : CUSTOMCLICKSTYLE; const EXPECTEDHOVEROPACITY = testProps['hoverOpacity'] ? testProps['hoverOpacity'] : CUSTOMHOVEROPACITY; let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; let runJestTimers = false; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp !== 'hoverStyle' && testProp !== 'hoverOpacity') { component[testProp] = testProps[testProp]; } }); } component.hoverHighlight = component.data[0]; component.hoverStyle = EXPECTEDHOVERSTYLE; component.hoverOpacity = EXPECTEDHOVEROPACITY; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], EXPECTEDHOVERSTYLE.strokeWidth + customRadiusModifier[2], EXPECTEDHOVERSTYLE.strokeWidth + 1 + customRadiusModifier[3] ]; // ACT page.root.appendChild(component); await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (!transitionEndAllSelector) { if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } } else { if (applyFlushTransitions) { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const expectedStrokeColor = getAccessibleStrokes(EXPECTEDHOVERSTYLE.color)[0]; const expectedScatterStrokeWidth = EXPECTEDHOVERSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); const selectedMarkHighlightContainer = page.doc.querySelector('.vcl-accessibility-focus-highlight'); const selectedMarkHighlightClip = selectedMarkHighlightContainer.childNodes[0]; const selectedMarkHighlightElement = selectedMarkHighlightContainer.childNodes[1]; const isRGB = checkRGB(selectedMarkHighlightElement); const clipID = `url(#${selectedMarkHighlightClip['getAttribute']('id')})`; // SOURCE MARK TESTS expect(selectedMark).toHaveClass('vcl-accessibility-focus-hoverSource'); expect(selectedMark.getAttribute('filter').indexOf('-hover-')).toBeGreaterThan(0); // TEST THAT FOCUS HIGHLIGHT ELEMENTS ARE CREATED expect(selectedMarkHighlightContainer).toBeTruthy(); expect(selectedMarkHighlightClip).toBeTruthy(); expect(selectedMarkHighlightClip.nodeName).toEqual('clipPath'); expect(selectedMarkHighlightElement).toBeTruthy(); expect(selectedMarkHighlightElement.nodeName).not.toEqual('clipPath'); expect(selectedMarkHighlightElement).toEqualAttribute('clip-path', clipID); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke-width')).toEqual( `${EXPECTEDHOVERSTYLE.strokeWidth * 2}px` ); // STROKE COLOR TEST expect(selectedMarkHighlightElement['style'].getPropertyValue('fill')).toEqual('none'); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke')).toEqual( isRGB ? rgb(expectedStrokeColor) : expectedStrokeColor ); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : EXPECTEDHOVERSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); // FILL COLOR TEST if (!(selectedMark.getAttribute('fill') === 'none')) { expect(selectedMark).toEqualAttribute('fill', EXPECTEDHOVERSTYLE.color); } } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', EXPECTEDHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', EXPECTEDHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', EXPECTEDHOVEROPACITY); } } }; export const interaction_hoverStyle_custom_update = { prop: 'hoverStyle', group: 'interaction', name: 'on hover (update) the mark should be custom hoverStyle and others should have hoverOpacity', testProps: { hoverOpacity: CUSTOMHOVEROPACITY, hoverStyle: CUSTOMCLICKSTYLE }, testSelector: '[data-testid=mark]', negTestSelector: '[data-testid=mark]', testFunc: async ( component: any, page: SpecPage, testProps: object, testSelector: string, negTestSelector: string ) => { // ARRANGE const EXPECTEDHOVERSTYLE = testProps['hoverStyle'] ? testProps['hoverStyle'] : CUSTOMCLICKSTYLE; const EXPECTEDHOVEROPACITY = testProps['hoverOpacity'] ? testProps['hoverOpacity'] : CUSTOMHOVEROPACITY; let useFilter = true; let fillStrokeOpacity = false; let applyFlushTransitions = true; let customRadiusModifier = [0, 0, 0, 0, 0]; let transitionEndAllSelector; let runJestTimers = false; if (Object.keys(testProps).length) { Object.keys(testProps).forEach(testProp => { if (testProp === 'useFilter') { useFilter = testProps[testProp]; } else if (testProp === 'fillStrokeOpacity') { fillStrokeOpacity = testProps[testProp]; } else if (testProp === 'applyFlushTransitions') { applyFlushTransitions = testProps[testProp]; } else if (testProp === 'customRadiusModifier') { customRadiusModifier = testProps[testProp]; } else if (testProp === 'runJestTimers') { runJestTimers = testProps[testProp]; } else if (testProp === 'transitionEndAllSelector') { transitionEndAllSelector = testProps[testProp]; } else if (testProp !== 'hoverStyle' && testProp !== 'hoverOpacity') { component[testProp] = testProps[testProp]; } }); } component.hoverStyle = EXPECTEDHOVERSTYLE; component.hoverOpacity = EXPECTEDHOVEROPACITY; const expectedMorphRadius = [ 1 + customRadiusModifier[0], 0 + customRadiusModifier[1], EXPECTEDHOVERSTYLE.strokeWidth + customRadiusModifier[2], EXPECTEDHOVERSTYLE.strokeWidth + 1 + customRadiusModifier[3] ]; // ACT RENDER page.root.appendChild(component); await page.waitForChanges(); const selectedMark = page.doc.querySelector(testSelector); const notSelectedMark = page.doc.querySelector(negTestSelector); if (applyFlushTransitions) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } // ACT UPDATE component.hoverHighlight = component.data[0]; await page.waitForChanges(); // ASSERT // GET MARKS SELECTED AND NOT if (applyFlushTransitions) { if (!transitionEndAllSelector) { flushTransitions(selectedMark); flushTransitions(notSelectedMark); await page.waitForChanges(); } else { const elements = page.doc.querySelectorAll(transitionEndAllSelector); await asyncForEach(elements, async element => { flushTransitions(element); await page.waitForChanges(); }); if (runJestTimers) { // since we have a timeout in the transitionEndAll we need to advance timers jest.runOnlyPendingTimers(); await page.waitForChanges(); } } } // FIGURE OUT WHAT COLOR THEY ARE AND DETERMINE EXPECTED STROKE USING OUR UTIL const expectedStrokeColor = getAccessibleStrokes(EXPECTEDHOVERSTYLE.color)[0]; const expectedScatterStrokeWidth = EXPECTEDHOVERSTYLE.strokeWidth / component.dotRadius; // DETERMINE WHICH TYPE OF TEST WE ARE DOING (TEXTURE BASED FILTER OR NOT) if (useFilter) { // GET THE FILTER OF THE SELECTED MARK AND STORE KEY ATTRIBUTES INTO AN OBJECT FOR EASE OF TESTING const selectedMarkFilter = page.doc.querySelector( selectedMark .getAttribute('filter') .replace('url(', '') .replace(')', '') ); const selectedMarkMorphs = selectedMarkFilter.querySelectorAll('feMorphology'); const selectedMarkHighlightContainer = page.doc.querySelector('.vcl-accessibility-focus-highlight'); const selectedMarkHighlightClip = selectedMarkHighlightContainer.childNodes[0]; const selectedMarkHighlightElement = selectedMarkHighlightContainer.childNodes[1]; const isRGB = checkRGB(selectedMarkHighlightElement); const clipID = `url(#${selectedMarkHighlightClip['getAttribute']('id')})`; // SOURCE MARK TESTS expect(selectedMark).toHaveClass('vcl-accessibility-focus-hoverSource'); expect(selectedMark.getAttribute('filter').indexOf('-hover-')).toBeGreaterThan(0); // TEST THAT FOCUS HIGHLIGHT ELEMENTS ARE CREATED expect(selectedMarkHighlightContainer).toBeTruthy(); expect(selectedMarkHighlightClip).toBeTruthy(); expect(selectedMarkHighlightClip.nodeName).toEqual('clipPath'); expect(selectedMarkHighlightElement).toBeTruthy(); expect(selectedMarkHighlightElement.nodeName).not.toEqual('clipPath'); expect(selectedMarkHighlightElement).toEqualAttribute('clip-path', clipID); // STROKE WIDTH TESTS selectedMarkMorphs.forEach((morph, i) => { expect(morph).toEqualAttribute('radius', expectedMorphRadius[i]); }); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke-width')).toEqual( `${EXPECTEDHOVERSTYLE.strokeWidth * 2}px` ); // STROKE COLOR TEST expect(selectedMarkHighlightElement['style'].getPropertyValue('fill')).toEqual('none'); expect(selectedMarkHighlightElement['style'].getPropertyValue('stroke')).toEqual( isRGB ? rgb(expectedStrokeColor) : expectedStrokeColor ); } else { // STROKE WIDTH TESTS expect(selectedMark).toEqualAttribute( 'stroke-width', component.tagName.toLowerCase() === 'scatter-plot' ? expectedScatterStrokeWidth : EXPECTEDHOVERSTYLE.strokeWidth ); // STROKE COLOR TEST expect(selectedMark).toEqualAttribute('stroke', expectedStrokeColor); // FILL COLOR TEST if (!(selectedMark.getAttribute('fill') === 'none')) { if (checkRGB(selectedMark)) { expect(selectedMark).toEqualAttribute('fill', rgb(EXPECTEDHOVERSTYLE.color)); } else { expect(selectedMark).toEqualAttribute('fill', EXPECTEDHOVERSTYLE.color); } } } // HOVER OPACITY TEST if (fillStrokeOpacity) { expect(notSelectedMark).toEqualAttribute('fill-opacity', EXPECTEDHOVEROPACITY); expect(notSelectedMark).toEqualAttribute('stroke-opacity', EXPECTEDHOVEROPACITY); } else { expect(notSelectedMark).toEqualAttribute('opacity', EXPECTEDHOVEROPACITY); } } };
the_stack
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { TopicCreationService } from 'components/entity-creation-services/topic-creation.service'; import { SkillSummary } from 'domain/skill/skill-summary.model'; import { CreatorTopicSummary } from 'domain/topic/creator-topic-summary.model'; import { TopicsAndSkillsDashboardBackendApiService } from 'domain/topics_and_skills_dashboard/topics-and-skills-dashboard-backend-api.service'; import { TopicsAndSkillsDashboardFilter } from 'domain/topics_and_skills_dashboard/topics-and-skills-dashboard-filter.model'; import { CreateNewSkillModalService } from 'pages/topic-editor-page/services/create-new-skill-modal.service'; import { WindowDimensionsService } from 'services/contextual/window-dimensions.service'; import { FocusManagerService } from 'services/stateful/focus-manager.service'; import { MockTranslatePipe } from 'tests/unit-test-utils'; import { TopicsAndSkillsDashboardPageComponent } from './topics-and-skills-dashboard-page.component'; import { TopicsAndSkillsDashboardPageService } from './topics-and-skills-dashboard-page.service'; /** * @fileoverview Unit tests for the topics and skills dashboard component. */ describe('Topics and skills dashboard page component', () => { let fixture: ComponentFixture<TopicsAndSkillsDashboardPageComponent>; let componentInstance: TopicsAndSkillsDashboardPageComponent; let windowDimensionsService: WindowDimensionsService; let topicsAndSkillsDashboardBackendApiService: TopicsAndSkillsDashboardBackendApiService; let focusManagerService: FocusManagerService; let topicCreationService: TopicCreationService; let createNewSkillModalService: CreateNewSkillModalService; let topicsAndSkillsDashboardPageService: TopicsAndSkillsDashboardPageService; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], declarations: [ TopicsAndSkillsDashboardPageComponent, MockTranslatePipe ], providers: [ FocusManagerService, CreateNewSkillModalService, TopicCreationService, TopicsAndSkillsDashboardBackendApiService, TopicsAndSkillsDashboardPageService, WindowDimensionsService ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TopicsAndSkillsDashboardPageComponent); componentInstance = fixture.componentInstance; windowDimensionsService = TestBed.inject(WindowDimensionsService); topicsAndSkillsDashboardBackendApiService = TestBed.inject( TopicsAndSkillsDashboardBackendApiService); focusManagerService = TestBed.inject(FocusManagerService); topicCreationService = TestBed.inject(TopicCreationService); createNewSkillModalService = TestBed.inject(CreateNewSkillModalService); topicsAndSkillsDashboardPageService = TestBed.inject( TopicsAndSkillsDashboardPageService); }); it('should create', () => { expect(componentInstance).toBeDefined(); }); it('should initialize', fakeAsync(() => { spyOn(windowDimensionsService, 'isWindowNarrow').and.returnValue(false); spyOn(TopicsAndSkillsDashboardFilter, 'createDefault').and.returnValue( null); spyOn(componentInstance, '_initDashboard'); componentInstance.ngOnInit(); topicsAndSkillsDashboardBackendApiService .onTopicsAndSkillsDashboardReinitialized.emit(true); tick(); expect(componentInstance._initDashboard).toHaveBeenCalled(); })); it('should destroy', () => { spyOn(componentInstance.directiveSubscriptions, 'unsubscribe'); componentInstance.ngOnDestroy(); expect(componentInstance.directiveSubscriptions.unsubscribe) .toHaveBeenCalled(); }); it('should generate numbers till range', () => { expect(componentInstance.generateNumbersTillRange(4)).toEqual([0, 1, 2, 3]); }); it('should check whether next skill page is present', () => { for (let i = 0; i < 10; i++) { componentInstance.skillSummaries.push(new SkillSummary( '', '', '', 1, 2, 3, 4, 5)); } componentInstance.skillPageNumber = 0; componentInstance.itemsPerPage = 4; expect(componentInstance.isNextSkillPagePresent()).toBeTrue(); componentInstance.itemsPerPage = 11; expect(componentInstance.isNextSkillPagePresent()).toBeFalse(); }); it('should set topic tab as active tab', () => { componentInstance.filterObject = { reset: () => {} } as TopicsAndSkillsDashboardFilter; spyOn(componentInstance.filterObject, 'reset'); spyOn(componentInstance, 'goToPageNumber'); spyOn(focusManagerService, 'setFocus'); componentInstance.setActiveTab(componentInstance.TAB_NAME_TOPICS); expect(componentInstance.filterObject.reset).toHaveBeenCalled(); expect(componentInstance.goToPageNumber).toHaveBeenCalled(); expect(focusManagerService.setFocus).toHaveBeenCalledWith('createTopicBtn'); }); it('should set skills tab as active tab', () => { componentInstance.filterObject = { reset: () => {} } as TopicsAndSkillsDashboardFilter; spyOn(componentInstance.filterObject, 'reset'); spyOn(componentInstance, 'initSkillDashboard'); spyOn(focusManagerService, 'setFocus'); componentInstance.setActiveTab(componentInstance.TAB_NAME_SKILLS); expect(componentInstance.filterObject.reset).toHaveBeenCalled(); expect(componentInstance.initSkillDashboard).toHaveBeenCalled(); expect(focusManagerService.setFocus).toHaveBeenCalledWith('createSkillBtn'); }); it('should intialize skill dashboard', () => { spyOn(componentInstance, 'applyFilters'); componentInstance.initSkillDashboard(); expect(componentInstance.moreSkillsPresent).toBeTrue(); expect(componentInstance.firstTimeFetchingSkills).toBeTrue(); expect(componentInstance.applyFilters).toHaveBeenCalledWith(); }); it('should create new topic', () => { spyOn(topicCreationService, 'createNewTopic'); componentInstance.createTopic(); expect(topicCreationService.createNewTopic).toHaveBeenCalled(); }); it('should create skill', () => { spyOn(createNewSkillModalService, 'createNewSkill'); componentInstance.createSkill(); expect(createNewSkillModalService.createNewSkill).toHaveBeenCalled(); }); it('should jump tab to given page number', () => { componentInstance.activeTab = componentInstance.TAB_NAME_TOPICS; for (let i = 0; i < 20; i++) { componentInstance.topicSummaries.push( new CreatorTopicSummary( '', '', 2, 2, 2, 2, 2, '', '', 2, 2, 2, 2, true, true, '', '', '', '')); } componentInstance.pageNumber = 1; componentInstance.itemsPerPage = 4; componentInstance.goToPageNumber(2); expect(componentInstance.displayedTopicSummaries.length).toEqual(4); componentInstance.activeTab = componentInstance.TAB_NAME_SKILLS; for (let i = 0; i < 10; i++) { componentInstance.skillSummaries.push(new SkillSummary( '', '', '', 1, 2, 3, 4, 5)); } componentInstance.pageNumber = 1; componentInstance.itemsPerPage = 2; componentInstance.goToPageNumber(2); expect(componentInstance.displayedSkillSummaries.length).toEqual(2); }); it('should fetch skills', fakeAsync(() => { componentInstance.moreSkillsPresent = true; componentInstance.firstTimeFetchingSkills = true; const resp = { skillSummaries: [], nextCursor: '', more: true }; spyOn( topicsAndSkillsDashboardBackendApiService, 'fetchSkillsDashboardDataAsync').and.returnValue(Promise.resolve(resp)); spyOn(componentInstance, 'goToPageNumber'); componentInstance.fetchSkills(); tick(); expect(componentInstance.moreSkillsPresent).toEqual(resp.more); expect(componentInstance.nextCursor).toEqual(resp.nextCursor); expect(componentInstance.currentCount).toEqual( componentInstance.skillSummaries.length); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith(0); expect(componentInstance.firstTimeFetchingSkills).toBeFalse(); componentInstance.fetchSkills(); tick(); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith( componentInstance.pageNumber + 1); componentInstance.skillPageNumber = 1; componentInstance.itemsPerPage = 1; componentInstance.moreSkillsPresent = false; for (let i = 0; i < 5; i++) { componentInstance.skillSummaries.push(new SkillSummary( '', '', '', 1, 2, 3, 4, 5)); } componentInstance.fetchSkills(); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith( componentInstance.pageNumber + 1); })); it('should apply filters', () => { // Skills tab. componentInstance.activeTab = componentInstance.TAB_NAME_SKILLS; spyOn(componentInstance, 'fetchSkills'); componentInstance.applyFilters(); expect(componentInstance.fetchSkills).toHaveBeenCalled(); // Topics tab. componentInstance.activeTab = componentInstance.TAB_NAME_TOPICS; spyOn(topicsAndSkillsDashboardPageService, 'getFilteredTopics') .and.returnValue([]); spyOn(componentInstance, 'goToPageNumber'); componentInstance.applyFilters(); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith(0); }); it('should reset filters', () => { componentInstance.filterObject = { reset: () => {} } as TopicsAndSkillsDashboardFilter; spyOn(componentInstance, 'getUpperLimitValueForPagination'); spyOn(componentInstance.filterObject, 'reset'); spyOn(componentInstance, 'applyFilters'); componentInstance.resetFilters(); expect(componentInstance.getUpperLimitValueForPagination) .toHaveBeenCalled(); expect(componentInstance.filterObject.reset).toHaveBeenCalled(); expect(componentInstance.applyFilters).toHaveBeenCalled(); }); it('should toggle filter box', () => { componentInstance.filterBoxIsShown = false; componentInstance.toggleFilterBox(); expect(componentInstance.filterBoxIsShown).toBeTrue(); }); it('should get upper limit value for pagination', () => { componentInstance.pageNumber = 2; componentInstance.itemsPerPage = 2; componentInstance.currentCount = 0; expect(componentInstance.getUpperLimitValueForPagination()).toEqual(0); }); it('should get total count value for skills', () => { componentInstance.skillSummaries = [ new SkillSummary('', '', '', 2, 3, 4, 6, 7)]; componentInstance.itemsPerPage = 0; expect(componentInstance.getTotalCountValueForSkills()).toEqual('many'); componentInstance.itemsPerPage = 2; expect(componentInstance.getTotalCountValueForSkills()).toEqual(1); }); it('should refresh pagination', () => { spyOn(componentInstance, 'goToPageNumber'); componentInstance.refreshPagination(); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith(0); }); it('should initialize topics and skills dashboard', fakeAsync(() => { spyOn( topicsAndSkillsDashboardBackendApiService, 'fetchDashboardDataAsync') .and.returnValues(Promise.resolve({ allClassroomNames: ['math'], canDeleteSkill: true, canDeleteTopic: true, canCreateTopic: true, canCreateSkill: true, untriagedSkillSummaries: [], mergeableSkillSummaries: [], totalSkillCount: 5, topicSummaries: [new CreatorTopicSummary( '', '', 2, 2, 2, 2, 2, '', '', 1, 1, 2, 3, true, true, '', '', '', '')], categorizedSkillsDict: {} }), Promise.resolve({ allClassroomNames: ['math'], canDeleteSkill: true, canDeleteTopic: true, canCreateTopic: true, canCreateSkill: true, untriagedSkillSummaries: [ new SkillSummary('', '', '', 2, 3, 4, 5, 6) ], mergeableSkillSummaries: [], totalSkillCount: 5, topicSummaries: [], categorizedSkillsDict: {} })); spyOn(componentInstance, 'applyFilters'); spyOn(focusManagerService, 'setFocus'); spyOn(componentInstance, 'initSkillDashboard'); componentInstance._initDashboard(false); tick(); componentInstance._initDashboard(false); tick(); })); it('should navigate to skill page', () => { componentInstance.fetchSkillsDebounced = () => {}; spyOn(componentInstance, 'isNextSkillPagePresent').and.returnValues( true, false); spyOn(componentInstance, 'goToPageNumber'); spyOn(componentInstance, 'fetchSkillsDebounced'); componentInstance.navigateSkillPage(componentInstance.MOVE_TO_NEXT_PAGE); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith( componentInstance.pageNumber + 1); componentInstance.navigateSkillPage(componentInstance.MOVE_TO_NEXT_PAGE); expect(componentInstance.fetchSkillsDebounced).toHaveBeenCalled(); componentInstance.pageNumber = 5; componentInstance.navigateSkillPage('not next page'); expect(componentInstance.goToPageNumber).toHaveBeenCalled(); }); it('should change page by one', () => { componentInstance.currentCount = 20; componentInstance.itemsPerPage = 5; componentInstance.pageNumber = 2; spyOn(componentInstance, 'goToPageNumber'); componentInstance.changePageByOne(componentInstance.MOVE_TO_PREV_PAGE); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith( componentInstance.pageNumber - 1); componentInstance.pageNumber = 1; componentInstance.changePageByOne(componentInstance.MOVE_TO_NEXT_PAGE); expect(componentInstance.goToPageNumber).toHaveBeenCalledWith( componentInstance.pageNumber + 1); }); });
the_stack
import { Agile, StatePersistent, Storage, Persistent, EnhancedState, Storages, assignSharedStorageManager, createStorageManager, } from '../../../src'; import { LogMock } from '../../helper/logMock'; import waitForExpect from 'wait-for-expect'; describe('StatePersistent Tests', () => { let dummyAgile: Agile; let dummyState: EnhancedState; let storageManager: Storages; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); dummyState = new EnhancedState(dummyAgile, 'dummyValue'); // Register Storage Manager storageManager = createStorageManager(); assignSharedStorageManager(storageManager); jest.spyOn(StatePersistent.prototype, 'instantiatePersistent'); jest.spyOn(StatePersistent.prototype, 'initialLoading'); jest.clearAllMocks(); }); it('should create StatePersistent and should call initialLoading if Persistent is ready (default config)', () => { // Overwrite instantiatePersistent once to not call it jest .spyOn(StatePersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const statePersistent = new StatePersistent(dummyState); expect(statePersistent).toBeInstanceOf(StatePersistent); expect(statePersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(statePersistent.initialLoading).toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(statePersistent._key).toBe(StatePersistent.placeHolderKey); expect(statePersistent.ready).toBeTruthy(); expect(statePersistent.isPersisted).toBeFalsy(); expect(statePersistent.onLoad).toBeUndefined(); expect(statePersistent.storageKeys).toStrictEqual([]); expect(statePersistent.config).toStrictEqual({ defaultStorageKey: null, // gets set in 'instantiatePersistent' which is mocked }); }); it('should create StatePersistent and should call initialLoading if Persistent is ready (specific config)', () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(StatePersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const statePersistent = new StatePersistent(dummyState, { key: 'statePersistentKey', storageKeys: ['test1', 'test2'], defaultStorageKey: 'test2', }); expect(statePersistent).toBeInstanceOf(StatePersistent); expect(statePersistent.instantiatePersistent).toHaveBeenCalledWith({ key: 'statePersistentKey', storageKeys: ['test1', 'test2'], defaultStorageKey: 'test2', }); expect(statePersistent.initialLoading).toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(statePersistent._key).toBe(StatePersistent.placeHolderKey); expect(statePersistent.ready).toBeTruthy(); expect(statePersistent.isPersisted).toBeFalsy(); expect(statePersistent.onLoad).toBeUndefined(); expect(statePersistent.storageKeys).toStrictEqual([]); expect(statePersistent.config).toStrictEqual({ defaultStorageKey: null, // gets set in 'instantiatePersistent' which is mocked }); }); it("should create StatePersistent and shouldn't call initialLoading if Persistent isn't ready", () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(StatePersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = false; }); const statePersistent = new StatePersistent(dummyState); expect(statePersistent).toBeInstanceOf(StatePersistent); expect(statePersistent.state()).toBe(dummyState); expect(statePersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(statePersistent.initialLoading).not.toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(statePersistent._key).toBe(StatePersistent.placeHolderKey); expect(statePersistent.ready).toBeFalsy(); expect(statePersistent.isPersisted).toBeFalsy(); expect(statePersistent.onLoad).toBeUndefined(); expect(statePersistent.storageKeys).toStrictEqual([]); expect(statePersistent.config).toStrictEqual({ defaultStorageKey: null }); }); it("should create StatePersistent and shouldn't call initialLoading if Persistent is ready (config.loadValue = false)", () => { // Overwrite instantiatePersistent once to not call it and set ready property jest .spyOn(StatePersistent.prototype, 'instantiatePersistent') .mockImplementationOnce(function () { // @ts-ignore this.ready = true; }); const statePersistent = new StatePersistent(dummyState, { loadValue: false, }); expect(statePersistent).toBeInstanceOf(StatePersistent); expect(statePersistent.state()).toBe(dummyState); expect(statePersistent.instantiatePersistent).toHaveBeenCalledWith({ key: undefined, storageKeys: [], defaultStorageKey: null, }); expect(statePersistent.initialLoading).not.toHaveBeenCalled(); // Check if Persistent was called with correct parameters expect(statePersistent._key).toBe(StatePersistent.placeHolderKey); expect(statePersistent.ready).toBeTruthy(); expect(statePersistent.isPersisted).toBeFalsy(); expect(statePersistent.onLoad).toBeUndefined(); expect(statePersistent.storageKeys).toStrictEqual([]); expect(statePersistent.config).toStrictEqual({ defaultStorageKey: null }); }); describe('StatePersistent Function Tests', () => { let statePersistent: StatePersistent; beforeEach(() => { statePersistent = new StatePersistent(dummyState, { key: 'statePersistentKey', storageKeys: ['dummyStorage'], }); storageManager.register( new Storage({ key: 'dummyStorage', methods: { get: jest.fn(), remove: jest.fn(), set: jest.fn(), }, }) ); }); describe('initialLoading function tests', () => { beforeEach(() => { jest.spyOn(Persistent.prototype, 'initialLoading'); }); it('should initialLoad and set isPersisted in State to true', async () => { await statePersistent.initialLoading(); await waitForExpect(() => { expect(Persistent.prototype.initialLoading).toHaveBeenCalled(); expect(dummyState.isPersisted).toBeTruthy(); }); }); }); describe('loadPersistedValue function tests', () => { beforeEach(() => { dummyState.set = jest.fn(); statePersistent.setupSideEffects = jest.fn(); }); it( 'should load State value with Persistent key from the corresponding Storage ' + 'and apply it to the State if the loading was successful', async () => { statePersistent.ready = true; storageManager.get = jest.fn(() => Promise.resolve('dummyValue' as any) ); const response = await statePersistent.loadPersistedValue(); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( statePersistent._key, statePersistent.config.defaultStorageKey ); expect(dummyState.set).toHaveBeenCalledWith('dummyValue', { storage: false, overwrite: true, }); expect(statePersistent.setupSideEffects).toHaveBeenCalledWith( statePersistent._key ); } ); it( "should load State value with Persistent key from the corresponding Storage, migrate it with the 'onMigrate()' method " + 'and apply it to the State if the loading was successful', async () => { statePersistent.ready = true; storageManager.get = jest.fn(() => Promise.resolve('dummyValue' as any) ); statePersistent.onMigrate = jest.fn((value) => `migrated_${value}`); const response = await statePersistent.loadPersistedValue(); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( statePersistent._key, statePersistent.config.defaultStorageKey ); expect(dummyState.set).toHaveBeenCalledWith('migrated_dummyValue', { storage: false, overwrite: true, }); expect(statePersistent.onMigrate).toHaveBeenCalledWith('dummyValue'); expect(statePersistent.setupSideEffects).toHaveBeenCalledWith( statePersistent._key ); } ); it( "shouldn't load State value with Persistent key from the corresponding Storage " + "and apply it to the State if the loading wasn't successful", async () => { statePersistent.ready = true; storageManager.get = jest.fn(() => Promise.resolve(undefined as any)); const response = await statePersistent.loadPersistedValue(); expect(response).toBeFalsy(); expect(storageManager.get).toHaveBeenCalledWith( statePersistent._key, statePersistent.config.defaultStorageKey ); expect(dummyState.set).not.toHaveBeenCalled(); expect(statePersistent.setupSideEffects).not.toHaveBeenCalled(); } ); it( 'should load State value with specified key from the corresponding Storage ' + 'and apply it to the State if the loading was successful', async () => { statePersistent.ready = true; storageManager.get = jest.fn(() => Promise.resolve('dummyValue' as any) ); const response = await statePersistent.loadPersistedValue('coolKey'); expect(response).toBeTruthy(); expect(storageManager.get).toHaveBeenCalledWith( 'coolKey', statePersistent.config.defaultStorageKey ); expect(dummyState.set).toHaveBeenCalledWith('dummyValue', { storage: false, overwrite: true, }); expect(statePersistent.setupSideEffects).toHaveBeenCalledWith( 'coolKey' ); } ); it( "shouldn't load State value from the corresponding Storage " + "if Persistent isn't ready yet", async () => { statePersistent.ready = false; storageManager.get = jest.fn(() => Promise.resolve(undefined as any)); const response = await statePersistent.loadPersistedValue(); expect(response).toBeFalsy(); expect(storageManager.get).not.toHaveBeenCalled(); expect(dummyState.set).not.toHaveBeenCalled(); expect(statePersistent.setupSideEffects).not.toHaveBeenCalled(); } ); }); describe('persistValue function tests', () => { beforeEach(() => { statePersistent.setupSideEffects = jest.fn(); statePersistent.rebuildStorageSideEffect = jest.fn(); statePersistent.isPersisted = false; }); it('should persist State value with Persistent key', async () => { statePersistent.ready = true; const response = await statePersistent.persistValue(); expect(response).toBeTruthy(); expect(statePersistent.setupSideEffects).toHaveBeenCalledWith( statePersistent._key ); expect(statePersistent.rebuildStorageSideEffect).toHaveBeenCalledWith( dummyState, statePersistent._key ); expect(statePersistent.isPersisted).toBeTruthy(); }); it('should persist State value with specified key', async () => { statePersistent.ready = true; const response = await statePersistent.persistValue('coolKey'); expect(response).toBeTruthy(); expect(statePersistent.setupSideEffects).toHaveBeenCalledWith( 'coolKey' ); expect(statePersistent.rebuildStorageSideEffect).toHaveBeenCalledWith( dummyState, 'coolKey' ); expect(statePersistent.isPersisted).toBeTruthy(); }); it("shouldn't persist State if Persistent isn't ready yet", async () => { statePersistent.ready = false; const response = await statePersistent.persistValue(); expect(response).toBeFalsy(); expect(statePersistent.setupSideEffects).not.toHaveBeenCalled(); expect(statePersistent.rebuildStorageSideEffect).not.toHaveBeenCalled(); expect(statePersistent.isPersisted).toBeFalsy(); }); }); describe('setupSideEffects function tests', () => { beforeEach(() => { jest.spyOn(dummyState, 'addSideEffect'); }); it( 'should add side effects for keeping the State value in sync ' + 'with the Storage value to the State', () => { statePersistent.setupSideEffects(); expect( dummyState.addSideEffect ).toHaveBeenCalledWith( StatePersistent.storeValueSideEffectKey, expect.any(Function), { weight: 0 } ); } ); describe("test added sideEffect called 'StatePersistent.storeValueSideEffectKey'", () => { beforeEach(() => { statePersistent.rebuildStorageSideEffect = jest.fn(); }); it("should call 'rebuildStorageSideEffect' (persistentKey)", async () => { await statePersistent.setupSideEffects(); dummyState.sideEffects[ StatePersistent.storeValueSideEffectKey ].callback(dummyState, { dummy: 'property', }); expect(statePersistent.rebuildStorageSideEffect).toHaveBeenCalledWith( dummyState, statePersistent._key, { dummy: 'property', } ); }); it("should call 'rebuildStorageSideEffect' (specified key)", async () => { await statePersistent.setupSideEffects('dummyKey'); dummyState.sideEffects[ StatePersistent.storeValueSideEffectKey ].callback(dummyState, { dummy: 'property', }); expect(statePersistent.rebuildStorageSideEffect).toHaveBeenCalledWith( dummyState, 'dummyKey', { dummy: 'property', } ); }); }); }); describe('removePersistedValue function tests', () => { beforeEach(() => { dummyState.removeSideEffect = jest.fn(); storageManager.remove = jest.fn(); statePersistent.isPersisted = true; }); it('should remove persisted State value from the corresponding Storage with Persistent key', async () => { statePersistent.ready = true; const response = await statePersistent.removePersistedValue(); expect(response).toBeTruthy(); expect(dummyState.removeSideEffect).toHaveBeenCalledWith( StatePersistent.storeValueSideEffectKey ); expect(storageManager.remove).toHaveBeenCalledWith( statePersistent._key, statePersistent.storageKeys ); expect(statePersistent.isPersisted).toBeFalsy(); }); it('should remove persisted State from the corresponding Storage with specified key', async () => { statePersistent.ready = true; const response = await statePersistent.removePersistedValue('coolKey'); expect(response).toBeTruthy(); expect(dummyState.removeSideEffect).toHaveBeenCalledWith( StatePersistent.storeValueSideEffectKey ); expect(storageManager.remove).toHaveBeenCalledWith( 'coolKey', statePersistent.storageKeys ); expect(statePersistent.isPersisted).toBeFalsy(); }); it("shouldn't remove State from the corresponding Storage if Persistent isn't ready yet", async () => { statePersistent.ready = false; const response = await statePersistent.removePersistedValue('coolKey'); expect(response).toBeFalsy(); expect(dummyState.removeSideEffect).not.toHaveBeenCalled(); expect(storageManager.remove).not.toHaveBeenCalled(); expect(statePersistent.isPersisted).toBeTruthy(); }); }); describe('formatKey function tests', () => { it('should return key of the State if no valid key was specified', () => { dummyState._key = 'coolKey'; const response = statePersistent.formatKey(undefined); expect(response).toBe('coolKey'); }); it('should return specified key', () => { dummyState._key = 'coolKey'; const response = statePersistent.formatKey('awesomeKey'); expect(response).toBe('awesomeKey'); }); it('should return and apply specified key to State if State had no own valid key before', () => { dummyState._key = undefined; const response = statePersistent.formatKey('awesomeKey'); expect(response).toBe('awesomeKey'); expect(dummyState._key).toBe('awesomeKey'); }); it('should return undefined if no valid key was specified and State has no valid key either', () => { dummyState._key = undefined; const response = statePersistent.formatKey(undefined); expect(response).toBeUndefined(); }); }); describe('rebuildStorageSideEffect function tests', () => { beforeEach(() => { storageManager.set = jest.fn(); }); it('should store current State value in the corresponding Storage (default config)', () => { statePersistent.rebuildStorageSideEffect(dummyState, 'coolKey'); expect(storageManager.set).toHaveBeenCalledWith( 'coolKey', dummyState.getPersistableValue(), statePersistent.storageKeys ); }); it( 'should store current State value in the corresponding Storage ' + "and format it with the 'onSave()' method (default config)", () => { statePersistent.onSave = jest.fn((value) => `save_${value}`); statePersistent.rebuildStorageSideEffect(dummyState, 'coolKey'); expect(storageManager.set).toHaveBeenCalledWith( 'coolKey', `save_${dummyState.getPersistableValue()}`, statePersistent.storageKeys ); expect(statePersistent.onSave).toHaveBeenCalledWith( dummyState.getPersistableValue() ); } ); it("shouldn't store State value in the corresponding Storage (config.storage = false)", () => { statePersistent.rebuildStorageSideEffect(dummyState, 'coolKey', { storage: false, }); expect(storageManager.set).not.toHaveBeenCalled(); }); }); }); });
the_stack
import {Oas20Document} from "../models/2.0/document.model"; import {Oas20Info} from "../models/2.0/info.model"; import {Oas20Contact} from "../models/2.0/contact.model"; import {Oas20License} from "../models/2.0/license.model"; import {OasExtensibleNode} from "../models/enode.model"; import {Oas20Tag} from "../models/2.0/tag.model"; import {Oas20ExternalDocumentation} from "../models/2.0/external-documentation.model"; import {Oas20SecurityRequirement} from "../models/2.0/security-requirement.model"; import {Oas20SecurityDefinitions} from "../models/2.0/security-definitions.model"; import {Oas20SecurityScheme} from "../models/2.0/security-scheme.model"; import {Oas20Scopes} from "../models/2.0/scopes.model"; import {Oas20PathItem} from "../models/2.0/path-item.model"; import {Oas20Paths} from "../models/2.0/paths.model"; import {Oas20Operation} from "../models/2.0/operation.model"; import {Oas20Parameter, Oas20ParameterBase, Oas20ParameterDefinition} from "../models/2.0/parameter.model"; import { Oas20AdditionalPropertiesSchema, Oas20AllOfSchema, Oas20ItemsSchema, Oas20PropertySchema, Oas20Schema, Oas20SchemaDefinition } from "../models/2.0/schema.model"; import {Oas20Items} from "../models/2.0/items.model"; import {Oas20Responses} from "../models/2.0/responses.model"; import {Oas20Response, Oas20ResponseBase, Oas20ResponseDefinition} from "../models/2.0/response.model"; import {Oas20Headers} from "../models/2.0/headers.model"; import {Oas20Example} from "../models/2.0/example.model"; import {Oas20Header} from "../models/2.0/header.model"; import {Oas20XML} from "../models/2.0/xml.model"; import {Oas20Definitions} from "../models/2.0/definitions.model"; import {Oas20ParametersDefinitions} from "../models/2.0/parameters-definitions.model"; import {Oas20ResponsesDefinitions} from "../models/2.0/responses-definitions.model"; import {IOas20NodeVisitor, IOas30NodeVisitor} from "../visitors/visitor.iface"; import {OasExtension} from "../models/extension.model"; import {OasInfo} from "../models/common/info.model"; import {OasContact} from "../models/common/contact.model"; import {OasLicense} from "../models/common/license.model"; import {Oas30Info} from "../models/3.0/info.model"; import {Oas30Document} from "../models/3.0/document.model"; import {Oas30LinkServer, Oas30Server} from "../models/3.0/server.model"; import {Oas30ServerVariable} from "../models/3.0/server-variable.model"; import {OasExternalDocumentation} from "../models/common/external-documentation.model"; import {Oas30SecurityRequirement} from "../models/3.0/security-requirement.model"; import {Oas30ExternalDocumentation} from "../models/3.0/external-documentation.model"; import {OasTag} from "../models/common/tag.model"; import {Oas30Tag} from "../models/3.0/tag.model"; import {OasXML} from "../models/common/xml.model"; import {OasSecurityRequirement} from "../models/common/security-requirement.model"; import {OasOperation} from "../models/common/operation.model"; import {OasParameterBase} from "../models/common/parameter.model"; import {OasResponses} from "../models/common/responses.model"; import {OasResponse} from "../models/common/response.model"; import {OasSchema} from "../models/common/schema.model"; import {OasPaths} from "../models/common/paths.model"; import {OasPathItem} from "../models/common/path-item.model"; import {Oas30Paths} from "../models/3.0/paths.model"; import {Oas30CallbackPathItem, Oas30PathItem} from "../models/3.0/path-item.model"; import {Oas30Operation} from "../models/3.0/operation.model"; import {Oas30Parameter, Oas30ParameterBase, Oas30ParameterDefinition} from "../models/3.0/parameter.model"; import { Oas30AdditionalPropertiesSchema, Oas30AllOfSchema, Oas30AnyOfSchema, Oas30ItemsSchema, Oas30NotSchema, Oas30OneOfSchema, Oas30PropertySchema, Oas30Schema, Oas30SchemaDefinition } from "../models/3.0/schema.model"; import {Oas30Response, Oas30ResponseBase, Oas30ResponseDefinition} from "../models/3.0/response.model"; import {Oas30Header, Oas30HeaderDefinition} from "../models/3.0/header.model"; import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../models/3.0/request-body.model"; import {Oas30MediaType} from "../models/3.0/media-type.model"; import {Oas30Encoding} from "../models/3.0/encoding.model"; import {Oas30Example, Oas30ExampleDefinition} from "../models/3.0/example.model"; import {Oas30Link, Oas30LinkDefinition} from "../models/3.0/link.model"; import {Oas30LinkParameterExpression} from "../models/3.0/link-parameter-expression.model"; import {Oas30Callback, Oas30CallbackDefinition} from "../models/3.0/callback.model"; import {OasDocument} from "../models/document.model"; import {Oas30Components} from "../models/3.0/components.model"; import {Oas30SecurityScheme} from "../models/3.0/security-scheme.model"; import {OasSecurityScheme} from "../models/common/security-scheme.model"; import {Oas30OAuthFlows} from "../models/3.0/oauth-flows.model"; import { Oas30AuthorizationCodeOAuthFlow, Oas30ClientCredentialsOAuthFlow, Oas30ImplicitOAuthFlow, Oas30OAuthFlow, Oas30PasswordOAuthFlow } from "../models/3.0/oauth-flow.model"; import {Oas30Contact} from "../models/3.0/contact.model"; import {Oas30License} from "../models/3.0/license.model"; import {Oas30Responses} from "../models/3.0/responses.model"; import {Oas30XML} from "../models/3.0/xml.model"; import {Oas30LinkRequestBodyExpression} from "../models/3.0/link-request-body-expression.model"; import {Oas30Discriminator} from "../models/3.0/discriminator.model"; import {OasNode, OasValidationProblem} from "../models/node.model"; /** * This class reads a javascript object and turns it into a OAS model. */ export abstract class OasJS2ModelReader { /** * Consumes and returns a property found in an entity js object. The property is read and * then deleted. * @param entity * @param property */ protected consume(entity: any, property: string): any { let rval: any = entity[property]; delete entity[property]; return rval; } /** * Returns true if the given thing is defined. * @param thing * @return {boolean} */ protected isDefined(thing: any): boolean { if (typeof thing === "undefined" || thing === null) { return false; } else { return true; } } /** * Reads an OAS Document object from the given javascript data. * @param document * @param documentModel * @param readExtras */ public readDocument(document: any, documentModel: OasDocument, readExtras: boolean = true): void { let info: any = this.consume(document, "info"); let paths: any = this.consume(document, "paths"); let security: any[] = this.consume(document, "security"); let tags: any = this.consume(document, "tags"); let externalDocs: any = this.consume(document, "externalDocs"); if (this.isDefined(info)) { let infoModel: OasInfo = documentModel.createInfo(); this.readInfo(info, infoModel); documentModel.info = infoModel; } if (this.isDefined(paths)) { let pathsModel: OasPaths = documentModel.createPaths(); this.readPaths(paths, pathsModel); documentModel.paths = pathsModel; } if (this.isDefined(security)) { let securityModels: OasSecurityRequirement[] = []; for (let sec of security) { let secModel: OasSecurityRequirement = documentModel.createSecurityRequirement(); this.readSecurityRequirement(sec, secModel); securityModels.push(secModel); } documentModel.security = securityModels; } if (this.isDefined(tags)) { let tagModels: OasTag[] = []; for (let tag of tags) { let tagModel: OasTag = documentModel.createTag(); this.readTag(tag, tagModel); tagModels.push(tagModel); } documentModel.tags = tagModels; } if (this.isDefined(externalDocs)) { let externalDocsModel: OasExternalDocumentation = documentModel.createExternalDocumentation(); this.readExternalDocumentation(externalDocs, externalDocsModel); documentModel.externalDocs = externalDocsModel; } this.readExtensions(document, documentModel); if (readExtras) { this.readExtraProperties(document, documentModel); } } /** * Reads a OAS Info object from the given javascript data. * @param info * @param infoModel */ public readInfo(info: any, infoModel: OasInfo, readExtras: boolean = true): void { let title: string = this.consume(info, "title"); let description: string = this.consume(info, "description"); let termsOfService: string = this.consume(info, "termsOfService"); let contact: any = this.consume(info, "contact"); let license: any = this.consume(info, "license"); let version: string = this.consume(info, "version"); if (this.isDefined(title)) { infoModel.title = title; } if (this.isDefined(description)) { infoModel.description = description; } if (this.isDefined(termsOfService)) { infoModel.termsOfService = termsOfService; } if (this.isDefined(contact)) { let contactModel: OasContact = infoModel.createContact(); this.readContact(contact, contactModel); infoModel.contact = contactModel; } if (this.isDefined(license)) { let licenseModel: OasLicense = infoModel.createLicense(); this.readLicense(license, licenseModel); infoModel.license = licenseModel; } if (this.isDefined(version)) { infoModel.version = version; } this.readExtensions(info, infoModel); if (readExtras) { this.readExtraProperties(info, infoModel); } } /** * Reads a OAS Contact object from the given javascript data. * @param contact * @param contactModel */ public readContact(contact: any, contactModel: OasContact, readExtras: boolean = true): void { let name: string = this.consume(contact, "name"); let url: string = this.consume(contact, "url"); let email: string = this.consume(contact, "email"); if (this.isDefined(name)) { contactModel.name = name; } if (this.isDefined(url)) { contactModel.url = url; } if (this.isDefined(email)) { contactModel.email = email; } this.readExtensions(contact, contactModel); if (readExtras) { this.readExtraProperties(contact, contactModel); } } /** * Reads a OAS License object from the given javascript data. * @param license * @param licenseModel */ public readLicense(license: any, licenseModel: OasLicense, readExtras: boolean = true): void { let name: string = this.consume(license, "name"); let url: string = this.consume(license, "url"); if (this.isDefined(name)) { licenseModel.name = name; } if (this.isDefined(url)) { licenseModel.url = url; } this.readExtensions(license, licenseModel); if (readExtras) { this.readExtraProperties(license, licenseModel); } } /** * Reads an OAS Paths object from the given JS data. * @param paths * @param pathsModel */ public readPaths(paths: any, pathsModel: OasPaths, readExtras: boolean = true): void { for (let path in paths) { if (path.indexOf("x-") === 0) { continue; } let pathItem: any = this.consume(paths, path); let pathItemModel: OasPathItem = pathsModel.createPathItem(path); this.readPathItem(pathItem, pathItemModel); pathsModel.addPathItem(path, pathItemModel); } this.readExtensions(paths, pathsModel); if (readExtras) { this.readExtraProperties(paths, pathsModel); } } /** * Reads an OAS PathItem object from the given JS data. * @param pathItem * @param pathItemModel */ public readPathItem(pathItem: any, pathItemModel: OasPathItem, readExtras: boolean = true): void { let $ref: string = this.consume(pathItem, "$ref"); let get: any = this.consume(pathItem, "get"); let put: any = this.consume(pathItem, "put"); let post: any = this.consume(pathItem, "post"); let delete_: any = this.consume(pathItem, "delete"); let options: any = this.consume(pathItem, "options"); let head: any = this.consume(pathItem, "head"); let patch: any = this.consume(pathItem, "patch"); let parameters: any[] = this.consume(pathItem, "parameters"); if (this.isDefined($ref)) { pathItemModel.$ref = $ref; } if (this.isDefined(get)) { let opModel: OasOperation = pathItemModel.createOperation("get"); this.readOperation(get, opModel); pathItemModel.get = opModel; } if (this.isDefined(put)) { let opModel: OasOperation = pathItemModel.createOperation("put"); this.readOperation(put, opModel); pathItemModel.put = opModel; } if (this.isDefined(post)) { let opModel: OasOperation = pathItemModel.createOperation("post"); this.readOperation(post, opModel); pathItemModel.post = opModel; } if (this.isDefined(delete_)) { let opModel: OasOperation = pathItemModel.createOperation("delete"); this.readOperation(delete_, opModel); pathItemModel.delete = opModel; } if (this.isDefined(options)) { let opModel: OasOperation = pathItemModel.createOperation("options"); this.readOperation(options, opModel); pathItemModel.options = opModel; } if (this.isDefined(head)) { let opModel: OasOperation = pathItemModel.createOperation("head"); this.readOperation(head, opModel); pathItemModel.head = opModel; } if (this.isDefined(patch)) { let opModel: OasOperation = pathItemModel.createOperation("patch"); this.readOperation(patch, opModel); pathItemModel.patch = opModel; } if (this.isDefined(parameters)) { for (let parameter of parameters) { let paramModel: OasParameterBase = pathItemModel.createParameter(); this.readParameter(parameter, paramModel); pathItemModel.addParameter(paramModel); } } this.readExtensions(pathItem, pathItemModel); if (readExtras) { this.readExtraProperties(pathItem, pathItemModel); } } /** * Reads an OAS Operation object from the given JS data. * @param operation * @param operationModel */ public readOperation(operation: any, operationModel: OasOperation, readExtras: boolean = true): void { let tags: string[] = this.consume(operation, "tags"); let summary: string = this.consume(operation, "summary"); let description: string = this.consume(operation, "description"); let externalDocs: any = this.consume(operation, "externalDocs"); let operationId: string = this.consume(operation, "operationId"); let parameters: any[] = this.consume(operation, "parameters"); let responses: any = this.consume(operation, "responses"); let deprecated: boolean = this.consume(operation, "deprecated"); let security: any[] = this.consume(operation, "security"); if (this.isDefined(tags)) { operationModel.tags = tags; } if (this.isDefined(summary)) { operationModel.summary = summary; } if (this.isDefined(description)) { operationModel.description = description; } if (this.isDefined(externalDocs)) { let externalDocsModel: Oas20ExternalDocumentation = operationModel.createExternalDocumentation(); this.readExternalDocumentation(externalDocs, externalDocsModel); operationModel.externalDocs = externalDocsModel; } if (this.isDefined(operationId)) { operationModel.operationId = operationId; } if (this.isDefined(parameters)) { for (let parameter of parameters) { let paramModel: OasParameterBase = operationModel.createParameter(); this.readParameter(parameter, paramModel); operationModel.addParameter(paramModel); } } if (this.isDefined(responses)) { let responsesModel: OasResponses = operationModel.createResponses(); this.readResponses(responses, responsesModel); operationModel.responses = responsesModel; } if (this.isDefined(deprecated)) { operationModel.deprecated = deprecated; } if (this.isDefined(security)) { for (let securityRequirement of security) { let securityRequirementModel: Oas20SecurityRequirement = operationModel.createSecurityRequirement(); this.readSecurityRequirement(securityRequirement, securityRequirementModel); operationModel.addSecurityRequirement(securityRequirementModel); } } this.readExtensions(operation, operationModel); if (readExtras) { this.readExtraProperties(operation, operationModel); } } /** * Reads an OAS Parameter object from the given JS data. * @param parameter * @param paramModel */ public abstract readParameter(parameter: any, paramModel: OasParameterBase): void; /** * Reads an OAS Responses object from the given JS data. * @param responses * @param responsesModel */ public readResponses(responses: any, responsesModel: OasResponses, readExtras: boolean = true): void { let default_: any = responses["default"]; if (this.isDefined(default_)) { let defaultModel: OasResponse = responsesModel.createResponse(); this.readResponse(default_, defaultModel); responsesModel.default = defaultModel; } for (let statusCode in responses) { if (statusCode.indexOf("x-") === 0) { continue; } if (statusCode === "default") { continue; } let response: any = responses[statusCode]; let responseModel: OasResponse = responsesModel.createResponse(statusCode); this.readResponse(response, responseModel); responsesModel.addResponse(statusCode, responseModel); } if (readExtras) { this.readExtensions(responses, responsesModel); } } /** * Reads an OAS Response from the given JS data. * @param response * @param responseModel */ public abstract readResponse(response: any, responseModel: OasResponse): void; /** * Reads an OAS Schema object from the given JS data. * @param schema * @param schemaModel */ public readSchema(schema: any, schemaModel: OasSchema, readExtras: boolean = true): void { let $ref: string = this.consume(schema, "$ref"); let format: string = this.consume(schema, "format"); let title: string = this.consume(schema, "title"); let description: string = this.consume(schema, "description"); let default_: any = this.consume(schema, "default"); let multipleOf: number = this.consume(schema, "multipleOf"); let maximum: number = this.consume(schema, "maximum"); let exclusiveMaximum: boolean = this.consume(schema, "exclusiveMaximum"); let minimum: number = this.consume(schema, "minimum"); let exclusiveMinimum: boolean = this.consume(schema, "exclusiveMinimum"); let maxLength: number = this.consume(schema, "maxLength"); // Require: integer let minLength: number = this.consume(schema, "minLength"); // Require: integer let pattern: string = this.consume(schema, "pattern"); let maxItems: number = this.consume(schema, "maxItems"); // Require: integer let minItems: number = this.consume(schema, "minItems"); // Require: integer let uniqueItems: boolean = this.consume(schema, "uniqueItems"); let maxProperties: number = this.consume(schema, "maxProperties"); let minProperties: number = this.consume(schema, "minProperties"); let required: string[] = this.consume(schema, "required"); let enum_: any[] = this.consume(schema, "enum"); let type: string = this.consume(schema, "type"); let items: any[] = this.consume(schema, "items"); let allOf: any[] = this.consume(schema, "allOf"); let properties: any = this.consume(schema, "properties"); let additionalProperties: boolean | Oas20Schema = this.consume(schema, "additionalProperties"); let readOnly: boolean = this.consume(schema, "readOnly"); let xml: Oas20XML = this.consume(schema, "xml"); let externalDocs: any = this.consume(schema, "externalDocs"); let example: any = this.consume(schema, "example"); if (this.isDefined($ref)) { schemaModel.$ref = $ref; } if (this.isDefined(format)) { schemaModel.format = format; } if (this.isDefined(title)) { schemaModel.title = title; } if (this.isDefined(description)) { schemaModel.description = description; } if (this.isDefined(default_)) { schemaModel.default = default_; } if (this.isDefined(multipleOf)) { schemaModel.multipleOf = multipleOf; } if (this.isDefined(maximum)) { schemaModel.maximum = maximum; } if (this.isDefined(exclusiveMaximum)) { schemaModel.exclusiveMaximum = exclusiveMaximum; } if (this.isDefined(minimum)) { schemaModel.minimum = minimum; } if (this.isDefined(exclusiveMinimum)) { schemaModel.exclusiveMinimum = exclusiveMinimum; } if (this.isDefined(maxLength)) { schemaModel.maxLength = maxLength; } if (this.isDefined(minLength)) { schemaModel.minLength = minLength; } if (this.isDefined(pattern)) { schemaModel.pattern = pattern; } if (this.isDefined(maxItems)) { schemaModel.maxItems = maxItems; } if (this.isDefined(minItems)) { schemaModel.minItems = minItems; } if (this.isDefined(uniqueItems)) { schemaModel.uniqueItems = uniqueItems; } if (this.isDefined(maxProperties)) { schemaModel.maxProperties = maxProperties; } if (this.isDefined(minProperties)) { schemaModel.minProperties = minProperties; } if (this.isDefined(required)) { schemaModel.required = required; } if (this.isDefined(enum_)) { schemaModel.enum = enum_; } if (this.isDefined(type)) { schemaModel.type = type; } if (this.isDefined(items)) { if (Array.isArray(items)) { schemaModel.items = items.map( item => { let itemsSchemaModel: OasSchema = schemaModel.createItemsSchema(); this.readSchema(item, itemsSchemaModel); return itemsSchemaModel; }); } else { let itemsSchemaModel: OasSchema = schemaModel.createItemsSchema(); this.readSchema(items, itemsSchemaModel); schemaModel.items = itemsSchemaModel; } } if (this.isDefined(allOf)) { let schemaModels: OasSchema[] = []; for (let allOfSchema of allOf) { let allOfSchemaModel: OasSchema = schemaModel.createAllOfSchema(); this.readSchema(allOfSchema, allOfSchemaModel); schemaModels.push(allOfSchemaModel); } schemaModel.allOf = schemaModels; } if (this.isDefined(properties)) { for (let propertyName in properties) { let propertySchema: any = properties[propertyName]; let propertySchemaModel: OasSchema = schemaModel.createPropertySchema(propertyName); this.readSchema(propertySchema, propertySchemaModel); schemaModel.addProperty(propertyName, propertySchemaModel); } } if (this.isDefined(additionalProperties)) { if (typeof additionalProperties === "boolean") { schemaModel.additionalProperties = <boolean>additionalProperties; } else { let additionalPropertiesModel: OasSchema = schemaModel.createAdditionalPropertiesSchema(); this.readSchema(additionalProperties, additionalPropertiesModel); schemaModel.additionalProperties = additionalPropertiesModel; } } if (this.isDefined(readOnly)) { schemaModel.readOnly = readOnly; } if (this.isDefined(xml)) { let xmlModel: Oas20XML = schemaModel.createXML(); this.readXML(xml, xmlModel); schemaModel.xml = xmlModel; } if (this.isDefined(externalDocs)) { let externalDocsModel: Oas20ExternalDocumentation = schemaModel.createExternalDocumentation(); this.readExternalDocumentation(externalDocs, externalDocsModel); schemaModel.externalDocs = externalDocsModel; } if (this.isDefined(example)) { schemaModel.example = example; } this.readExtensions(schema, schemaModel); if (readExtras) { this.readExtraProperties(schema, schemaModel); } } /** * Reads an OAS XML object from the given JS data. * @param xml * @param xmlModel */ public readXML(xml: any, xmlModel: OasXML, readExtras: boolean = true): void { let name: string = this.consume(xml, "name"); let namespace: string = this.consume(xml, "namespace"); let prefix: string = this.consume(xml, "prefix"); let attribute: boolean = this.consume(xml, "attribute"); let wrapped: boolean = this.consume(xml, "wrapped"); if (this.isDefined(name)) { xmlModel.name = name; } if (this.isDefined(namespace)) { xmlModel.namespace = namespace; } if (this.isDefined(prefix)) { xmlModel.prefix = prefix; } if (this.isDefined(attribute)) { xmlModel.attribute = attribute; } if (this.isDefined(wrapped)) { xmlModel.wrapped = wrapped; } this.readExtensions(xml, xmlModel); if (readExtras) { this.readExtraProperties(xml, xmlModel); } } /** * Reads an OAS 2.0 Security Schema object from the given javascript data. * @param scheme * @param schemeModel */ public readSecurityScheme(scheme: any, schemeModel: OasSecurityScheme, readExtras: boolean = true): void { let type: string = this.consume(scheme, "type"); let description: string = this.consume(scheme, "description"); let name: string = this.consume(scheme, "name"); let in_: string = this.consume(scheme, "in"); if (this.isDefined(type)) { schemeModel.type = type; } if (this.isDefined(description)) { schemeModel.description = description; } if (this.isDefined(name)) { schemeModel.name = name; } if (this.isDefined(in_)) { schemeModel.in = in_; } this.readExtensions(scheme, schemeModel); if (readExtras) { this.readExtraProperties(scheme, schemeModel); } } /** * Reads an OAS Security Requirement object from the given javascript data. * @param sec * @param secModel */ public readSecurityRequirement(sec: any, secModel: OasSecurityRequirement): void { for (let name in sec) { secModel.addSecurityRequirementItem(name, sec[name]); } } /** * Reads a OAS Tag object from the given javascript data. * @param tag * @param tagModel */ public readTag(tag: any, tagModel: OasTag, readExtras: boolean = true): void { let name: string = this.consume(tag, "name"); let description: string = this.consume(tag, "description"); let externalDocs: any = this.consume(tag, "externalDocs"); if (this.isDefined(name)) { tagModel.name = name; } if (this.isDefined(description)) { tagModel.description = description; } if (this.isDefined(externalDocs)) { let externalDocsModel: OasExternalDocumentation = tagModel.createExternalDocumentation(); this.readExternalDocumentation(externalDocs, externalDocsModel); tagModel.externalDocs = externalDocsModel; } this.readExtensions(tag, tagModel); if (readExtras) { this.readExtraProperties(tag, tagModel); } } /** * Reads an OAS External Documentation object from the given javascript data. * @param externalDocs * @param externalDocsModel */ public readExternalDocumentation(externalDocs: any, externalDocsModel: OasExternalDocumentation, readExtras: boolean = true): void { let description: string = this.consume(externalDocs, "description"); let url: any = this.consume(externalDocs, "url"); if (this.isDefined(description)) { externalDocsModel.description = description; } if (this.isDefined(url)) { externalDocsModel.url = url; } this.readExtensions(externalDocs, externalDocsModel); if (readExtras) { this.readExtraProperties(externalDocs, externalDocsModel); } } /** * Reads all of the extension nodes. An extension node is characterized by a property * that begins with "x-". * @param jsData * @param model */ public readExtensions(jsData:any, model: OasExtensibleNode): void { let keys: string[] = Object.keys(jsData); keys.forEach( key => { if (key.indexOf("x-") === 0) { let val: any = this.consume(jsData, key); model.addExtension(key, val); } }); } /** * Reads all remaining properties. Anything left is an "extra" (or unexpected) property. * @param jsData * @param model */ public readExtraProperties(jsData: any, model: OasNode): void { for (let key in jsData) { let val: any = jsData[key]; console.info(`WARN: found unexpected property "${ key }".`); model.addExtraProperty(key, val); } } } /** * This class reads a javascript object and turns it into a OAS 2.0 model. It is obviously * assumed that the javascript data actually does represent an OAS 2.0 document. */ export class Oas20JS2ModelReader extends OasJS2ModelReader { /** * Reads the given javascript data and returns an OAS 2.0 document. Throws an error if * the root 'swagger' property is not found or if its value is not "2.0". * @param jsData */ public read(jsData: any): Oas20Document { let docModel: Oas20Document = new Oas20Document(); this.readDocument(jsData, docModel); return docModel; } /** * Reads an OAS 2.0 Document object from the given javascript data. * @param document * @param documentModel */ public readDocument(document: any, documentModel: Oas20Document): void { let swagger: string = this.consume(document, "swagger"); if (swagger != "2.0") { throw Error("Unsupported specification version: " + swagger); } super.readDocument(document, documentModel, false); let host: string = this.consume(document, "host"); let basePath: string = this.consume(document, "basePath"); let schemes: string[] = this.consume(document, "schemes"); let consumes: string[] = this.consume(document, "consumes"); let produces: string[] = this.consume(document, "produces"); let definitions: any = this.consume(document, "definitions"); let parameters: any = this.consume(document, "parameters"); let responses: any = this.consume(document, "responses"); let securityDefinitions: any[] = this.consume(document, "securityDefinitions"); if (this.isDefined(host)) { documentModel.host = host; } if (this.isDefined(basePath)) { documentModel.basePath = basePath; } if (this.isDefined(schemes)) { documentModel.schemes = schemes; } if (this.isDefined(consumes)) { documentModel.consumes = consumes; } if (this.isDefined(produces)) { documentModel.produces = produces; } if (this.isDefined(definitions)) { let definitionsModel: Oas20Definitions = documentModel.createDefinitions(); this.readDefinitions(definitions, definitionsModel); documentModel.definitions = definitionsModel; } if (this.isDefined(parameters)) { let parametersDefinitionsModel: Oas20ParametersDefinitions = documentModel.createParametersDefinitions(); this.readParametersDefinitions(parameters, parametersDefinitionsModel); documentModel.parameters = parametersDefinitionsModel; } if (this.isDefined(responses)) { let responsesDefinitionsModel: Oas20ResponsesDefinitions = documentModel.createResponsesDefinitions(); this.readResponsesDefinitions(responses, responsesDefinitionsModel); documentModel.responses = responsesDefinitionsModel; } if (this.isDefined(securityDefinitions)) { let securityDefinitionsModel: Oas20SecurityDefinitions = documentModel.createSecurityDefinitions(); this.readSecurityDefinitions(securityDefinitions, securityDefinitionsModel); documentModel.securityDefinitions = securityDefinitionsModel; } this.readExtraProperties(document, documentModel); } /** * Reads an OAS 2.0 Schema object from the given javascript data. * @param schema * @param schemaModel */ public readSchema(schema: any, schemaModel: Oas20Schema): void { super.readSchema(schema, schemaModel, false); let discriminator: string = this.consume(schema, "discriminator"); if (this.isDefined(discriminator)) { schemaModel.discriminator = discriminator; } this.readExtraProperties(schema, schemaModel); } /** * Reads an OAS 2.0 Security Definitions object from the given javascript data. * @param securityDefinitions * @param securityDefinitionsModel */ public readSecurityDefinitions(securityDefinitions: any[], securityDefinitionsModel: Oas20SecurityDefinitions): void { for (let name in securityDefinitions) { let scheme: any = securityDefinitions[name]; let schemeModel: Oas20SecurityScheme = securityDefinitionsModel.createSecurityScheme(name); this.readSecurityScheme(scheme, schemeModel); securityDefinitionsModel.addSecurityScheme(name, schemeModel); } } /** * Reads an OAS 2.0 Security Schema object from the given javascript data. * @param scheme * @param schemeModel */ public readSecurityScheme(scheme: any, schemeModel: Oas20SecurityScheme): void { super.readSecurityScheme(scheme, schemeModel, false); let flow: string = this.consume(scheme, "flow"); let authorizationUrl: string = this.consume(scheme, "authorizationUrl"); let tokenUrl: string = this.consume(scheme, "tokenUrl"); let scopes: any = this.consume(scheme, "scopes"); if (this.isDefined(flow)) { schemeModel.flow = flow; } if (this.isDefined(authorizationUrl)) { schemeModel.authorizationUrl = authorizationUrl; } if (this.isDefined(tokenUrl)) { schemeModel.tokenUrl = tokenUrl; } if (this.isDefined(scopes)) { let scopesModel: Oas20Scopes = schemeModel.createScopes(); this.readScopes(scopes, scopesModel); schemeModel.scopes = scopesModel; } this.readExtraProperties(scheme, schemeModel); } /** * Reads an OAS 2.0 Scopes object from the given javascript data. * @param scopes * @param scopesModel */ public readScopes(scopes: any, scopesModel: Oas20Scopes): void { for (let scope in scopes) { if (scope.indexOf("x-") === 0) { continue; } let description: string = this.consume(scopes, scope); scopesModel.addScope(scope, description); } this.readExtensions(scopes, scopesModel); this.readExtraProperties(scopes, scopesModel); } /** * Reads an OAS 2.0 Operation object from the given JS data. * @param operation * @param operationModel */ public readOperation(operation: any, operationModel: Oas20Operation): void { super.readOperation(operation, operationModel, false); let consumes: string[] = this.consume(operation, "consumes"); let produces: string[] = this.consume(operation, "produces"); let schemes: string[] = this.consume(operation, "schemes"); if (this.isDefined(consumes)) { operationModel.consumes = consumes; } if (this.isDefined(produces)) { operationModel.produces = produces; } if (this.isDefined(schemes)) { operationModel.schemes = schemes; } this.readExtraProperties(operation, operationModel); } /** * Reads an OAS 2.0 Parameter object from the given JS data. * @param parameter * @param paramModel */ public readParameter(parameter: any, paramModel: Oas20Parameter): void { let $ref: string = this.consume(parameter, "$ref"); if (this.isDefined($ref)) { paramModel.$ref = $ref; } this.readParameterBase(parameter, paramModel); this.readExtraProperties(parameter, paramModel); } /** * Reads an OAS 2.0 Parameter Definition from the given JS data. * @param parameterDef * @param paramDefModel */ public readParameterDefinition(parameterDef: any, paramDefModel: Oas20ParameterDefinition): void { this.readParameterBase(parameterDef, paramDefModel); this.readExtraProperties(parameterDef, paramDefModel); } /** * Reads an OAS 2.0 Parameter object from the given JS data. * @param parameter * @param paramModel */ private readParameterBase(parameter: any, paramModel: Oas20ParameterBase): void { this.readItems(parameter, paramModel, false); let name: string = this.consume(parameter, "name"); let in_: string = this.consume(parameter, "in"); let description: string = this.consume(parameter, "description"); let required: boolean = this.consume(parameter, "required"); let schema: any = this.consume(parameter, "schema"); let allowEmptyValue: boolean = this.consume(parameter, "allowEmptyValue"); if (this.isDefined(name)) { paramModel.name = name; } if (this.isDefined(in_)) { paramModel.in = in_; } if (this.isDefined(description)) { paramModel.description = description; } if (this.isDefined(required)) { paramModel.required = required; } if (this.isDefined(schema)) { let schemaModel: Oas20Schema = paramModel.createSchema(); this.readSchema(schema, schemaModel); paramModel.schema = schemaModel; } if (this.isDefined(allowEmptyValue)) { paramModel.allowEmptyValue = allowEmptyValue; } this.readExtensions(parameter, paramModel); } /** * Reads an OAS 2.0 Items object from the given JS data. * @param items * @param itemsModel */ public readItems(items: any, itemsModel: Oas20Items, readExtra: boolean = true): void { let type: string = this.consume(items, "type"); let format: string = this.consume(items, "format"); let itemsChild: any = this.consume(items, "items"); let collectionFormat: string = this.consume(items, "collectionFormat"); let default_: any = this.consume(items, "default"); let maximum: number = this.consume(items, "maximum"); let exclusiveMaximum: boolean = this.consume(items, "exclusiveMaximum"); let minimum: number = this.consume(items, "minimum"); let exclusiveMinimum: boolean = this.consume(items, "exclusiveMinimum"); let maxLength: number = this.consume(items, "maxLength"); // Require: integer let minLength: number = this.consume(items, "minLength"); // Require: integer let pattern: string = this.consume(items, "pattern"); let maxItems: number = this.consume(items, "maxItems"); // Require: integer let minItems: number = this.consume(items, "minItems"); // Require: integer let uniqueItems: boolean = this.consume(items, "uniqueItems"); let enum_: any[] = this.consume(items, "enum"); let multipleOf: number = this.consume(items, "multipleOf"); if (this.isDefined(type)) { itemsModel.type = type; } if (this.isDefined(format)) { itemsModel.format = format; } if (this.isDefined(itemsChild)) { let itemsChildModel: Oas20Items = itemsModel.createItems(); this.readItems(itemsChild, itemsChildModel); itemsModel.items = itemsChildModel; } if (this.isDefined(collectionFormat)) { itemsModel.collectionFormat = collectionFormat; } if (this.isDefined(default_)) { itemsModel.default = default_; } if (this.isDefined(maximum)) { itemsModel.maximum = maximum; } if (this.isDefined(exclusiveMaximum)) { itemsModel.exclusiveMaximum = exclusiveMaximum; } if (this.isDefined(minimum)) { itemsModel.minimum = minimum; } if (this.isDefined(exclusiveMinimum)) { itemsModel.exclusiveMinimum = exclusiveMinimum; } if (this.isDefined(maxLength)) { itemsModel.maxLength = maxLength; } if (this.isDefined(minLength)) { itemsModel.minLength = minLength; } if (this.isDefined(pattern)) { itemsModel.pattern = pattern; } if (this.isDefined(maxItems)) { itemsModel.maxItems = maxItems; } if (this.isDefined(minItems)) { itemsModel.minItems = minItems; } if (this.isDefined(uniqueItems)) { itemsModel.uniqueItems = uniqueItems; } if (this.isDefined(enum_)) { itemsModel.enum = enum_; } if (this.isDefined(multipleOf)) { itemsModel.multipleOf = multipleOf; } this.readExtensions(items, itemsModel); if (readExtra) { this.readExtraProperties(items, itemsModel); } } /** * Reads an OAS 2.0 Response object from the given JS data. * @param response * @param responseModel */ public readResponse(response: any, responseModel: Oas20Response): void { let $ref: string = this.consume(response, "$ref"); if (this.isDefined($ref)) { responseModel.$ref = $ref; } this.readResponseBase(response, responseModel); this.readExtraProperties(response, responseModel); } /** * Reads an OAS 2.0 Response Definition object from the given JS data. * @param response * @param responseDefModel */ public readResponseDefinition(response: any, responseDefModel: Oas20ResponseDefinition): void { this.readResponseBase(response, responseDefModel); this.readExtraProperties(response, responseDefModel); } /** * Reads an OAS 2.0 Response object from the given JS data. * @param response * @param responseModel */ private readResponseBase(response: any, responseModel: Oas20ResponseBase): void { let description: string = this.consume(response, "description"); let schema: any = this.consume(response, "schema"); let headers: any = this.consume(response, "headers"); let examples: any = this.consume(response, "examples"); if (this.isDefined(description)) { responseModel.description = description; } if (this.isDefined(schema)) { let schemaModel: Oas20Schema = responseModel.createSchema(); this.readSchema(schema, schemaModel); responseModel.schema = schemaModel; } if (this.isDefined(headers)) { let headersModel: Oas20Headers = responseModel.createHeaders(); this.readHeaders(headers, headersModel); responseModel.headers = headersModel; } if (this.isDefined(examples)) { let exampleModel: Oas20Example = responseModel.createExample(); this.readExample(examples, exampleModel); responseModel.examples = exampleModel; } this.readExtensions(response, responseModel); } /** * Reads an OAS 2.0 Example object from the given JS data. * @param examples * @param exampleModel */ public readExample(examples: any, exampleModel: Oas20Example): void { for (let contentType in examples) { let example: any = examples[contentType]; exampleModel.addExample(contentType, example); } } /** * Reads an OAS Headers object from the given JS data. * @param headers * @param headersModel */ public readHeaders(headers: any, headersModel: Oas20Headers): void { for (let headerName in headers) { let header: any = headers[headerName]; let headerModel: Oas20Header = headersModel.createHeader(headerName); this.readHeader(header, headerModel); headersModel.addHeader(headerName, headerModel); } } /** * Reads an OAS 2.0 Header object from the given JS data. * @param header * @param headerModel */ public readHeader(header: any, headerModel: Oas20Header): void { let description: string = this.consume(header, "description"); if (this.isDefined(description)) { headerModel.description = description; } // Note: readItems() will finalize the input, so we can't read anything after this this.readItems(header, headerModel); } /** * Reads an OAS 2.0 Definitions object from the given JS data. * @param definitions * @param definitionsModel */ public readDefinitions(definitions: any, definitionsModel: Oas20Definitions): void { for (let definitionName in definitions) { let definition: any = definitions[definitionName]; let definitionSchemaModel: Oas20SchemaDefinition = definitionsModel.createSchemaDefinition(definitionName); this.readSchema(definition, definitionSchemaModel); definitionsModel.addDefinition(definitionName, definitionSchemaModel); } } /** * Reads an OAS 2.0 Parameters Definitions object from the given JS data. * @param parameters * @param parametersDefinitionsModel */ public readParametersDefinitions(parameters: any, parametersDefinitionsModel: Oas20ParametersDefinitions): void { for (let parameterName in parameters) { let parameter: any = parameters[parameterName]; let parameterDefModel: Oas20ParameterDefinition = parametersDefinitionsModel.createParameter(parameterName); this.readParameterDefinition(parameter, parameterDefModel); parametersDefinitionsModel.addParameter(parameterName, parameterDefModel); } } /** * Reads an OAS 2.0 Responses Definitions object from the given JS data. * @param responses * @param responsesDefinitionsModel */ public readResponsesDefinitions(responses: any, responsesDefinitionsModel: Oas20ResponsesDefinitions): void { for (let responseName in responses) { let response: any = responses[responseName]; let responseModel: Oas20ResponseDefinition = responsesDefinitionsModel.createResponse(responseName); this.readResponseBase(response, responseModel); responsesDefinitionsModel.addResponse(responseName, responseModel); } } } /** * A visitor used to invoke the appropriate readXYZ() method on the Oas20JS2ModelReader * class. This is useful when reading a partial (non root) model from a JS object. The * caller still needs to first construct the appropriate model prior to reading into it. */ export class Oas20JS2ModelReaderVisitor implements IOas20NodeVisitor { /** * Constructor. * @param reader * @param jsData */ constructor(private reader: Oas20JS2ModelReader, private jsData: any) {} public visitDocument(node: Oas20Document): void { this.reader.readDocument(this.jsData, node); } public visitInfo(node: Oas20Info): void { this.reader.readInfo(this.jsData, node); } public visitContact(node: Oas20Contact): void { this.reader.readContact(this.jsData, node); } public visitLicense(node: Oas20License): void { this.reader.readLicense(this.jsData, node); } public visitPaths(node: Oas20Paths): void { this.reader.readPaths(this.jsData, node); } public visitPathItem(node: Oas20PathItem): void { this.reader.readPathItem(this.jsData, node); } public visitOperation(node: Oas20Operation): void { this.reader.readOperation(this.jsData, node); } public visitParameter(node: Oas20Parameter): void { this.reader.readParameter(this.jsData, node); } public visitParameterDefinition(node: Oas20ParameterDefinition): void { this.reader.readParameterDefinition(this.jsData, node); } public visitExternalDocumentation(node: Oas20ExternalDocumentation): void { this.reader.readExternalDocumentation(this.jsData, node); } public visitSecurityRequirement(node: Oas20SecurityRequirement): void { this.reader.readSecurityRequirement(this.jsData, node); } public visitResponses(node: Oas20Responses): void { this.reader.readResponses(this.jsData, node); } public visitResponse(node: Oas20Response): void { this.reader.readResponse(this.jsData, node); } public visitResponseDefinition(node: Oas20ResponseDefinition): void { this.reader.readResponseDefinition(this.jsData, node); } public visitSchema(node: Oas20Schema): void { this.reader.readSchema(this.jsData, node); } public visitHeaders(node: Oas20Headers): void { this.reader.readHeaders(this.jsData, node); } public visitHeader(node: Oas20Header): void { this.reader.readHeader(this.jsData, node); } public visitExample(node: Oas20Example): void { this.reader.readExample(this.jsData, node); } public visitItems(node: Oas20Items): void { this.reader.readItems(this.jsData, node); } public visitTag(node: Oas20Tag): void { this.reader.readTag(this.jsData, node); } public visitSecurityDefinitions(node: Oas20SecurityDefinitions): void { this.reader.readSecurityDefinitions(this.jsData, node); } public visitSecurityScheme(node: Oas20SecurityScheme): void { this.reader.readSecurityScheme(this.jsData, node); } public visitScopes(node: Oas20Scopes): void { this.reader.readScopes(this.jsData, node); } public visitXML(node: Oas20XML): void { this.reader.readXML(this.jsData, node); } public visitSchemaDefinition(node: Oas20SchemaDefinition): void { this.reader.readSchema(this.jsData, node); } public visitPropertySchema(node: Oas20PropertySchema): void { this.reader.readSchema(this.jsData, node); } public visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void { this.reader.readSchema(this.jsData, node); } public visitAllOfSchema(node: Oas20AllOfSchema): void { this.reader.readSchema(this.jsData, node); } public visitItemsSchema(node: Oas20ItemsSchema): void { this.reader.readSchema(this.jsData, node); } public visitDefinitions(node: Oas20Definitions): void { this.reader.readDefinitions(this.jsData, node); } public visitParametersDefinitions(node: Oas20ParametersDefinitions): void { this.reader.readParametersDefinitions(this.jsData, node); } public visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void { this.reader.readResponsesDefinitions(this.jsData, node); } public visitExtension(node: OasExtension): void { // Not supported: cannot read a single extension } public visitValidationProblem(node: OasValidationProblem): void { // Not supported: validation problems are transient } } /** * A visitor used to invoke the appropriate readXYZ() method on the Oas20JS2ModelReader * class. This is useful when reading a partial (non root) model from a JS object. The * caller still needs to first construct the appropriate model prior to reading into it. */ export class Oas30JS2ModelReaderVisitor implements IOas30NodeVisitor { /** * Constructor. * @param reader * @param jsData */ constructor(private reader: Oas30JS2ModelReader, private jsData: any) {} public visitDocument(node: Oas30Document): void { this.reader.readDocument(this.jsData, node); } public visitInfo(node: Oas30Info): void { this.reader.readInfo(this.jsData, node); } public visitContact(node: Oas30Contact): void { this.reader.readContact(this.jsData, node); } public visitLicense(node: Oas30License): void { this.reader.readLicense(this.jsData, node); } public visitPaths(node: Oas30Paths): void { this.reader.readPaths(this.jsData, node); } public visitPathItem(node: Oas30PathItem): void { this.reader.readPathItem(this.jsData, node); } public visitOperation(node: Oas30Operation): void { this.reader.readOperation(this.jsData, node); } public visitParameter(node: Oas30Parameter): void { this.reader.readParameter(this.jsData, node); } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.reader.readParameterBase(this.jsData, node); } public visitResponses(node: Oas30Responses): void { this.reader.readResponses(this.jsData, node); } public visitResponse(node: Oas30Response): void { this.reader.readResponse(this.jsData, node); } public visitMediaType(node: Oas30MediaType): void { this.reader.readMediaType(this.jsData, node); } public visitEncoding(node: Oas30Encoding): void { this.reader.readEncoding(this.jsData, node); } public visitExample(node: Oas30Example): void { this.reader.readExample(this.jsData, node); } public visitLink(node: Oas30Link): void { this.reader.readLink(this.jsData, node); } public visitLinkParameterExpression(node: Oas30LinkParameterExpression): void { // Nothing to read - the expression is simple and not extensible } public visitLinkRequestBodyExpression(node: Oas30LinkRequestBodyExpression): void { // Nothing to read - the expression is simple and not extensible } public visitLinkServer(node: Oas30LinkServer): void { this.reader.readServer(this.jsData, node); } public visitResponseDefinition(node: Oas30ResponseDefinition): void { this.reader.readResponseBase(this.jsData, node); } public visitSchema(node: Oas30Schema): void { this.reader.readSchema(this.jsData, node); } public visitDiscriminator(node: Oas30Discriminator): void { this.reader.readDiscriminator(this.jsData, node); } public visitXML(node: Oas30XML): void { this.reader.readXML(this.jsData, node); } public visitHeader(node: Oas30Header): void { this.reader.readHeader(this.jsData, node); } public visitRequestBody(node: Oas30RequestBody): void { this.reader.readRequestBody(this.jsData, node); } public visitCallback(node: Oas30Callback): void { this.reader.readCallback(this.jsData, node); } public visitCallbackPathItem(node: Oas30CallbackPathItem): void { this.reader.readPathItem(this.jsData, node); } public visitServer(node: Oas30Server): void { this.reader.readServer(this.jsData, node); } public visitServerVariable(node: Oas30ServerVariable): void { this.reader.readServerVariable(this.jsData, node); } public visitSecurityRequirement(node: Oas30SecurityRequirement): void { this.reader.readSecurityRequirement(this.jsData, node); } public visitTag(node: Oas30Tag): void { this.reader.readTag(this.jsData, node); } public visitExternalDocumentation(node: Oas30ExternalDocumentation): void { this.reader.readExternalDocumentation(this.jsData, node); } public visitAllOfSchema(node: Oas30AllOfSchema): void { this.reader.readSchema(this.jsData, node); } public visitAnyOfSchema(node: Oas30AnyOfSchema): void { this.reader.readSchema(this.jsData, node); } public visitOneOfSchema(node: Oas30OneOfSchema): void { this.reader.readSchema(this.jsData, node); } public visitNotSchema(node: Oas30NotSchema): void { this.reader.readSchema(this.jsData, node); } public visitPropertySchema(node: Oas30PropertySchema): void { this.reader.readSchema(this.jsData, node); } public visitItemsSchema(node: Oas30ItemsSchema): void { this.reader.readSchema(this.jsData, node); } public visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void { this.reader.readSchema(this.jsData, node); } public visitComponents(node: Oas30Components): void { this.reader.readComponents(this.jsData, node); } public visitSchemaDefinition(node: Oas30SchemaDefinition): void { this.reader.readSchema(this.jsData, node); } public visitExampleDefinition(node: Oas30ExampleDefinition): void { this.reader.readExample(this.jsData, node); } public visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void { this.reader.readRequestBody(this.jsData, node); } public visitHeaderDefinition(node: Oas30HeaderDefinition): void { this.reader.readHeader(this.jsData, node); } public visitOAuthFlows(node: Oas30OAuthFlows): void { this.reader.readOAuthFlows(this.jsData, node); } public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.reader.readOAuthFlow(this.jsData, node); } public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.reader.readOAuthFlow(this.jsData, node); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.reader.readOAuthFlow(this.jsData, node); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.reader.readOAuthFlow(this.jsData, node); } public visitSecurityScheme(node: Oas30SecurityScheme): void { this.reader.readSecurityScheme(this.jsData, node); } public visitLinkDefinition(node: Oas30LinkDefinition): void { this.reader.readLink(this.jsData, node); } public visitCallbackDefinition(node: Oas30CallbackDefinition): void { this.reader.readCallback(this.jsData, node); } public visitExtension(node: OasExtension): void { // Not supported: cannot read a single extension } public visitValidationProblem(node: OasValidationProblem): void { // Not supported: validation problems are transient } } /** * This class reads a javascript object and turns it into a OAS 3.0 model. It is obviously * assumed that the javascript data actually does represent an OAS 3.0 document. */ export class Oas30JS2ModelReader extends OasJS2ModelReader { /** * Reads the given javascript data and returns an OAS 3.0 document. Throws an error if * the root 'openapi' property is not found or if its value is not "3.0.x". * @param jsData */ public read(jsData: any): Oas30Document { let docModel: Oas30Document = new Oas30Document(); this.readDocument(jsData, docModel); return docModel; } /** * Reads an OAS 3.0 Document object from the given JS data. * @param document * @param documentModel */ public readDocument(document: any, documentModel: Oas30Document): void { let openapi: string = this.consume(document, "openapi"); if (openapi.indexOf("3.") != 0) { throw Error("Unsupported specification version: " + openapi); } super.readDocument(document, documentModel, false); let servers: any = this.consume(document, "servers"); let components: any = this.consume(document, "components"); documentModel.openapi = openapi; if (Array.isArray(servers)) { documentModel.servers = []; servers.forEach( server => { let serverModel: Oas30Server = documentModel.createServer(); this.readServer(server, serverModel); documentModel.servers.push(serverModel); }) } if (this.isDefined(components)) { let componentsModel: Oas30Components = documentModel.createComponents(); this.readComponents(components, componentsModel); documentModel.components = componentsModel; } this.readExtraProperties(document, documentModel); } /** * Reads an OAS 3.0 Components object from the given JS data. * @param components * @param componentsModel */ public readComponents(components: any, componentsModel: Oas30Components): void { let schemas: any = this.consume(components, "schemas"); let responses: any = this.consume(components, "responses"); let parameters: any = this.consume(components, "parameters"); let examples: any = this.consume(components, "examples"); let requestBodies: any = this.consume(components, "requestBodies"); let headers: any = this.consume(components, "headers"); let securitySchemes: any = this.consume(components, "securitySchemes"); let links: any = this.consume(components, "links"); let callbacks: any = this.consume(components, "callbacks"); if (this.isDefined(schemas)) { for (let name in schemas) { let schema: any = schemas[name]; let schemaModel: Oas30SchemaDefinition = componentsModel.createSchemaDefinition(name); this.readSchema(schema, schemaModel); componentsModel.addSchemaDefinition(name, schemaModel); } } if (this.isDefined(responses)) { for (let name in responses) { let response: any = responses[name]; let responseModel: Oas30ResponseDefinition = componentsModel.createResponseDefinition(name); this.readResponseBase(response, responseModel); componentsModel.addResponseDefinition(name, responseModel); } } if (this.isDefined(parameters)) { for (let name in parameters) { let parameter: any = parameters[name]; let parameterModel: Oas30ParameterDefinition = componentsModel.createParameterDefinition(name); this.readParameterBase(parameter, parameterModel); componentsModel.addParameterDefinition(name, parameterModel); } } if (this.isDefined(examples)) { for (let name in examples) { let example: any = examples[name]; let exampleModel: Oas30ExampleDefinition = componentsModel.createExampleDefinition(name); this.readExample(example, exampleModel); componentsModel.addExampleDefinition(name, exampleModel); } } if (this.isDefined(requestBodies)) { for (let name in requestBodies) { let requestBody: any = requestBodies[name]; let requestBodyModel: Oas30RequestBodyDefinition = componentsModel.createRequestBodyDefinition(name); this.readRequestBody(requestBody, requestBodyModel); componentsModel.addRequestBodyDefinition(name, requestBodyModel); } } if (this.isDefined(headers)) { for (let name in headers) { let header: any = headers[name]; let headerModel: Oas30HeaderDefinition = componentsModel.createHeaderDefinition(name); this.readHeader(header, headerModel); componentsModel.addHeaderDefinition(name, headerModel); } } if (this.isDefined(securitySchemes)) { for (let name in securitySchemes) { let securityScheme: any = securitySchemes[name]; let securitySchemeModel: Oas30SecurityScheme = componentsModel.createSecurityScheme(name); this.readSecurityScheme(securityScheme, securitySchemeModel); componentsModel.addSecurityScheme(name, securitySchemeModel); } } if (this.isDefined(links)) { for (let name in links) { let link: any = links[name]; let linkModel: Oas30LinkDefinition = componentsModel.createLinkDefinition(name); this.readLink(link, linkModel); componentsModel.addLinkDefinition(name, linkModel); } } if (this.isDefined(callbacks)) { for (let name in callbacks) { let callback: any = callbacks[name]; let callbackModel: Oas30CallbackDefinition = componentsModel.createCallbackDefinition(name); this.readCallback(callback, callbackModel); componentsModel.addCallbackDefinition(name, callbackModel); } } this.readExtensions(components, componentsModel); this.readExtraProperties(components, componentsModel); } /** * Reads an OAS 3.0 Security Scheme object from the given JS data. * @param securityScheme * @param securitySchemeModel */ public readSecurityScheme(securityScheme: any, securitySchemeModel: Oas30SecurityScheme): void { super.readSecurityScheme(securityScheme, securitySchemeModel, false); let $ref: string = this.consume(securityScheme, "$ref"); let scheme: string = this.consume(securityScheme, "scheme"); let bearerFormat: string = this.consume(securityScheme, "bearerFormat"); let flows: any = this.consume(securityScheme, "flows"); let openIdConnectUrl: string = this.consume(securityScheme, "openIdConnectUrl"); if (this.isDefined($ref)) { securitySchemeModel.$ref = $ref; } if (this.isDefined(scheme)) { securitySchemeModel.scheme = scheme; } if (this.isDefined(bearerFormat)) { securitySchemeModel.bearerFormat = bearerFormat; } if (this.isDefined(flows)) { let flowsModel: Oas30OAuthFlows = securitySchemeModel.createOAuthFlows(); this.readOAuthFlows(flows, flowsModel); securitySchemeModel.flows = flowsModel; } if (this.isDefined(openIdConnectUrl)) { securitySchemeModel.openIdConnectUrl = openIdConnectUrl; } this.readExtensions(securityScheme, securitySchemeModel); this.readExtraProperties(securityScheme, securitySchemeModel); } /** * Reads an OAS 3.0 OAuth Flows object from the given JS data. * @param flows * @param flowsModel */ public readOAuthFlows(flows: any, flowsModel: Oas30OAuthFlows): void { let implicit: any = this.consume(flows, "implicit"); let password: any = this.consume(flows, "password"); let clientCredentials: any = this.consume(flows, "clientCredentials"); let authorizationCode: any = this.consume(flows, "authorizationCode"); if (this.isDefined(implicit)) { let flowModel: Oas30ImplicitOAuthFlow = flowsModel.createImplicitOAuthFlow(); this.readOAuthFlow(implicit, flowModel); flowsModel.implicit = flowModel; } if (this.isDefined(password)) { let flowModel: Oas30PasswordOAuthFlow = flowsModel.createPasswordOAuthFlow(); this.readOAuthFlow(password, flowModel); flowsModel.password = flowModel; } if (this.isDefined(clientCredentials)) { let flowModel: Oas30ClientCredentialsOAuthFlow = flowsModel.createClientCredentialsOAuthFlow(); this.readOAuthFlow(clientCredentials, flowModel); flowsModel.clientCredentials = flowModel; } if (this.isDefined(authorizationCode)) { let flowModel: Oas30AuthorizationCodeOAuthFlow = flowsModel.createAuthorizationCodeOAuthFlow(); this.readOAuthFlow(authorizationCode, flowModel); flowsModel.authorizationCode = flowModel; } this.readExtensions(flows, flowsModel); this.readExtraProperties(flows, flowsModel); } /** * Reads an OAS 3.0 OAuth Flow object from the given JS data. * @param flow * @param flowModel */ public readOAuthFlow(flow: any, flowModel: Oas30OAuthFlow): void { let authorizationUrl: string = this.consume(flow, "authorizationUrl"); let tokenUrl: string = this.consume(flow, "tokenUrl"); let refreshUrl: string = this.consume(flow, "refreshUrl"); let scopes: any = this.consume(flow, "scopes"); if (this.isDefined(authorizationUrl)) { flowModel.authorizationUrl = authorizationUrl; } if (this.isDefined(tokenUrl)) { flowModel.tokenUrl = tokenUrl; } if (this.isDefined(refreshUrl)) { flowModel.refreshUrl = refreshUrl; } if (this.isDefined(scopes)) { for (let name in scopes) { let scopeDescription: any = scopes[name]; flowModel.addScope(name, scopeDescription); } } this.readExtensions(flow, flowModel); this.readExtraProperties(flow, flowModel); } /** * Reads an OAS 3.0 PathItem object from the given JS data. * @param pathItem * @param pathItemModel */ public readPathItem(pathItem: any, pathItemModel: Oas30PathItem): void { super.readPathItem(pathItem, pathItemModel, false); let summary: any = this.consume(pathItem, "summary"); let description: any = this.consume(pathItem, "description"); let trace: any = this.consume(pathItem, "trace"); let servers: any = this.consume(pathItem, "servers"); if (this.isDefined(summary)) { pathItemModel.summary = summary; } if (this.isDefined(description)) { pathItemModel.description = description; } if (this.isDefined(trace)) { let opModel: Oas30Operation = pathItemModel.createOperation("trace"); this.readOperation(trace, opModel); pathItemModel.trace = opModel; } if (Array.isArray(servers)) { pathItemModel.servers = []; for (let server of servers) { let serverModel: Oas30Server = pathItemModel.createServer(); this.readServer(server, serverModel); pathItemModel.servers.push(serverModel); } } this.readExtraProperties(pathItem, pathItemModel); } /** * Reads an OAS 3.0 Header object from the given js data. * @param header * @param headerModel */ public readHeader(header: any, headerModel: Oas30Header): void { let $ref: string = this.consume(header, "$ref"); let description: string = this.consume(header, "description"); let required: boolean = this.consume(header, "required"); let schema: any = this.consume(header, "schema"); let allowEmptyValue: boolean = this.consume(header, "allowEmptyValue"); let deprecated: boolean = this.consume(header, "deprecated"); let style: string = this.consume(header, "style"); let explode: boolean = this.consume(header, "explode"); let allowReserved: boolean = this.consume(header, "allowReserved"); let example: any = this.consume(header, "example"); let examples: any = this.consume(header, "examples"); let content: any = this.consume(header, "content"); if (this.isDefined($ref)) { headerModel.$ref = $ref; } if (this.isDefined(description)) { headerModel.description = description; } if (this.isDefined(required)) { headerModel.required = required; } if (this.isDefined(schema)) { let schemaModel: Oas30Schema = headerModel.createSchema(); this.readSchema(schema, schemaModel); headerModel.schema = schemaModel; } if (this.isDefined(allowEmptyValue)) { headerModel.allowEmptyValue = allowEmptyValue; } if (this.isDefined(deprecated)) { headerModel.deprecated = deprecated; } if (this.isDefined(style)) { headerModel.style = style; } if (this.isDefined(explode)) { headerModel.explode = explode; } if (this.isDefined(allowReserved)) { headerModel.allowReserved = allowReserved; } if (this.isDefined(example)) { headerModel.example = example; } if (this.isDefined(examples)) { for (let exampleName in examples) { let exx: any = examples[exampleName]; let exampleModel: Oas30Example = headerModel.createExample(exampleName); this.readExample(exx, exampleModel); headerModel.addExample(exampleModel); } } if (this.isDefined(content)) { for (let name in content) { let mediaType: any = content[name]; let mediaTypeModel: Oas30MediaType = headerModel.createMediaType(name); this.readMediaType(mediaType, mediaTypeModel); headerModel.addMediaType(name, mediaTypeModel); } } this.readExtensions(header, headerModel); this.readExtraProperties(header, headerModel); } /** * Reads an OAS 3.0 Parameter object from the given JS data. * @param parameter * @param paramModel */ public readParameterBase(parameter: any, paramModel: Oas30ParameterBase): void { let $ref: string = this.consume(parameter, "$ref"); let name: string = this.consume(parameter, "name"); let in_: string = this.consume(parameter, "in"); let description: string = this.consume(parameter, "description"); let required: boolean = this.consume(parameter, "required"); let schema: any = this.consume(parameter, "schema"); let allowEmptyValue: boolean = this.consume(parameter, "allowEmptyValue"); let deprecated: boolean = this.consume(parameter, "deprecated"); let style: string = this.consume(parameter, "style"); let explode: boolean = this.consume(parameter, "explode"); let allowReserved: boolean = this.consume(parameter, "allowReserved"); let example: any = this.consume(parameter, "example"); let examples: any = this.consume(parameter, "examples"); let content: any = this.consume(parameter, "content"); if (this.isDefined($ref)) { paramModel.$ref = $ref; } if (this.isDefined(name)) { paramModel.name = name; } if (this.isDefined(in_)) { paramModel.in = in_; } if (this.isDefined(description)) { paramModel.description = description; } if (this.isDefined(required)) { paramModel.required = required; } if (this.isDefined(schema)) { let schemaModel: Oas30Schema = paramModel.createSchema(); this.readSchema(schema, schemaModel); paramModel.schema = schemaModel; } if (this.isDefined(allowEmptyValue)) { paramModel.allowEmptyValue = allowEmptyValue; } if (this.isDefined(deprecated)) { paramModel.deprecated = deprecated; } if (this.isDefined(style)) { paramModel.style = style; } if (this.isDefined(explode)) { paramModel.explode = explode; } if (this.isDefined(allowReserved)) { paramModel.allowReserved = allowReserved; } if (this.isDefined(example)) { paramModel.example = example; } if (this.isDefined(examples)) { for (let exampleName in examples) { let exx: any = examples[exampleName]; let exampleModel: Oas30Example = paramModel.createExample(exampleName); this.readExample(exx, exampleModel); paramModel.addExample(exampleModel); } } if (this.isDefined(content)) { for (let name in content) { let mediaType: any = content[name]; let mediaTypeModel: Oas30MediaType = paramModel.createMediaType(name); this.readMediaType(mediaType, mediaTypeModel); paramModel.addMediaType(name, mediaTypeModel); } } this.readExtensions(parameter, paramModel); } /** * Reads an OAS 3.0 Parameter object from the given js data. * @param parameter * @param paramModel */ public readParameter(parameter: any, paramModel: Oas30Parameter): void { let $ref: string = this.consume(parameter, "$ref"); if (this.isDefined($ref)) { paramModel.$ref = $ref; } this.readParameterBase(parameter, paramModel); this.readExtraProperties(parameter, paramModel); } /** * Reads an OAS 3.0 Operation object from the given JS data. * @param operation * @param operationModel */ public readOperation(operation: any, operationModel: Oas30Operation): void { super.readOperation(operation, operationModel, false); let requestBody: any = this.consume(operation, "requestBody"); let callbacks: any = this.consume(operation, "callbacks"); let servers: Oas30Server[] = this.consume(operation, "servers"); if (this.isDefined(requestBody)) { let requestBodyModel: Oas30RequestBody = operationModel.createRequestBody(); this.readRequestBody(requestBody, requestBodyModel); operationModel.requestBody = requestBodyModel; } if (this.isDefined(callbacks)) { for (let name in callbacks) { let callback: any = callbacks[name]; let callbackModel: Oas30Callback = operationModel.createCallback(name); this.readCallback(callback, callbackModel); operationModel.addCallback(name, callbackModel); } } if (Array.isArray(servers)) { operationModel.servers = []; servers.forEach( server => { let serverModel: Oas30Server = operationModel.createServer(); this.readServer(server, serverModel); operationModel.servers.push(serverModel); }) } this.readExtraProperties(operation, operationModel); } /** * Reads an OAS 3.0 Callback object from the given JS data. * @param callback * @param callbackModel */ public readCallback(callback: any, callbackModel: Oas30Callback): void { for (let name in callback) { if (name === "$ref") { callbackModel.$ref = this.consume(callback, name); } else { let pathItem: any = this.consume(callback, name); let pathItemModel: Oas30PathItem = callbackModel.createPathItem(name); this.readPathItem(pathItem, pathItemModel); callbackModel.addPathItem(name, pathItemModel); } } this.readExtensions(callback, callbackModel); this.readExtraProperties(callback, callbackModel); } /** * Reads an OAS 3.0 Request Body object from the given JS data. * @param requestBody * @param requestBodyModel */ public readRequestBody(requestBody: any, requestBodyModel: Oas30RequestBody): void { let $ref: string = this.consume(requestBody, "$ref"); let description: string = this.consume(requestBody, "description"); let content: any = this.consume(requestBody, "content"); let required: boolean = this.consume(requestBody, "required"); if (this.isDefined($ref)) { requestBodyModel.$ref = $ref; } if (this.isDefined(description)) { requestBodyModel.description = description; } if (this.isDefined(content)) { for (let name in content) { let mediaType: any = content[name]; let mediaTypeModel: Oas30MediaType = requestBodyModel.createMediaType(name); this.readMediaType(mediaType, mediaTypeModel); requestBodyModel.addMediaType(name, mediaTypeModel); } } if (this.isDefined(required)) { requestBodyModel.required = required; } this.readExtensions(requestBody, requestBodyModel); this.readExtraProperties(requestBody, requestBodyModel); } /** * Reads an OAS 3.0 Media Type from the given js data. * @param mediaType * @param mediaTypeModel */ public readMediaType(mediaType: any, mediaTypeModel: Oas30MediaType): void { let schema: any = this.consume(mediaType, "schema"); let example: any = this.consume(mediaType, "example"); let examples: any = this.consume(mediaType, "examples"); let encodings: any = this.consume(mediaType, "encoding"); if (this.isDefined(schema)) { let schemaModel: Oas30Schema = mediaTypeModel.createSchema(); this.readSchema(schema, schemaModel); mediaTypeModel.schema = schemaModel; } if (this.isDefined(example)) { mediaTypeModel.example = example; } if (this.isDefined(examples)) { for (let exampleName in examples) { let exx: any = examples[exampleName]; let exampleModel: Oas30Example = mediaTypeModel.createExample(exampleName); this.readExample(exx, exampleModel); mediaTypeModel.addExample(exampleModel); } } if (this.isDefined(encodings)) { for (let name in encodings) { let encoding: any = encodings[name]; let encodingModel: Oas30Encoding = mediaTypeModel.createEncoding(name); this.readEncoding(encoding, encodingModel); mediaTypeModel.addEncoding(name, encodingModel); } } this.readExtensions(mediaType, mediaTypeModel); this.readExtraProperties(mediaType, mediaTypeModel); } /** * Reads an OAS 3.0 Example from the given js data. * @param example * @param exampleModel */ public readExample(example: any, exampleModel: Oas30Example) { let $ref: string = this.consume(example, "$ref"); let summary: string = this.consume(example, "summary"); let description: string = this.consume(example, "description"); let value: any = this.consume(example, "value"); let externalValue: string = this.consume(example, "externalValue"); if (this.isDefined($ref)) { exampleModel.$ref = $ref; } if (this.isDefined(summary)) { exampleModel.summary = summary; } if (this.isDefined(description)) { exampleModel.description = description; } if (this.isDefined(value)) { exampleModel.value = value; } if (this.isDefined(externalValue)) { exampleModel.externalValue = externalValue; } this.readExtensions(example, exampleModel); this.readExtraProperties(example, exampleModel); } /** * Reads an OAS 3.0 Encoding from the given js data. * @param encodingProperty * @param encodingModel */ public readEncoding(encodingProperty: any, encodingModel: Oas30Encoding): void { let contentType: string = this.consume(encodingProperty, "contentType"); let headers: any = this.consume(encodingProperty, "headers"); let style: string = this.consume(encodingProperty, "style"); let explode: boolean = this.consume(encodingProperty, "explode"); let allowReserved: boolean = this.consume(encodingProperty, "allowReserved"); if (this.isDefined(contentType)) { encodingModel.contentType = contentType; } if (this.isDefined(headers)) { for (let name in headers) { let header: any = headers[name]; let headerModel: Oas30Header = encodingModel.createHeader(name); this.readHeader(header, headerModel); encodingModel.addHeader(name, headerModel); } } if (this.isDefined(style)) { encodingModel.style = style; } if (this.isDefined(explode)) { encodingModel.explode = explode; } if (this.isDefined(allowReserved)) { encodingModel.allowReserved = allowReserved; } this.readExtensions(encodingProperty, encodingModel); this.readExtraProperties(encodingProperty, encodingModel); } /** * Reads an OAS 3.0 Response object from the given js data. * @param response * @param responseModel */ public readResponse(response: any, responseModel: Oas30Response): void { this.readResponseBase(response, responseModel); this.readExtraProperties(response, responseModel); } /** * Reads an OAS 3.0 Response object from the given JS data. * @param response * @param responseModel */ public readResponseBase(response: any, responseModel: Oas30ResponseBase): void { let $ref: string = this.consume(response, "$ref"); let description: string = this.consume(response, "description"); let headers: any = this.consume(response, "headers"); let content: any = this.consume(response, "content"); let links: any = this.consume(response, "links"); if (this.isDefined($ref)) { responseModel.$ref = $ref; } if (this.isDefined(description)) { responseModel.description = description; } if (this.isDefined(headers)) { for (let name in headers) { let header: any = headers[name]; let headerModel: Oas30Header = responseModel.createHeader(name); this.readHeader(header, headerModel); responseModel.addHeader(name, headerModel); } } if (this.isDefined(content)) { for (let name in content) { let mediaType: any = content[name]; let mediaTypeModel: Oas30MediaType = responseModel.createMediaType(name); this.readMediaType(mediaType, mediaTypeModel); responseModel.addMediaType(name, mediaTypeModel); } } if (this.isDefined(links)) { for (let name in links) { let link: any = links[name]; let linkModel: Oas30Link = responseModel.createLink(name); this.readLink(link, linkModel); responseModel.addLink(name, linkModel); } } this.readExtensions(response, responseModel); } /** * Reads an OAS 3.0 Link object from the given js data. * @param link * @param linkModel */ public readLink(link: any, linkModel: Oas30Link): void { let $ref: string = this.consume(link, "$ref"); let operationRef: string = this.consume(link, "operationRef"); let operationId: string = this.consume(link, "operationId"); let parameters: any = this.consume(link, "parameters"); let requestBody: any = this.consume(link, "requestBody"); let description: string = this.consume(link, "description"); let server: any = this.consume(link, "server"); if (this.isDefined($ref)) { linkModel.$ref = $ref; } if (this.isDefined(operationRef)) { linkModel.operationRef = operationRef; } if (this.isDefined(operationId)) { linkModel.operationId = operationId; } if (this.isDefined(parameters)) { for (let name in parameters) { let expression: any = parameters[name]; linkModel.addLinkParameter(name, expression); } } if (this.isDefined(requestBody)) { let linkRequestBodyExpressionModel: Oas30LinkRequestBodyExpression = linkModel.createLinkRequestBodyExpression(requestBody); linkModel.requestBody = linkRequestBodyExpressionModel; } if (this.isDefined(description)) { linkModel.description = description; } if (this.isDefined(server)) { let serverModel: Oas30Server = linkModel.createServer(); this.readServer(server, serverModel); linkModel.server = serverModel; } this.readExtensions(link, linkModel); this.readExtraProperties(link, linkModel); } /** * Reads an OAS 3.0 Schema object from the given js data. * @param schema * @param schemaModel */ public readSchema(schema: any, schemaModel: Oas30Schema): void { super.readSchema(schema, schemaModel, false); let oneOf: any[] = this.consume(schema, "oneOf"); let anyOf: any[] = this.consume(schema, "anyOf"); let not: any = this.consume(schema, "not"); let discriminator: any = this.consume(schema, "discriminator"); let nullable: boolean = this.consume(schema, "nullable"); let writeOnly: boolean = this.consume(schema, "writeOnly"); let deprecated: boolean = this.consume(schema, "deprecated"); if (this.isDefined(discriminator)) { let discriminatorModel: Oas30Discriminator = schemaModel.createDiscriminator(); this.readDiscriminator(discriminator, discriminatorModel); schemaModel.discriminator = discriminatorModel; } if (this.isDefined(oneOf)) { let schemaModels: OasSchema[] = []; for (let oneOfSchema of oneOf) { let oneOfSchemaModel: OasSchema = schemaModel.createOneOfSchema(); this.readSchema(oneOfSchema, oneOfSchemaModel as Oas30Schema); schemaModels.push(oneOfSchemaModel); } schemaModel.oneOf = schemaModels; } if (this.isDefined(anyOf)) { let schemaModels: OasSchema[] = []; for (let anyOfSchema of anyOf) { let anyOfSchemaModel: OasSchema = schemaModel.createAnyOfSchema(); this.readSchema(anyOfSchema, anyOfSchemaModel as Oas30Schema); schemaModels.push(anyOfSchemaModel); } schemaModel.anyOf = schemaModels; } if (this.isDefined(not)) { let notSchema: OasSchema = schemaModel.createNotSchema(); this.readSchema(not, notSchema as Oas30Schema); schemaModel.not = notSchema; } if (this.isDefined(nullable)) { schemaModel.nullable = nullable; } if (this.isDefined(writeOnly)) { schemaModel.writeOnly = writeOnly; } if (this.isDefined(deprecated)) { schemaModel.deprecated = deprecated; } this.readExtraProperties(schema, schemaModel); } /** * Reads a OAS 3.0 Server object from the given javascript data. * @param server * @param serverModel */ public readServer(server: any, serverModel: Oas30Server): void { let url: string = this.consume(server, "url"); let description: string = this.consume(server, "description"); let variables: any = this.consume(server, "variables"); if (this.isDefined(url)) { serverModel.url = url; } if (this.isDefined(description)) { serverModel.description = description; } if (this.isDefined(variables)) { for (let name in variables) { let serverVariable: any = variables[name]; let serverVariableModel: Oas30ServerVariable = serverModel.createServerVariable(name); this.readServerVariable(serverVariable, serverVariableModel); serverModel.addServerVariable(name, serverVariableModel); } } this.readExtensions(server, serverModel); this.readExtraProperties(server, serverModel); } /** * Reads an OAS 3.0 Server Variable object from the given JS data. * @param serverVariable * @param serverVariableModel */ public readServerVariable(serverVariable: any, serverVariableModel: Oas30ServerVariable): void { let _enum: string[] = this.consume(serverVariable, "enum"); let _default: string = this.consume(serverVariable, "default"); let description: any = this.consume(serverVariable, "description"); if (Array.isArray(_enum)) { serverVariableModel.enum = _enum; } if (this.isDefined(_default)) { serverVariableModel.default = _default; } if (this.isDefined(description)) { serverVariableModel.description = description; } this.readExtensions(serverVariable, serverVariableModel); this.readExtraProperties(serverVariable, serverVariableModel); } /** * Reads an OAS 3.0 Discriminator object from the given JS data. * @param discriminator * @param discriminatorModel */ public readDiscriminator(discriminator: any, discriminatorModel: Oas30Discriminator) { let propertyName: string = this.consume(discriminator, "propertyName"); let mapping: any = this.consume(discriminator, "mapping"); if (this.isDefined(propertyName)) { discriminatorModel.propertyName = propertyName; } if (this.isDefined(mapping)) { discriminatorModel.mapping = mapping; } this.readExtensions(discriminator, discriminatorModel); this.readExtraProperties(discriminator, discriminatorModel); } }
the_stack
import { IConfusionMatrixagglomeratedMetricStructure } from "./IConfusionMatrixagglomeratedMetricStructure"; import { IConfusionMatrixBaseMetrics } from "./IConfusionMatrixBaseMetrics"; import { IConfusionMatrixBaseMicroAverageMetrics } from "./IConfusionMatrixBaseMicroAverageMetrics"; import { IConfusionMatrixMeanDerivedMetrics } from "./IConfusionMatrixMeanDerivedMetrics"; import { IConfusionMatrixMeanDerivedWeightedMetrics } from "./IConfusionMatrixMeanDerivedWeightedMetrics"; import { IConfusionMatrixMeanMetrics } from "./IConfusionMatrixMeanMetrics"; import { IConfusionMatrixQuantileMetrics } from "./IConfusionMatrixQuantileMetrics"; import { IConfusionMatrixSummationMetrics } from "./IConfusionMatrixSummationMetrics"; import { IConfusionMatrix } from "./IConfusionMatrix"; import { BinaryConfusionMatrix } from "./BinaryConfusionMatrix"; import { DictionaryMapUtility } from "../../data_structure/DictionaryMapUtility"; import { StructValueCount } from "../../label_structure/StructValueCount"; import { Utility } from "../../utility/Utility"; export abstract class ConfusionMatrixBase implements IConfusionMatrix { protected labels: string[] = []; protected labelMap: Map<string, number> = new Map<string, number>(); constructor( labels: string[], labelMap: Map<string, number>) { this.resetLabelsAndMap(labels, labelMap); } public abstract reset(): void; public generateConfusionMatrixMetricStructure( quantileConfiguration: number = 4): IConfusionMatrixagglomeratedMetricStructure { const confusionMatrix: IConfusionMatrix = this; const crossValidationBinaryConfusionMatrix: BinaryConfusionMatrix[] = confusionMatrix.getBinaryConfusionMatrices(); const labelMap: Map<string, number> = confusionMatrix.getLabelMap(); const labelBinaryConfusionMatrixBasicMetricMap: Map<string, Map<string, number>> = new Map<string, Map<string, number>>(); labelMap.forEach((value: number, key: string) => { labelBinaryConfusionMatrixBasicMetricMap.set( key, crossValidationBinaryConfusionMatrix[value].getBasicMetrics()); }); const labelBinaryConfusionMatrixMap: Map<string, BinaryConfusionMatrix> = new Map<string, BinaryConfusionMatrix>(); labelMap.forEach((value: number, key: string) => { labelBinaryConfusionMatrixMap.set( key, crossValidationBinaryConfusionMatrix[value]); }); const binaryConfusionMatrices: BinaryConfusionMatrix[] = confusionMatrix.getBinaryConfusionMatrices(); const microQuantileMetrics: IConfusionMatrixQuantileMetrics = confusionMatrix.getMicroQuantileMetrics(binaryConfusionMatrices, quantileConfiguration); const macroQuantileMetrics: IConfusionMatrixQuantileMetrics = confusionMatrix.getMacroQuantileMetrics(binaryConfusionMatrices, quantileConfiguration); const microAverageMetricArray: IConfusionMatrixBaseMicroAverageMetrics = confusionMatrix.getMicroAverageMetrics(binaryConfusionMatrices); const accuracy: number = microAverageMetricArray.averagePrecisionRecallF1Accuracy; const truePositives: number = microAverageMetricArray.truePositives; const falsePositives: number = microAverageMetricArray.falsePositives; const falseNegatives: number = microAverageMetricArray.falseNegatives; const supportMicroAverage: number = microAverageMetricArray.total; const microAverageMetrics: IConfusionMatrixBaseMetrics = { // tslint:disable-next-line: object-literal-key-quotes "accuracy": accuracy, // tslint:disable-next-line: object-literal-key-quotes "truePositives": truePositives, // tslint:disable-next-line: object-literal-key-quotes "falsePositives": falsePositives, // tslint:disable-next-line: object-literal-key-quotes "falseNegatives": falseNegatives, // tslint:disable-next-line: object-literal-key-quotes "total": supportMicroAverage }; const summationMicroAverageMetricArray: IConfusionMatrixSummationMetrics = confusionMatrix.getSummationMicroAverageMetrics(binaryConfusionMatrices); const summationPrecision: number = summationMicroAverageMetricArray.summationPrecision; const summationRecall: number = summationMicroAverageMetricArray.summationRecall; const summationF1Score: number = summationMicroAverageMetricArray.summationF1Score; const summationAccuracy: number = summationMicroAverageMetricArray.summationAccuracy; const summationTruePositives: number = summationMicroAverageMetricArray.summationTruePositives; const summationFalsePositives: number = summationMicroAverageMetricArray.summationFalsePositives; const summationTrueNegatives: number = summationMicroAverageMetricArray.summationTrueNegatives; const summationFalseNegatives: number = summationMicroAverageMetricArray.summationFalseNegatives; const summationSupport: number = summationMicroAverageMetricArray.summationSupport; const total: number = summationMicroAverageMetricArray.total; const summationMicroAverageMetrics: IConfusionMatrixSummationMetrics = { // tslint:disable-next-line: object-literal-key-quotes "summationPrecision": summationPrecision, // tslint:disable-next-line: object-literal-key-quotes "summationRecall": summationRecall, // tslint:disable-next-line: object-literal-key-quotes "summationF1Score": summationF1Score, // tslint:disable-next-line: object-literal-key-quotes "summationAccuracy": summationAccuracy, // tslint:disable-next-line: object-literal-key-quotes "summationTruePositives": summationTruePositives, // tslint:disable-next-line: object-literal-key-quotes "summationFalsePositives": summationFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "summationTrueNegatives": summationTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "summationFalseNegatives": summationFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "summationSupport": summationSupport, // tslint:disable-next-line: object-literal-key-quotes "total": total }; const macroAverageMetricArray: IConfusionMatrixMeanMetrics = confusionMatrix.getMacroAverageMetrics(binaryConfusionMatrices); const averagePrecision: number = macroAverageMetricArray.averagePrecision; const averageRecall: number = macroAverageMetricArray.averageRecall; const averageF1Score: number = macroAverageMetricArray.averageF1Score; const averageAccuracy: number = macroAverageMetricArray.averageAccuracy; const averageTruePositives: number = macroAverageMetricArray.averageTruePositives; const averageFalsePositives: number = macroAverageMetricArray.averageFalsePositives; const averageTrueNegatives: number = macroAverageMetricArray.averageTrueNegatives; const averageFalseNegatives: number = macroAverageMetricArray.averageFalseNegatives; const averageSupport: number = macroAverageMetricArray.averageSupport; const supportMacroAverage: number = macroAverageMetricArray.total; const macroAverageMetrics: IConfusionMatrixMeanMetrics = { // tslint:disable-next-line: object-literal-key-quotes "averagePrecision": averagePrecision, // tslint:disable-next-line: object-literal-key-quotes "averageRecall": averageRecall, // tslint:disable-next-line: object-literal-key-quotes "averageF1Score": averageF1Score, // tslint:disable-next-line: object-literal-key-quotes "averageAccuracy": averageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "averageTruePositives": averageTruePositives, // tslint:disable-next-line: object-literal-key-quotes "averageFalsePositives": averageFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "averageTrueNegatives": averageTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageFalseNegatives": averageFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageSupport": averageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": supportMacroAverage }; const summationMacroAverageMetricArray: IConfusionMatrixMeanMetrics = confusionMatrix.getSummationMacroAverageMetrics(binaryConfusionMatrices); const summationAveragePrecision: number = summationMacroAverageMetricArray.averagePrecision; const summationAverageRecall: number = summationMacroAverageMetricArray.averageRecall; const summationAverageF1Score: number = summationMacroAverageMetricArray.averageF1Score; const summationAverageAccuracy: number = summationMacroAverageMetricArray.averageAccuracy; const summationAverageTruePositives: number = summationMacroAverageMetricArray.averageTruePositives; const summationAverageFalsePositives: number = summationMacroAverageMetricArray.averageFalsePositives; const summationAverageTrueNegatives: number = summationMacroAverageMetricArray.averageTrueNegatives; const summationAverageFalseNegatives: number = summationMacroAverageMetricArray.averageFalseNegatives; const summationAverageSupport: number = summationMacroAverageMetricArray.averageSupport; const summationSupportMacroAverage: number = summationMacroAverageMetricArray.total; const summationMacroAverageMetrics: IConfusionMatrixMeanMetrics = { // tslint:disable-next-line: object-literal-key-quotes "averagePrecision": summationAveragePrecision, // tslint:disable-next-line: object-literal-key-quotes "averageRecall": summationAverageRecall, // tslint:disable-next-line: object-literal-key-quotes "averageF1Score": summationAverageF1Score, // tslint:disable-next-line: object-literal-key-quotes "averageAccuracy": summationAverageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "averageTruePositives": summationAverageTruePositives, // tslint:disable-next-line: object-literal-key-quotes "averageFalsePositives": summationAverageFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "averageTrueNegatives": summationAverageTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageFalseNegatives": summationAverageFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageSupport": summationAverageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": summationSupportMacroAverage }; const positiveSupportLabelMacroAverageMetricArray: IConfusionMatrixMeanMetrics = confusionMatrix.getPositiveSupportLabelMacroAverageMetrics(binaryConfusionMatrices); const positiveSupportLabelAveragePrecision: number = positiveSupportLabelMacroAverageMetricArray.averagePrecision; const positiveSupportLabelAverageRecall: number = positiveSupportLabelMacroAverageMetricArray.averageRecall; const positiveSupportLabelAverageF1Score: number = positiveSupportLabelMacroAverageMetricArray.averageF1Score; const positiveSupportLabelAverageAccuracy: number = positiveSupportLabelMacroAverageMetricArray.averageAccuracy; const positiveSupportLabelAverageTruePositives: number = positiveSupportLabelMacroAverageMetricArray.averageTruePositives; const positiveSupportLabelAverageFalsePositives: number = positiveSupportLabelMacroAverageMetricArray.averageFalsePositives; const positiveSupportLabelAverageTrueNegatives: number = positiveSupportLabelMacroAverageMetricArray.averageTrueNegatives; const positiveSupportLabelAverageFalseNegatives: number = positiveSupportLabelMacroAverageMetricArray.averageFalseNegatives; const positiveSupportLabelAverageSupport: number = positiveSupportLabelMacroAverageMetricArray.averageSupport; const positiveSupportLabelSupportMacroAverage: number = positiveSupportLabelMacroAverageMetricArray.total; const positiveSupportLabelMacroAverageMetrics: IConfusionMatrixMeanMetrics = { // tslint:disable-next-line: object-literal-key-quotes "averagePrecision": positiveSupportLabelAveragePrecision, // tslint:disable-next-line: object-literal-key-quotes "averageRecall": positiveSupportLabelAverageRecall, // tslint:disable-next-line: object-literal-key-quotes "averageF1Score": positiveSupportLabelAverageF1Score, // tslint:disable-next-line: object-literal-key-quotes "averageAccuracy": positiveSupportLabelAverageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "averageTruePositives": positiveSupportLabelAverageTruePositives, // tslint:disable-next-line: object-literal-key-quotes "averageFalsePositives": positiveSupportLabelAverageFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "averageTrueNegatives": positiveSupportLabelAverageTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageFalseNegatives": positiveSupportLabelAverageFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageSupport": positiveSupportLabelAverageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": positiveSupportLabelSupportMacroAverage }; const positiveSupportLabelSummationMacroAverageMetricArray: IConfusionMatrixMeanMetrics = confusionMatrix.getPositiveSupportLabelSummationMacroAverageMetrics(binaryConfusionMatrices); const positiveSupportLabelSummationAveragePrecision: number = positiveSupportLabelSummationMacroAverageMetricArray.averagePrecision; const positiveSupportLabelSummationAverageRecall: number = positiveSupportLabelSummationMacroAverageMetricArray.averageRecall; const positiveSupportLabelSummationAverageF1Score: number = positiveSupportLabelSummationMacroAverageMetricArray.averageF1Score; const positiveSupportLabelSummationAverageAccuracy: number = positiveSupportLabelSummationMacroAverageMetricArray.averageAccuracy; const positiveSupportLabelSummationAverageTruePositives: number = positiveSupportLabelSummationMacroAverageMetricArray.averageTruePositives; const positiveSupportLabelSummationAverageFalsePositives: number = positiveSupportLabelSummationMacroAverageMetricArray.averageFalsePositives; const positiveSupportLabelSummationAverageTrueNegatives: number = positiveSupportLabelSummationMacroAverageMetricArray.averageTrueNegatives; const positiveSupportLabelSummationAverageFalseNegatives: number = positiveSupportLabelSummationMacroAverageMetricArray.averageFalseNegatives; const positiveSupportLabelSummationAverageSupport: number = positiveSupportLabelSummationMacroAverageMetricArray.averageSupport; const positiveSupportLabelSummationSupportMacroAverage: number = positiveSupportLabelSummationMacroAverageMetricArray.total; const positiveSupportLabelSummationMacroAverageMetrics: IConfusionMatrixMeanMetrics = { // tslint:disable-next-line: object-literal-key-quotes "averagePrecision": positiveSupportLabelSummationAveragePrecision, // tslint:disable-next-line: object-literal-key-quotes "averageRecall": positiveSupportLabelSummationAverageRecall, // tslint:disable-next-line: object-literal-key-quotes "averageF1Score": positiveSupportLabelSummationAverageF1Score, // tslint:disable-next-line: object-literal-key-quotes "averageAccuracy": positiveSupportLabelSummationAverageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "averageTruePositives": positiveSupportLabelSummationAverageTruePositives, // tslint:disable-next-line: object-literal-key-quotes "averageFalsePositives": positiveSupportLabelSummationAverageFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "averageTrueNegatives": positiveSupportLabelSummationAverageTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageFalseNegatives": positiveSupportLabelSummationAverageFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageSupport": positiveSupportLabelSummationAverageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": positiveSupportLabelSummationSupportMacroAverage }; const weightedMacroAverageMetricArray: IConfusionMatrixMeanDerivedMetrics = confusionMatrix.getWeightedMacroAverageMetrics(binaryConfusionMatrices); const weightedAveragePrecision: number = weightedMacroAverageMetricArray.averagePrecision; const weightedAverageRecall: number = weightedMacroAverageMetricArray.averageRecall; const weightedAverageF1Score: number = weightedMacroAverageMetricArray.averageF1Score; const weightedAverageAccuracy: number = weightedMacroAverageMetricArray.averageAccuracy; const weightedAverageSupport: number = weightedMacroAverageMetricArray.averageSupport; const supportWeightedMacroAverage: number = weightedMacroAverageMetricArray.total; const weightedMacroAverageMetrics: IConfusionMatrixMeanDerivedWeightedMetrics = { // tslint:disable-next-line: object-literal-key-quotes "weightedAveragePrecision": weightedAveragePrecision, // tslint:disable-next-line: object-literal-key-quotes "weightedAverageRecall": weightedAverageRecall, // tslint:disable-next-line: object-literal-key-quotes "weightedAverageF1Score": weightedAverageF1Score, // tslint:disable-next-line: object-literal-key-quotes "weightedAverageAccuracy": weightedAverageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "weightedAverageSupport": weightedAverageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": supportWeightedMacroAverage }; const summationWeightedMacroAverageMetricArray: IConfusionMatrixMeanMetrics = confusionMatrix.getSummationWeightedMacroAverageMetrics(binaryConfusionMatrices); const summationWeightedAveragePrecision: number = summationWeightedMacroAverageMetricArray.averagePrecision; const summationWeightedAverageRecall: number = summationWeightedMacroAverageMetricArray.averageRecall; const summationWeightedAverageF1Score: number = summationWeightedMacroAverageMetricArray.averageF1Score; const summationWeightedAverageAccuracy: number = summationWeightedMacroAverageMetricArray.averageAccuracy; const summationWeightedAverageTruePositives: number = summationWeightedMacroAverageMetricArray.averageTruePositives; const summationWeightedAverageFalsePositives: number = summationWeightedMacroAverageMetricArray.averageFalsePositives; const summationWeightedAverageTrueNegatives: number = summationWeightedMacroAverageMetricArray.averageTrueNegatives; const summationWeightedAverageFalseNegatives: number = summationWeightedMacroAverageMetricArray.averageFalseNegatives; const summationWeightedAverageSupport: number = summationWeightedMacroAverageMetricArray.averageSupport; const summationWeightedSupportMacroAverage: number = summationWeightedMacroAverageMetricArray.total; const summationWeightedMacroAverageMetrics: IConfusionMatrixMeanMetrics = { // tslint:disable-next-line: object-literal-key-quotes "averagePrecision": summationWeightedAveragePrecision, // tslint:disable-next-line: object-literal-key-quotes "averageRecall": summationWeightedAverageRecall, // tslint:disable-next-line: object-literal-key-quotes "averageF1Score": summationWeightedAverageF1Score, // tslint:disable-next-line: object-literal-key-quotes "averageAccuracy": summationWeightedAverageAccuracy, // tslint:disable-next-line: object-literal-key-quotes "averageTruePositives": summationWeightedAverageTruePositives, // tslint:disable-next-line: object-literal-key-quotes "averageFalsePositives": summationWeightedAverageFalsePositives, // tslint:disable-next-line: object-literal-key-quotes "averageTrueNegatives": summationWeightedAverageTrueNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageFalseNegatives": summationWeightedAverageFalseNegatives, // tslint:disable-next-line: object-literal-key-quotes "averageSupport": summationWeightedAverageSupport, // tslint:disable-next-line: object-literal-key-quotes "total": summationWeightedSupportMacroAverage }; const confusionMatrixMetricStructure: IConfusionMatrixagglomeratedMetricStructure = { microQuantileMetrics, macroQuantileMetrics, confusionMatrix, labelBinaryConfusionMatrixBasicMetricMap, labelBinaryConfusionMatrixMap, microAverageMetrics, summationMicroAverageMetrics, macroAverageMetrics, summationMacroAverageMetrics, positiveSupportLabelMacroAverageMetrics, positiveSupportLabelSummationMacroAverageMetrics, weightedMacroAverageMetrics, summationWeightedMacroAverageMetrics }; return confusionMatrixMetricStructure; } public getNumberLabels(): number { return this.labels.length; } public getLabels(): string[] { return this.labels; } public getLabelMap(): Map<string, number> { return this.labelMap; } public abstract getBinaryConfusionMatrices(): BinaryConfusionMatrix[]; public getTotal(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): number { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const total: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getPositives(), 0); return total; } public getMicroQuantileMetrics( binaryConfusionMatrices: BinaryConfusionMatrix[] = [], quantileConfiguration: number = 4): IConfusionMatrixQuantileMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const precisions: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getPrecision(), x.getSupport())); const quantilesPrecisions: number[] = Utility.findValueCountPairQuantiles(precisions, quantileConfiguration) as number[]; const recalls: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getRecall(), x.getSupport())); const quantilesRecalls: number[] = Utility.findValueCountPairQuantiles(recalls, quantileConfiguration) as number[]; const f1Scores: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getF1Score(), x.getSupport())); const quantilesF1Scores: number[] = Utility.findValueCountPairQuantiles(f1Scores, quantileConfiguration) as number[]; const truePositives: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getTruePositives(), x.getSupport())); const quantilesTruePositives: number[] = Utility.findValueCountPairQuantiles(truePositives, quantileConfiguration) as number[]; const falsePositives: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getFalsePositives(), x.getSupport())); const quantilesFalsePositives: number[] = Utility.findValueCountPairQuantiles(falsePositives, quantileConfiguration) as number[]; const trueNegatives: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getTrueNegatives(), x.getSupport())); const quantilesTrueNegatives: number[] = Utility.findValueCountPairQuantiles(trueNegatives, quantileConfiguration) as number[]; const falseNegatives: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getFalseNegatives(), x.getSupport())); const quantilesFalseNegatives: number[] = Utility.findValueCountPairQuantiles(falseNegatives, quantileConfiguration) as number[]; const accuracies: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getAccuracy(), x.getSupport())); const quantilesAccuracies: number[] = Utility.findValueCountPairQuantiles(accuracies, quantileConfiguration) as number[]; const supports: StructValueCount[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => new StructValueCount(x.getSupport(), x.getSupport())); const quantilesSupports: number[] = Utility.findValueCountPairQuantiles(supports, quantileConfiguration) as number[]; const microQuantileMetrics: IConfusionMatrixQuantileMetrics = { quantilesPrecisions, quantilesRecalls, quantilesF1Scores, quantilesTruePositives, quantilesFalsePositives, quantilesTrueNegatives, quantilesFalseNegatives, quantilesAccuracies, quantilesSupports, total}; return microQuantileMetrics; } public getMacroQuantileMetrics( binaryConfusionMatrices: BinaryConfusionMatrix[] = [], quantileConfiguration: number = 4): IConfusionMatrixQuantileMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const precisions: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getPrecision()); const quantilesPrecisions: number[] = Utility.findQuantiles(precisions, quantileConfiguration) as number[]; const recalls: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getRecall()); const quantilesRecalls: number[] = Utility.findQuantiles(recalls, quantileConfiguration) as number[]; const f1Scores: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getF1Score()); const quantilesF1Scores: number[] = Utility.findQuantiles(f1Scores, quantileConfiguration) as number[]; const truePositives: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getTruePositives()); const quantilesTruePositives: number[] = Utility.findQuantiles(truePositives, quantileConfiguration) as number[]; const falsePositives: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getFalsePositives()); const quantilesFalsePositives: number[] = Utility.findQuantiles(falsePositives, quantileConfiguration) as number[]; const trueNegatives: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getTrueNegatives()); const quantilesTrueNegatives: number[] = Utility.findQuantiles(trueNegatives, quantileConfiguration) as number[]; const falseNegatives: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getFalseNegatives()); const quantilesFalseNegatives: number[] = Utility.findQuantiles(falseNegatives, quantileConfiguration) as number[]; const accuracies: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getAccuracy()); const quantilesAccuracies: number[] = Utility.findQuantiles(accuracies, quantileConfiguration) as number[]; const supports: number[] = binaryConfusionMatrices.map( (x: BinaryConfusionMatrix) => x.getSupport()); const quantilesSupports: number[] = Utility.findQuantiles(supports, quantileConfiguration) as number[]; const macroQuantileMetrics: IConfusionMatrixQuantileMetrics = { quantilesPrecisions, quantilesRecalls, quantilesF1Scores, quantilesTruePositives, quantilesFalsePositives, quantilesTrueNegatives, quantilesFalseNegatives, quantilesAccuracies, quantilesSupports, total}; return macroQuantileMetrics; } public getMicroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixBaseMicroAverageMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const truePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTruePositives(), 0); const falsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalsePositives(), 0); const falseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalseNegatives(), 0); const averagePrecisionRecallF1Accuracy: number = truePositives / total; const microAverageMetrics: IConfusionMatrixBaseMicroAverageMetrics = { averagePrecisionRecallF1Accuracy, truePositives, falsePositives, falseNegatives, total }; return microAverageMetrics; } public getSummationMicroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixSummationMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const summationTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTruePositives(), 0); const summationFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalsePositives(), 0); const summationTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTrueNegatives(), 0); const summationFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalseNegatives(), 0); const summationArithmeticAverageTotal: number = summationTruePositives + summationFalsePositives + summationTrueNegatives + summationFalseNegatives; const summationArithmeticAveragePositives: number = summationTruePositives + summationFalseNegatives; const summationArithmeticAveragePredictedPositives: number = summationTruePositives + summationFalsePositives; const summationArithmeticAverageBinaryConfusionMatrix: BinaryConfusionMatrix = new BinaryConfusionMatrix( summationArithmeticAverageTotal, summationTruePositives, summationArithmeticAveragePositives, summationArithmeticAveragePredictedPositives); const summationPrecision: number = summationArithmeticAverageBinaryConfusionMatrix.getPrecision(); const summationRecall: number = summationArithmeticAverageBinaryConfusionMatrix.getRecall(); const summationF1Score: number = summationArithmeticAverageBinaryConfusionMatrix.getF1Score(); const summationAccuracy: number = summationArithmeticAverageBinaryConfusionMatrix.getAccuracy(); const summationSupport: number = summationArithmeticAverageBinaryConfusionMatrix.getSupport(); const total: number = summationArithmeticAverageTotal; const macroAverageMetrics: IConfusionMatrixSummationMetrics = { summationPrecision, summationRecall, summationF1Score, summationTruePositives, summationFalsePositives, summationTrueNegatives, summationFalseNegatives, summationAccuracy, summationSupport, total }; return macroAverageMetrics; } public getMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const numberLabels: number = binaryConfusionMatrices.length; const averagePrecision: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getPrecision(), 0) / numberLabels; const averageRecall: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getRecall(), 0) / numberLabels; const averageF1Score: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getF1Score(), 0) / numberLabels; const averageTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTruePositives(), 0) / numberLabels; const averageFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalsePositives(), 0) / numberLabels; const averageTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTrueNegatives(), 0) / numberLabels; const averageFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalseNegatives(), 0) / numberLabels; const averageAccuracy: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getAccuracy(), 0) / numberLabels; const averageSupport: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getSupport(), 0) / numberLabels; /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const macroAverageMetrics: IConfusionMatrixMeanMetrics = { averagePrecision, averageRecall, averageF1Score, averageTruePositives, averageFalsePositives, averageTrueNegatives, averageFalseNegatives, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public getSummationMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const numberLabels: number = binaryConfusionMatrices.length; /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const averageTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTruePositives(), 0) / numberLabels; const averageFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalsePositives(), 0) / numberLabels; const averageTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTrueNegatives(), 0) / numberLabels; const averageFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalseNegatives(), 0) / numberLabels; const summationArithmeticAverageTotal: number = averageTruePositives + averageFalsePositives + averageTrueNegatives + averageFalseNegatives; const summationArithmeticAveragePositives: number = averageTruePositives + averageFalseNegatives; const summationArithmeticAveragePredictedPositives: number = averageTruePositives + averageFalsePositives; const summationArithmeticAverageBinaryConfusionMatrix: BinaryConfusionMatrix = new BinaryConfusionMatrix( summationArithmeticAverageTotal, averageTruePositives, summationArithmeticAveragePositives, summationArithmeticAveragePredictedPositives); const averagePrecision: number = summationArithmeticAverageBinaryConfusionMatrix.getPrecision(); const averageRecall: number = summationArithmeticAverageBinaryConfusionMatrix.getRecall(); const averageF1Score: number = summationArithmeticAverageBinaryConfusionMatrix.getF1Score(); const averageAccuracy: number = summationArithmeticAverageBinaryConfusionMatrix.getAccuracy(); const averageSupport: number = summationArithmeticAverageBinaryConfusionMatrix.getSupport(); const macroAverageMetrics: IConfusionMatrixMeanMetrics = { averagePrecision, averageRecall, averageF1Score, averageTruePositives, averageFalsePositives, averageTrueNegatives, averageFalseNegatives, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public getPositiveSupportLabelMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const numberPositiveSupportLabels: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? 1 : 0), 0); const averagePrecision: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getPrecision() : 0), 0) / numberPositiveSupportLabels; const averageRecall: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getRecall() : 0), 0) / numberPositiveSupportLabels; const averageF1Score: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getF1Score() : 0), 0) / numberPositiveSupportLabels; const averageTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getTruePositives() : 0), 0) / numberPositiveSupportLabels; const averageFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getFalsePositives() : 0), 0) / numberPositiveSupportLabels; const averageTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getTrueNegatives() : 0), 0) / numberPositiveSupportLabels; const averageFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getFalseNegatives() : 0), 0) / numberPositiveSupportLabels; const averageAccuracy: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getAccuracy() : 0), 0) / numberPositiveSupportLabels; const averageSupport: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getSupport() : 0), 0) / numberPositiveSupportLabels; /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const macroAverageMetrics: IConfusionMatrixMeanMetrics = { averagePrecision, averageRecall, averageF1Score, averageTruePositives, averageFalsePositives, averageTrueNegatives, averageFalseNegatives, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public getPositiveSupportLabelSummationMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } const numberPositiveSupportLabels: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? 1 : 0), 0); /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const averageTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getTruePositives() : 0), 0) / numberPositiveSupportLabels; const averageFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getFalsePositives() : 0), 0) / numberPositiveSupportLabels; const averageTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getTrueNegatives() : 0), 0) / numberPositiveSupportLabels; const averageFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + (entry.getSupport() > 0 ? entry.getFalseNegatives() : 0), 0) / numberPositiveSupportLabels; const summationArithmeticAverageTotal: number = averageTruePositives + averageFalsePositives + averageTrueNegatives + averageFalseNegatives; const summationArithmeticAveragePositives: number = averageTruePositives + averageFalseNegatives; const summationArithmeticAveragePredictedPositives: number = averageTruePositives + averageFalsePositives; const summationArithmeticAverageBinaryConfusionMatrix: BinaryConfusionMatrix = new BinaryConfusionMatrix( summationArithmeticAverageTotal, averageTruePositives, summationArithmeticAveragePositives, summationArithmeticAveragePredictedPositives); const averagePrecision: number = summationArithmeticAverageBinaryConfusionMatrix.getPrecision(); const averageRecall: number = summationArithmeticAverageBinaryConfusionMatrix.getRecall(); const averageF1Score: number = summationArithmeticAverageBinaryConfusionMatrix.getF1Score(); const averageAccuracy: number = summationArithmeticAverageBinaryConfusionMatrix.getAccuracy(); const averageSupport: number = summationArithmeticAverageBinaryConfusionMatrix.getSupport(); const macroAverageMetrics: IConfusionMatrixMeanMetrics = { averagePrecision, averageRecall, averageF1Score, averageTruePositives, averageFalsePositives, averageTrueNegatives, averageFalseNegatives, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public getWeightedMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanDerivedMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const averagePrecision: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getPrecision() * entry.getPositives(), 0) / total; const averageRecall: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getRecall() * entry.getPositives(), 0) / total; const averageF1Score: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getF1Score() * entry.getPositives(), 0) / total; const averageAccuracy: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getAccuracy() * entry.getPositives(), 0) / total; const averageSupport: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getSupport() * entry.getPositives(), 0) / total; const macroAverageMetrics: IConfusionMatrixMeanDerivedMetrics = { averagePrecision, averageRecall, averageF1Score, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public getSummationWeightedMacroAverageMetrics(binaryConfusionMatrices: BinaryConfusionMatrix[] = []): IConfusionMatrixMeanMetrics { if (Utility.isEmptyArray(binaryConfusionMatrices)) { binaryConfusionMatrices = this.getBinaryConfusionMatrices(); } /** ---- NOTE-use-getTotal() ---- * const total: number = * binaryConfusionMatrices.reduce( * (accumulation, entry) => accumulation + entry.getPositives(), 0); */ const total: number = this.getTotal(binaryConfusionMatrices); const averageTruePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTruePositives() * entry.getPositives(), 0) / total; const averageFalsePositives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalsePositives() * entry.getPositives(), 0) / total; const averageTrueNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getTrueNegatives() * entry.getPositives(), 0) / total; const averageFalseNegatives: number = binaryConfusionMatrices.reduce( (accumulation, entry) => accumulation + entry.getFalseNegatives() * entry.getPositives(), 0) / total; const summationWeightedAverageTotal: number = averageTruePositives + averageFalsePositives + averageTrueNegatives + averageFalseNegatives; const summationWeightedAveragePositives: number = averageTruePositives + averageFalseNegatives; const summationWeightedAveragePredictedPositives: number = averageTruePositives + averageFalsePositives; const summationWeightedAverageBinaryConfusionMatrix: BinaryConfusionMatrix = new BinaryConfusionMatrix( summationWeightedAverageTotal, averageTruePositives, summationWeightedAveragePositives, summationWeightedAveragePredictedPositives); const averagePrecision: number = summationWeightedAverageBinaryConfusionMatrix.getPrecision(); const averageRecall: number = summationWeightedAverageBinaryConfusionMatrix.getRecall(); const averageF1Score: number = summationWeightedAverageBinaryConfusionMatrix.getF1Score(); const averageAccuracy: number = summationWeightedAverageBinaryConfusionMatrix.getAccuracy(); const averageSupport: number = summationWeightedAverageBinaryConfusionMatrix.getSupport(); const macroAverageMetrics: IConfusionMatrixMeanMetrics = { averagePrecision, averageRecall, averageF1Score, averageTruePositives, averageFalsePositives, averageTrueNegatives, averageFalseNegatives, averageAccuracy, averageSupport, total }; return macroAverageMetrics; } public validateLabelId( labelId: number, throwIfNotLegal: boolean = true): boolean { if (labelId < 0) { if (throwIfNotLegal) { Utility.debuggingThrow( `labelId=${labelId}, small than 0`); } return false; } if (labelId >= this.getNumberLabels()) { if (throwIfNotLegal) { Utility.debuggingThrow( `labelId=${labelId}, greater or equal to number of labels, ${this.getNumberLabels()}`); } return false; } return true; } public validateLabel( label: string, throwIfNotLegal: boolean = true): boolean { if (!this.getLabelMap().has(label)) { if (throwIfNotLegal) { Utility.debuggingThrow( `label=${label}, not int the label map=${DictionaryMapUtility.jsonStringifyStringKeyGenericValueNativeMap(this.getLabelMap())}`); } return false; } return true; } protected resetLabelsAndMap( labels: string[], labelMap: Map<string, number>): void { DictionaryMapUtility.validateStringArrayAndStringKeyNumberValueMap(labels, labelMap); this.labels = labels; this.labelMap = labelMap; } }
the_stack
import { CachingPoliciesProcessor } from '@src/cache/CachingPoliciesProcessor' import { CACHE_POINTER_PREFIX, IpcCacheOpCodes, IpcOpCodes, SerializeModes } from '@src/constants' import { CacheProvider, CacheStorageKey } from '@discordoo/providers' import { DiscordooError, resolveDiscordooShards } from '@src/utils' import { Client, ProviderConstructor } from '@src/core' import { EntityKey } from '@src/api/entities' import { IpcCacheClearRequestPacket, IpcCacheClearResponsePacket, IpcCacheCountRequestPacket, IpcCacheCountResponsePacket, IpcCacheCountsRequestPacket, IpcCacheCountsResponsePacket, IpcCacheDeleteRequestPacket, IpcCacheDeleteResponsePacket, IpcCacheFilterRequestPacket, IpcCacheFilterResponsePacket, IpcCacheFindRequestPacket, IpcCacheFindResponsePacket, IpcCacheForEachRequestPacket, IpcCacheForEachResponsePacket, IpcCacheGetRequestPacket, IpcCacheGetResponsePacket, IpcCacheHasRequestPacket, IpcCacheHasResponsePacket, IpcCacheMapRequestPacket, IpcCacheMapResponsePacket, IpcCacheSetRequestPacket, IpcCacheSetResponsePacket, IpcCacheSizeRequestPacket, IpcCacheSizeResponsePacket, IpcCacheSweepRequestPacket, IpcCacheSweepResponsePacket } from '@src/sharding/interfaces/ipc/IpcPackets' import { cacheProviderClearPolyfill, cacheProviderCountPolyfill, cacheProviderCountsPolyfill, cacheProviderFilterPolyfill, cacheProviderFindPolyfill, cacheProviderHasPolyfill, cacheProviderMapPolyfill, cacheProviderSizePolyfill, cacheProviderSweepPolyfill, } from '@src/cache/polyfills' import { CacheManagerClearOptions, CacheManagerCountOptions, CacheManagerCountsOptions, CacheManagerData, CacheManagerDeleteOptions, CacheManagerFilterOptions, CacheManagerFindOptions, CacheManagerForEachOptions, CacheManagerGetOptions, CacheManagerHasOptions, CacheManagerMapOptions, CacheManagerSetOptions, CacheManagerSizeOptions, CacheManagerSweepOptions, CacheOptions, CachePointer, } from '@src/cache/interfaces' import { EntitiesUtil } from '@src/api/entities/EntitiesUtil' import { toJson } from '@src/utils/toJson' import { isCachePointer } from '@src/utils/cachePointer' export class CacheManager<P extends CacheProvider = CacheProvider> { public client: Client public provider: P private readonly _policiesProcessor: CachingPoliciesProcessor constructor(client: Client, Provider: ProviderConstructor<P>, data: CacheManagerData) { this.client = client this.provider = new Provider(this.client, data.cacheOptions, data.providerOptions) this._policiesProcessor = new CachingPoliciesProcessor(this.client) } async get<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, key: K, options: CacheManagerGetOptions & { __ddcp?: boolean } = {} ): Promise<V | undefined> { let result: any if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheGetRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.GET, event_id: this.client.internals.ipc.generate(), key, keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, serialize: SerializeModes.ANY } } const { d: response } = await this.client.internals.ipc.send<IpcCacheGetResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { result = await this.provider.get<K, V>(keyspace, options?.storage ?? storage, key) } const pointer = isCachePointer(result) if (pointer) { // __ddcp option means that previous value are cache pointer. cache pointer cannot point to another cache pointer. if (options.__ddcp) { console.log('recursive cache pointer', pointer) return undefined } console.log('get pointer', pointer) return this.get(pointer[0], pointer[1], entityKey, pointer[2], { ...options, storage: pointer[1], __ddcp: true }) } result = await this._prepareData('out', result, entityKey) return result } async set<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, policy: keyof CacheOptions = 'global', key: K, value: V | CachePointer, options: CacheManagerSetOptions = {} ): Promise<this> { if (typeof value !== 'object' && typeof value !== 'string'!) { throw new DiscordooError( 'CacheManager#set', 'Cache cannot operate with anything expect objects. Received', value === null ? 'null' : typeof value ) } let limited = false, shouldClear = true /** * When entityKey is unknown or value is a cachePointer, do not apply cache policies. * When the global cache policy allows or does not allow writing, use only this value. * When the global cache policy is not in effect, use the specified cache policy. * If any cache policy prohibits writing, clear the existing cache. * */ if (entityKey !== 'any') { const pointer = isCachePointer(value) if (pointer) { const allowed = await this.has(pointer[0], pointer[1], pointer[2]) limited = !allowed shouldClear = limited } else { const globalAllowed = await this._policiesProcessor.global(value) if (globalAllowed !== undefined) { limited = !globalAllowed } else { limited = !(await this._policiesProcessor[policy](value)) } } } if (limited) { if (shouldClear) await this.delete(keyspace, storage, key, options) return this } const data = await this._prepareData('in', value, entityKey, this.isShardedRequest(options)) if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheSetRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.SET, event_id: this.client.internals.ipc.generate(), key, keyspace, storage: options.storage ?? storage, entity_key: entityKey, shards, policy, value: data, serialize: SerializeModes.BOOLEAN } } const { d: response } = await this.client.internals.ipc.send<IpcCacheSetResponsePacket>(request, { waitResponse: true }) if (!response.success) { throw new DiscordooError(...response.result) } } else { await this.provider.set<K, V>(keyspace, options.storage ?? storage, key, data) } return this } async delete<K = string>( keyspace: string, storage: CacheStorageKey, key: K | K[], options: CacheManagerDeleteOptions = {} ): Promise<boolean> { if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheDeleteRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.DELETE, event_id: this.client.internals.ipc.generate(), key, keyspace, storage: options?.storage ?? storage, shards, serialize: SerializeModes.BOOLEAN } } const { d: response } = await this.client.internals.ipc.send<IpcCacheDeleteResponsePacket>(request, { waitResponse: true }) return response.success } else { return this.provider.delete<K>(keyspace, options?.storage ?? storage, key) } } async forEach<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (unknown | Promise<unknown>), options: CacheManagerForEachOptions = {} ): Promise<void> { if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheForEachRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.FOREACH, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})` } } await this.client.internals.ipc.send<IpcCacheForEachResponsePacket>(request, { waitResponse: true }) } else { await this.provider.forEach<K, V, P>(keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate)) } return undefined } async size( keyspace: string, storage: CacheStorageKey, options: CacheManagerSizeOptions = {} ): Promise<number> { let result = 0 if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheSizeRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.SIZE, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, shards, serialize: SerializeModes.NUMBER } } const { d: response } = await this.client.internals.ipc.send<IpcCacheSizeResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { if (this.provider.size) { result = await this.provider.size(keyspace, options?.storage ?? storage) } else { result = await cacheProviderSizePolyfill<P>(this.provider, keyspace, options?.storage ?? storage) } } return result } async has<K = string>( keyspace: string, storage: CacheStorageKey, key: K, options: CacheManagerHasOptions = {} ): Promise<boolean> { let result = false if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheHasRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.HAS, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, key, shards, serialize: SerializeModes.BOOLEAN } } const { d: response } = await this.client.internals.ipc.send<IpcCacheHasResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { if (this.provider.has) { result = await this.provider.has<K>(keyspace, options?.storage ?? storage, key) } else { result = await cacheProviderHasPolyfill<K, P>(this.provider, keyspace, options?.storage ?? storage, key) } } return result } async sweep<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (boolean | Promise<boolean>), options: CacheManagerSweepOptions = {} ): Promise<void> { if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheSweepRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.SWEEP, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})` } } await this.client.internals.ipc.send<IpcCacheSweepResponsePacket>(request, { waitResponse: true }) } else { if (this.provider.sweep) { await this.provider.sweep<K, V, P>(keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate)) } else { await cacheProviderSweepPolyfill<K, V, P>( this.provider, keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } } return undefined } async filter<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (boolean | Promise<boolean>), options: CacheManagerFilterOptions = {} ): Promise<[ K, V ][]> { let result: [ K, V ][] = [] if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheFilterRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.FILTER, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})`, serialize: SerializeModes.ARRAY } } const { d: response } = await this.client.internals.ipc.send<IpcCacheFilterResponsePacket>(request, { waitResponse: true }) if (response.success) { result = await Promise.all(response.result.map(this._makePredicate(entityKey, (v, k) => ([ k, v ])))) } } else { if (this.provider.filter) { result = await this.provider.filter<K, V, P>( keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } else { result = await cacheProviderFilterPolyfill<K, V, P>( this.provider, keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } } return result } async map<K = string, V = any, R = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (R | Promise<R>), options: CacheManagerMapOptions = {} ): Promise<R[]> { let result: R[] = [] if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheMapRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.MAP, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})`, serialize: SerializeModes.ARRAY } } const { d: response } = await this.client.internals.ipc.send<IpcCacheMapResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { if (this.provider.map) { result = await this.provider.map<K, V, R, P>( keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } else { result = await cacheProviderMapPolyfill<K, V, R, P>( this.provider, keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } } return result } async find<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (boolean | Promise<boolean>), options: CacheManagerFindOptions = {} ): Promise<V | undefined> { let result: V | undefined if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheFindRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.FIND, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})`, serialize: SerializeModes.ANY } } const { d: response } = await this.client.internals.ipc.send<IpcCacheFindResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { if (this.provider.find) { result = await this.provider.find<K, V, P> (keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } else { result = await cacheProviderFindPolyfill<K, V, P>( this.provider, keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } } result = await this._prepareData('out', result, entityKey) return result } async clear( keyspace: string, storage: CacheStorageKey, options: CacheManagerClearOptions = {} ): Promise<boolean> { if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheClearRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.CLEAR, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, shards, serialize: SerializeModes.BOOLEAN } } const { d: response } = await this.client.internals.ipc.send<IpcCacheClearResponsePacket>(request, { waitResponse: true }) return response.success } else { if (this.provider.clear) { return this.provider.clear(keyspace, options?.storage ?? storage) } else { return cacheProviderClearPolyfill<P>(this.provider, keyspace, options?.storage ?? storage) } } } async count<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicate: (value: V, key: K, provider: P) => (boolean | Promise<boolean>), options: CacheManagerCountOptions = {} ): Promise<number> { let result = 0 if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheCountRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.COUNT, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, script: `(${predicate})`, serialize: SerializeModes.NUMBER } } const { d: response } = await this.client.internals.ipc.send<IpcCacheCountResponsePacket>(request, { waitResponse: true }) if (response.success) { result = response.result } } else { if (this.provider.count) { result = await this.provider.count<K, V, P>( keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } else { result = await cacheProviderCountPolyfill<K, V, P>( this.provider, keyspace, options?.storage ?? storage, this._makePredicate(entityKey, predicate) ) } } return result } async counts<K = string, V = any>( keyspace: string, storage: CacheStorageKey, entityKey: EntityKey, predicates: ((value: V, key: K, provider: P) => (boolean | Promise<boolean>))[], options: CacheManagerCountsOptions = {} ): Promise<number[]> { let results: number[] = [] if (this.isShardedRequest(options)) { const shards = resolveDiscordooShards(this.client, options.shard!) const request: IpcCacheCountsRequestPacket = { op: IpcOpCodes.CACHE_OPERATE, d: { op: IpcCacheOpCodes.COUNTS, event_id: this.client.internals.ipc.generate(), keyspace, storage: options?.storage ?? storage, entity_key: entityKey, shards, scripts: predicates.map(p => (`(${p})`)), serialize: SerializeModes.NUMBERS_ARRAY } } const { d: response } = await this.client.internals.ipc.send<IpcCacheCountsResponsePacket>(request, { waitResponse: true }) if (response.success) { results = response.result } } else { if (this.provider.counts) { results = await this.provider.counts<K, V, P>( keyspace, options?.storage ?? storage, predicates.map(p => this._makePredicate(entityKey, p)) ) } else { results = await cacheProviderCountsPolyfill<K, V, P>( this.provider, keyspace, options?.storage ?? storage, predicates.map(p => this._makePredicate(entityKey, p)) ) } } return results } get [Symbol.for('_ddooPoliciesProcessor')](): CachingPoliciesProcessor { // for internal use by a library outside of this class return this._policiesProcessor } init() { return this.provider.init() } private isShardedRequest(options?: any): boolean { return typeof options.shard !== 'undefined' && this.client.internals.sharding.active && !this.provider.sharedCache } private _makePredicate(entityKey: EntityKey, predicate: any): any { return async (value, key, prov) => { return predicate(await this._prepareData('out', value, entityKey), key, prov) } } private async _prepareData(direction: 'in' | 'out', data: any, entityKey: EntityKey, forIpcRequest?: boolean): Promise<any> { if (forIpcRequest) return toJson(data) if (direction === 'in') { const pointer = isCachePointer(data) if (pointer || entityKey === 'any') { switch (this.provider.compatible) { case 'classes': case 'json': return toJson(data) case 'text': return toJson(data, true) case 'buffer': return Buffer.from(toJson(data, true)) } } const Entity: any = EntitiesUtil.get(entityKey, data) switch (this.provider.compatible) { case 'classes': if (!(data instanceof Entity)) data = await new Entity(this.client).init?.(data) break case 'json': data = toJson(data) break case 'text': data = toJson(data, true) break case 'buffer': data = Buffer.from(toJson(data, true)) break } return data } else if (direction === 'out') { let jsonOrEntity: any switch (this.provider.compatible) { case 'classes': case 'json': jsonOrEntity = data break case 'text': jsonOrEntity = data ? JSON.parse(data) : data break case 'buffer': jsonOrEntity = data ? JSON.parse(data.toString('utf8')) : data break } const pointer = isCachePointer(jsonOrEntity) if (pointer) { return await this.get(pointer[0], pointer[1], entityKey, pointer[2]) } if (entityKey === 'any') { return jsonOrEntity } if (jsonOrEntity) { const Entity: any = EntitiesUtil.get(entityKey, jsonOrEntity) if (!(jsonOrEntity instanceof Entity)) jsonOrEntity = await new Entity(this.client).init?.(jsonOrEntity) } return jsonOrEntity } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormOpportunityClose_Information { interface tab_resolution_Sections { information: DevKit.Controls.Section; } interface tab_resolution extends DevKit.Controls.ITab { Section: tab_resolution_Sections; } interface Tabs { resolution: tab_resolution; } interface Body { Tab: Tabs; /** Actual end time of the opportunity close activity. */ ActualEnd: DevKit.Controls.Date; /** Actual revenue generated for the opportunity. */ ActualRevenue: DevKit.Controls.Money; /** Unique identifier of the competitor with which the opportunity close activity is associated. */ CompetitorId: DevKit.Controls.Lookup; /** Activity that is created automatically when an opportunity is closed, containing information such as the description of the closing and actual revenue. */ Description: DevKit.Controls.String; } } class FormOpportunityClose_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form OpportunityClose_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 OpportunityClose_Information */ Body: DevKit.FormOpportunityClose_Information.Body; } namespace FormOpportunity_Close { interface tab_OpportunityClose_Sections { quickOpportunityClose_column1_section1: DevKit.Controls.Section; quickOpportunityClose_column2_section1: DevKit.Controls.Section; quickOpportunityClose_column3_section1: DevKit.Controls.Section; } interface tab_OpportunityClose extends DevKit.Controls.ITab { Section: tab_OpportunityClose_Sections; } interface Tabs { OpportunityClose: tab_OpportunityClose; } interface Body { Tab: Tabs; /** Actual end time of the opportunity close activity. */ ActualEnd: DevKit.Controls.Date; /** Actual revenue generated for the opportunity. */ ActualRevenue: DevKit.Controls.Money; /** Unique identifier of the competitor with which the opportunity close activity is associated. */ CompetitorId: DevKit.Controls.Lookup; /** Activity that is created automatically when an opportunity is closed, containing information such as the description of the closing and actual revenue. */ Description: DevKit.Controls.String; /** Unique identifier of the opportunity closed. */ OpportunityId: DevKit.Controls.Lookup; /** Status of the opportunity. */ OpportunityStateCode: DevKit.Controls.OptionSet; /** Status reason of the opportunity. */ OpportunityStatusCode: DevKit.Controls.OptionSet; /** Subject associated with the opportunity close activity. */ Subject: DevKit.Controls.String; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } } class FormOpportunity_Close extends DevKit.IForm { /** * DynamicsCrm.DevKit form Opportunity_Close * @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 Opportunity_Close */ Body: DevKit.FormOpportunity_Close.Body; } class OpportunityCloseApi { /** * DynamicsCrm.DevKit OpportunityCloseApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Additional information provided by the external application as JSON. For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the opportunity close activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Actual duration of the opportunity close activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Actual end time of the opportunity close activity. */ ActualEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Actual revenue generated for the opportunity. */ ActualRevenue: DevKit.WebApi.MoneyValue; /** Value of the Actual Revenue in base currency. */ ActualRevenue_Base: DevKit.WebApi.MoneyValueReadonly; /** Actual start time of the opportunity close activity. */ ActualStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Category of the opportunity close activity. */ Category: DevKit.WebApi.StringValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the competitor with which the opportunity close activity is associated. */ CompetitorId: DevKit.WebApi.LookupValue; /** Unique identifier of the user who created the opportunity close activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who created the record. */ CreatedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Date and time when the opportunity close activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the opportunityclose. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Activity that is created automatically when an opportunity is closed, containing information such as the description of the closing and actual revenue. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Information about whether the opportunity close activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information that specifies if the opportunity close activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of the user who last modified the opportunity close activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who modified the record. */ ModifiedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Date and time when the opportunity close activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the opportunityclose. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the opportunity closed. */ OpportunityId: DevKit.WebApi.LookupValue; /** Status of the opportunity. */ OpportunityStateCode: DevKit.WebApi.OptionSetValue; /** Status reason of the opportunity. */ OpportunityStatusCode: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of the activity. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_account_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebooking_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebookingheader_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bulkoperation_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaign_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaignactivity_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlement_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlementtemplate_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_incident_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_new_interactionforemail_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgearticle_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgebaserecord_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_lead_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_customerasset_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_playbookinstance_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_opportunity_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_site_opportunityclose: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Scheduled duration of the opportunity close activity, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValueReadonly; /** Scheduled end time of the opportunity close activity. */ ScheduledEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Scheduled start time of the opportunity close activity. */ ScheduledStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of the service with which the opportunity close activity is associated. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the opportunity close activity is open, completed, or canceled. By default, opportunity close activities are completed unless the opportunity is reactivated, which updates them to canceled. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the opportunity close activity. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Subcategory of the opportunity close activity. */ Subcategory: DevKit.WebApi.StringValue; /** Subject associated with the opportunity close activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace OpportunityClose { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum OpportunityStateCode { /** 2 */ Lost, /** 0 */ Open, /** 1 */ Won } enum OpportunityStatusCode { /** 4 */ Canceled, /** 1 */ In_Progress, /** 2 */ On_Hold, /** 5 */ Out_Sold, /** 3 */ Won } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open } enum StatusCode { /** 3 */ Canceled, /** 2 */ Completed, /** 1 */ Open } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Opportunity Close'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
export default class gLong { private low_ : number private high_ : number // A cache of the Long representations of small integer values. private static IntCache_: { [val: number]: gLong } = {} // Commonly used constant values. private static TWO_PWR_16_DBL_ = 1 << 16; private static TWO_PWR_24_DBL_ = 1 << 24; private static TWO_PWR_32_DBL_ = gLong.TWO_PWR_16_DBL_ * gLong.TWO_PWR_16_DBL_; private static TWO_PWR_31_DBL_ = gLong.TWO_PWR_32_DBL_ / 2; private static TWO_PWR_48_DBL_ = gLong.TWO_PWR_32_DBL_ * gLong.TWO_PWR_16_DBL_; private static TWO_PWR_64_DBL_ = gLong.TWO_PWR_32_DBL_ * gLong.TWO_PWR_32_DBL_; private static TWO_PWR_63_DBL_ = gLong.TWO_PWR_64_DBL_ / 2; /** * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Longs. * * The internal representation of a long is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @param {number} low The low (signed) 32 bits of the long. * @param {number} high The high (signed) 32 bits of the long. * @constructor */ constructor(low: number, high: number) { this.low_ = low | 0; // force into 32 signed bits. this.high_ = high | 0; // force into 32 signed bits. } /** * Returns a Long representing the given (32-bit) integer value. * @param {number} value The 32-bit integer in question. * @return {!gLong} The corresponding Long value. */ public static fromInt(value: number): gLong { if (-128 <= value && value < 128) { var cachedObj = gLong.IntCache_[value]; if (cachedObj) { return cachedObj; } } var obj = new gLong(value, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { gLong.IntCache_[value] = obj; } return obj; } public static ZERO = gLong.fromInt(0); public static ONE = gLong.fromInt(1); public static NEG_ONE = gLong.fromInt(-1); private static TWO_PWR_24_ = gLong.fromInt(gLong.TWO_PWR_24_DBL_); /** * Returns a Long representing the given value, provided that it is a finite * number. Otherwise, zero is returned. * @param {number} value The number in question. * @return {!gLong} The corresponding Long value. */ public static fromNumber(value: number): gLong { if (isNaN(value) || !isFinite(value)) { return gLong.ZERO; } else if (value <= -gLong.TWO_PWR_63_DBL_) { return gLong.MIN_VALUE; } else if (value + 1 >= gLong.TWO_PWR_63_DBL_) { return gLong.MAX_VALUE; } else if (value < 0) { return gLong.fromNumber(-value).negate(); } else { return new gLong( (value % gLong.TWO_PWR_32_DBL_) | 0, (value / gLong.TWO_PWR_32_DBL_) | 0); } } /** * Returns a Long representing the 64-bit integer that comes by concatenating * the given high and low bits. Each is assumed to use 32 bits. * @param {number} lowBits The low 32-bits. * @param {number} highBits The high 32-bits. * @return {!gLong} The corresponding Long value. */ public static fromBits(lowBits: number, highBits: number): gLong { return new gLong(lowBits, highBits); } public static MAX_VALUE = gLong.fromBits(0xFFFFFFFF, 0x7FFFFFFF); public static MIN_VALUE = gLong.fromBits(0, 0x80000000); /** * Returns a Long representation of the given string, written using the given * radix. * @param {string} str The textual representation of the Long. * @param {number=} opt_radix The radix in which the text is written. * @return {!gLong} The corresponding Long value. */ public static fromString(str: string, opt_radix?: number): gLong { if (str.length == 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) == '-') { return gLong.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = gLong.fromNumber(Math.pow(radix, 8)); var result = gLong.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = gLong.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(gLong.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(gLong.fromNumber(value)); } } return result; } /** @return {number} The value, assuming it is a 32-bit integer. */ public toInt(): number { return this.low_; } /** @return {number} The closest floating-point representation to this value. */ public toNumber(): number { return this.high_ * gLong.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); } /** * @param {number=} opt_radix The radix in which the text should be written. * @return {string} The textual representation of this value. */ public toString(opt_radix?: number): string { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(gLong.MIN_VALUE)) { // We need to change the Long value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixLong = gLong.fromNumber(radix); var div = this.div(radixLong); var rem = div.multiply(radixLong).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = gLong.fromNumber(Math.pow(radix, 6)); var rem: gLong = this; var result = ''; while (true) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } } /** @return {number} The high 32-bits as a signed value. */ public getHighBits(): number { return this.high_; } /** @return {number} The low 32-bits as a signed value. */ public getLowBits(): number { return this.low_; } /** @return {number} The low 32-bits as an unsigned value. */ public getLowBitsUnsigned(): number { return (this.low_ >= 0) ? this.low_ : gLong.TWO_PWR_32_DBL_ + this.low_; } /** * @return {number} Returns the number of bits needed to represent the absolute * value of this Long. */ public getNumBitsAbs(): number { if (this.isNegative()) { if (this.equals(gLong.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ != 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) != 0) { break; } } return this.high_ != 0 ? bit + 33 : bit + 1; } } /** @return {boolean} Whether this value is zero. */ public isZero(): boolean { return this.high_ == 0 && this.low_ == 0; } /** @return {boolean} Whether this value is negative. */ public isNegative(): boolean { return this.high_ < 0; } /** @return {boolean} Whether this value is odd. */ public isOdd(): boolean { return (this.low_ & 1) == 1; } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long equals the other. */ public equals(other: gLong): boolean { return (this.high_ == other.high_) && (this.low_ == other.low_); } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long does not equal the other. */ public notEquals(other: gLong): boolean { return (this.high_ != other.high_) || (this.low_ != other.low_); } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long is less than the other. */ public lessThan(other: gLong): boolean { return this.compare(other) < 0; } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long is less than or equal to the other. */ public lessThanOrEqual(other: gLong): boolean { return this.compare(other) <= 0; } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long is greater than the other. */ public greaterThan(other: gLong): boolean { return this.compare(other) > 0; } /** * @param {gLong} other Long to compare against. * @return {boolean} Whether this Long is greater than or equal to the other. */ public greaterThanOrEqual(other: gLong): boolean { return this.compare(other) >= 0; } /** * Compares this Long with the given one. * @param {gLong} other Long to compare against. * @return {number} 0 if they are the same, 1 if the this is greater, and -1 * if the given one is greater. */ public compare(other: gLong): number { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } } /** @return {!gLong} The negation of this value. */ public negate(): gLong { if (this.equals(gLong.MIN_VALUE)) { return gLong.MIN_VALUE; } else { return this.not().add(gLong.ONE); } } /** * Returns the sum of this and the given Long. * @param {gLong} other Long to add to this one. * @return {!gLong} The sum of this and the given Long. */ public add(other: gLong): gLong { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xFFFF; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xFFFF; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xFFFF; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xFFFF; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xFFFF; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xFFFF; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xFFFF; c48 += a48 + b48; c48 &= 0xFFFF; return gLong.fromBits((c16 << 16) | c00, (c48 << 16) | c32); } /** * Returns the difference of this and the given Long. * @param {gLong} other Long to subtract from this. * @return {!gLong} The difference of this and the given Long. */ public subtract(other: gLong): gLong { return this.add(other.negate()); } /** * Returns the product of this and the given long. * @param {gLong} other Long to multiply with this. * @return {!gLong} The product of this and the other. */ public multiply(other: gLong): gLong { if (this.isZero()) { return gLong.ZERO; } else if (other.isZero()) { return gLong.ZERO; } if (this.equals(gLong.MIN_VALUE)) { return other.isOdd() ? gLong.MIN_VALUE : gLong.ZERO; } else if (other.equals(gLong.MIN_VALUE)) { return this.isOdd() ? gLong.MIN_VALUE : gLong.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate().multiply(other).negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both longs are small, use float multiplication if (this.lessThan(gLong.TWO_PWR_24_) && other.lessThan(gLong.TWO_PWR_24_)) { return gLong.fromNumber(this.toNumber() * other.toNumber()); } // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xFFFF; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xFFFF; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xFFFF; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xFFFF; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xFFFF; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xFFFF; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xFFFF; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xFFFF; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xFFFF; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xFFFF; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xFFFF; return gLong.fromBits((c16 << 16) | c00, (c48 << 16) | c32); } /** * Returns this Long divided by the given one. * @param {gLong} other Long by which to divide. * @return {!gLong} This Long divided by the given one. */ public div(other: gLong): gLong { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return gLong.ZERO; } if (this.equals(gLong.MIN_VALUE)) { if (other.equals(gLong.ONE) || other.equals(gLong.NEG_ONE)) { return gLong.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(gLong.MIN_VALUE)) { return gLong.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var l_approx = halfThis.div(other).shiftLeft(1); if (l_approx.equals(gLong.ZERO)) { return other.isNegative() ? gLong.ONE : gLong.NEG_ONE; } else { var rem = this.subtract(other.multiply(l_approx)); var result = l_approx.add(rem.div(other)); return result; } } } else if (other.equals(gLong.MIN_VALUE)) { return gLong.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate().div(other).negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = gLong.ZERO; var rem: gLong = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = 1; if (log2 > 48) delta = Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = gLong.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = gLong.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = gLong.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; } /** * Returns this Long modulo the given one. * @param {gLong} other Long by which to mod. * @return {!gLong} This Long modulo the given one. */ public modulo(other: gLong): gLong { return this.subtract(this.div(other).multiply(other)); } /** @return {!gLong} The bitwise-NOT of this value. */ public not(): gLong { return gLong.fromBits(~this.low_, ~this.high_); } /** * Returns the bitwise-AND of this Long and the given one. * @param {gLong} other The Long with which to AND. * @return {!gLong} The bitwise-AND of this and the other. */ public and(other: gLong): gLong { return gLong.fromBits(this.low_ & other.low_, this.high_ & other.high_); } /** * Returns the bitwise-OR of this Long and the given one. * @param {gLong} other The Long with which to OR. * @return {!gLong} The bitwise-OR of this and the other. */ public or(other: gLong): gLong { return gLong.fromBits(this.low_ | other.low_, this.high_ | other.high_); } /** * Returns the bitwise-XOR of this Long and the given one. * @param {gLong} other The Long with which to XOR. * @return {!gLong} The bitwise-XOR of this and the other. */ public xor(other: gLong): gLong { return gLong.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); } /** * Returns this Long with bits shifted to the left by the given amount. * @param {number} numBits The number of bits by which to shift. * @return {!gLong} This shifted to the left by the given amount. */ public shiftLeft(numBits: number): gLong { numBits &= 63; if (numBits == 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return gLong.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return gLong.fromBits(0, low << (numBits - 32)); } } } /** * Returns this Long with bits shifted to the right by the given amount. * @param {number} numBits The number of bits by which to shift. * @return {!gLong} This shifted to the right by the given amount. */ public shiftRight(numBits: number): gLong { numBits &= 63; if (numBits == 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return gLong.fromBits( (low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return gLong.fromBits( high >> (numBits - 32), high >= 0 ? 0 : -1); } } } /** * Returns this Long with bits shifted to the right by the given amount, with * the new top bits matching the current sign bit. * @param {number} numBits The number of bits by which to shift. * @return {!gLong} This shifted to the right by the given amount, with * zeros placed into the new leading bits. */ public shiftRightUnsigned(numBits: number): gLong { numBits &= 63; if (numBits == 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return gLong.fromBits( (low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits == 32) { return gLong.fromBits(high, 0); } else { return gLong.fromBits(high >>> (numBits - 32), 0); } } } }
the_stack
import React, { useRef, useState, useEffect, useLayoutEffect, MutableRefObject, useCallback, useMemo, } from "react"; import classnames from "classnames"; import { reaction, toJS } from "mobx"; import { ChartEventStore } from "@src/stores"; import * as _ from "lodash-es"; import { Button, ButtonGroup, Badge } from "@douyinfe/semi-ui"; import { IconSearch, IconOrderedList } from "@douyinfe/semi-icons"; import { MouseMoveEvent, UnitEnum } from "@src/models"; import { formatter } from "@src/utils"; // 宏 const TOOLTIP_SPACING = 10; // Tooltip 与边界的距离 const TOOLTIP_MIN_HEIGHT = 100; // Chart Tooltip 最小高度 const CROSSHAIR_SPACING = 20; // 位于左右两侧时,鼠标与 tooltip 边界的间隙 enum TOOLTIP_POSITION { TOP = "top", RIGHT = "right", BOTTOM = "bottom", LEFT = "left", } // const setContentMaxSize = ( // el: HTMLElement, // size: { height?: number; width?: number } = {} // ) => { // if (!el) { // return; // } // const { height, width } = size; // height && (el.style.maxHeight = `${height}px`); // width && (el.style.maxWidth = `${width}px`); // }; const getCanvasActualPixel = (val: number): number => { // canvas scale size in retina. // ref: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio return val / window.devicePixelRatio; }; const ChartTooltipToolBar = () => { return ( <ButtonGroup> <Button style={{ paddingLeft: 0, paddingRight: 0 }} icon={<IconSearch />} size="small" /> <Button style={{ paddingLeft: 0, paddingRight: 0 }} icon={<IconOrderedList />} size="small" /> </ButtonGroup> ); }; const setPosition = ( target: HTMLElement, position: | { top?: number | string; right?: number | string; bottom?: number | string; left?: number | string; } | undefined ) => { if (!target || !position) { return; } const { top, right, bottom, left } = position; const topValue = top === undefined ? "auto" : typeof top === "number" ? `${top}px` : top; const rightValue = right === undefined ? "auto" : typeof right === "number" ? `${right}px` : right; const bottomValue = bottom === undefined ? "auto" : typeof bottom === "number" ? `${bottom}px` : bottom; const leftValue = left === undefined ? "auto" : typeof left === "number" ? `${left}px` : left; target.style.top = topValue; target.style.right = rightValue; target.style.bottom = bottomValue; target.style.left = leftValue; }; export default function ChartToltip() { const container = useRef() as MutableRefObject<HTMLDivElement>; // tooltip container const arrow = useRef() as MutableRefObject<HTMLDivElement>; // tooltip arrow const timer = useRef() as MutableRefObject<number | null>; // control mouse leave tooltip hide const [visible, setVisible] = useState<boolean>(false); // control tooltip if display const [event, setEvent] = useState<MouseMoveEvent>(); const [dataSource, setDataSource] = useState<any[]>([]); // console.log("iniiiiiiiiiiiiiiiiiiiiiiiiii"); /* 可视区域 */ const boundaryRect = document.body.getBoundingClientRect(); const clearTimer = () => { // make sure invoke it after setTimer setTimeout(() => { if (timer.current) { clearTimeout(timer.current); timer.current = null; } }, 0); }; const setTimer = useCallback(() => { // console.log("eeeee"); if (timer.current) { // console.log("hhhhhhhhh"); return; } timer.current = +setTimeout(() => { setVisible(false); ChartEventStore.setShowTooltip(false); clearTimer(); }, 200); }, []); useEffect(() => { const disposer = [ reaction( () => ChartEventStore.mouseMoveEvent, (e) => { if (!e) { return; } setVisible(true); ChartEventStore.setShowTooltip(true); setEvent(e); // console.log("tooltip move ", e); if (timer.current) { // if previous timer not clear, need clear it clearTimer(); } } ), reaction( () => ChartEventStore.mouseLeaveEvent, () => { console.log("settimer"); setTimer(); } ), ]; return () => { disposer.forEach((d) => d()); }; }, [setTimer]); useEffect(() => { if (!event) { return; } setDataSource([event]); }, [event]); /** * 设置 Tooltip 位置 * @param mouseX 相对于边界(boundary)的 offsetX * @param position 目标位置(上、右、下、左) * @param maxSize ToolTip 最大尺寸 */ const layoutTooltip = ( mouseX: number, position: TOOLTIP_POSITION, maxSize: { height: number; width: number } ) => { if (!event) { return; } // 当前 Tooltip 高度 const tooltipHeight = container.current.offsetHeight; // 当前 Tooltip 宽度 const tooltipWidth = container.current.offsetWidth; // console.log({mouseX, position, tooltipHeight, tooltipWidth}); // console.log(maxSize); const reachLeftBoundary = mouseX - tooltipWidth / 2 - TOOLTIP_SPACING < 0; const reachRightBoundary = mouseX + tooltipWidth / 2 + TOOLTIP_SPACING > boundaryRect.width; const reachBoundary = reachLeftBoundary || reachRightBoundary; const chartCanvasRect = event.chartCanvasRect; const chartCanvas = event.chartCanvas; let kickPosition, containerPosition; switch (position) { case TOOLTIP_POSITION.BOTTOM: containerPosition = { left: !reachBoundary ? chartCanvas.offsetLeft + mouseX - tooltipWidth / 2 //move : reachLeftBoundary ? TOOLTIP_SPACING : undefined, top: chartCanvasRect.bottom - 14, // (getCanvasActualPixel(chartCanvas.height) - chartArea.height) + // chartArea.top, right: reachRightBoundary ? TOOLTIP_SPACING : undefined, }; kickPosition = { left: chartCanvasRect.left + event.mouseX, }; break; case TOOLTIP_POSITION.TOP: containerPosition = { left: !reachBoundary ? mouseX - tooltipWidth / 2 : reachLeftBoundary ? TOOLTIP_SPACING : undefined, top: chartCanvasRect.y - tooltipHeight + 5, right: reachRightBoundary ? TOOLTIP_SPACING : undefined, }; kickPosition = { top: chartCanvasRect.y + 4, left: chartCanvasRect.left + event.mouseX, }; break; case TOOLTIP_POSITION.LEFT: kickPosition = { right: -15, top: "50%", }; containerPosition = { left: mouseX - CROSSHAIR_SPACING - tooltipWidth, // left: isRight ? mouseClientX + CROSSHAIR_SPACING : mouseClientX - CROSSHAIR_SPACING - toolTipReact.width - 15, top: "50%", }; break; case TOOLTIP_POSITION.RIGHT: kickPosition = { left: 2, top: "50%", }; containerPosition = { left: mouseX + CROSSHAIR_SPACING, top: "50%", }; break; default: break; } // debugger; // console.log("kickPosition", kickPosition); // console.log("containerPosition", containerPosition); setPosition(arrow.current, kickPosition); setPosition(container.current, containerPosition); }; // calc tooltip move position useLayoutEffect(() => { if (!event) { // when component init, event is null return; } const chartCanvasRect = event.chartCanvasRect; const offsetLeft = event ? event.mouseX : 0; // 当前点鼠标对于边界的 offsetX 值 const mouseClientX = offsetLeft + chartCanvasRect.left - boundaryRect.left; // console.log( // "do move...", // chartCanvasRect, // boundaryRect, // offsetLeft, // mouseClientX // ); // 上方可视区域 const topAreaHeight = chartCanvasRect.top - boundaryRect.top; // 下方可视区域 const bottomAreaHeight = boundaryRect.bottom - chartCanvasRect.bottom; // 左侧可视区域 const leftAreaWidth = mouseClientX - CROSSHAIR_SPACING; // 右侧可视区域 const rightAreaWidth = boundaryRect.width - mouseClientX - CROSSHAIR_SPACING; // 当前 Tooltip 高度 const tooltipHeight = container.current.clientHeight; // 当前 Tooltip 宽度 const tooltipWidth = container.current.clientWidth; // 判断所处位置 let targetPosition: TOOLTIP_POSITION; // 上下足以容纳 // console.log( // "bottomAreaHeight", // bottomAreaHeight, // "topAreaHeight", // topAreaHeight // ); if ( bottomAreaHeight > TOOLTIP_MIN_HEIGHT || topAreaHeight > TOOLTIP_MIN_HEIGHT ) { if (bottomAreaHeight - TOOLTIP_SPACING > tooltipHeight) { targetPosition = TOOLTIP_POSITION.BOTTOM; } else if (topAreaHeight - TOOLTIP_SPACING > tooltipHeight) { targetPosition = TOOLTIP_POSITION.TOP; } else { targetPosition = bottomAreaHeight > topAreaHeight ? TOOLTIP_POSITION.BOTTOM : TOOLTIP_POSITION.TOP; } } else { if (leftAreaWidth - TOOLTIP_SPACING > tooltipWidth) { targetPosition = TOOLTIP_POSITION.LEFT; } else if (rightAreaWidth - TOOLTIP_SPACING > tooltipWidth) { targetPosition = TOOLTIP_POSITION.RIGHT; } else { targetPosition = leftAreaWidth > rightAreaWidth ? TOOLTIP_POSITION.LEFT : TOOLTIP_POSITION.RIGHT; } } let maxSize = { height: 0, width: 0 }; // 设置高度 switch (targetPosition) { case TOOLTIP_POSITION.BOTTOM: maxSize = { height: bottomAreaHeight - TOOLTIP_SPACING, width: boundaryRect.width - TOOLTIP_SPACING * 2, }; break; case TOOLTIP_POSITION.TOP: maxSize = { height: topAreaHeight - TOOLTIP_SPACING, width: boundaryRect.width - TOOLTIP_SPACING * 2, }; break; case TOOLTIP_POSITION.LEFT: maxSize = { height: chartCanvasRect.height - TOOLTIP_SPACING * 2, width: leftAreaWidth - TOOLTIP_SPACING, }; break; case TOOLTIP_POSITION.RIGHT: maxSize = { height: chartCanvasRect.height - TOOLTIP_SPACING * 2, width: rightAreaWidth - TOOLTIP_SPACING, }; break; default: break; } // setContentMaxSize(container.current, maxSize); // 设置位置 // let tooltipPos; // setTimeout(() => { // }, 0); layoutTooltip(mouseClientX, targetPosition, maxSize); }, [dataSource, event]); const datasets = _.get(event, "chart.config.data.datasets", []); return ( <div ref={container} className={classnames("lin-chart-tooltip", { fixed: true, // "in-chart": true, hide: !visible, })} onMouseEnter={clearTimer} onMouseLeave={setTimer} > <div ref={arrow} className="arrow" /> <div className="title"> <div className="lindb-chart-tooltip__timestamp"> {_.get(event, `chart.config.data.timeLabels[${event?.index}]`, null)} </div> <ChartTooltipToolBar /> </div> <div className="content-wrapper"> <div className="content"> <ul className="list"> {datasets.map((item: any) => ( <li className="list-item" key={item.label + item.borderColor}> <div className="icon"> <Badge style={{ backgroundColor: item.borderColor }} dot /> </div> <span className="key">{item.label}</span> <span className="value"> {formatter( _.get(item, `data[${event?.index}]`, 0), _.get(event, "chart.config._config.unit", UnitEnum.None) )} </span> </li> ))} </ul> </div> </div> </div> ); }
the_stack
const quickselect = require('quickselect'); export interface GNode<L extends boolean> { children:L extends true ? BBox[] : Node[]; height:number; leaf:L; minX:number; minY:number; minZ:number; maxX:number; maxY:number; maxZ:number; } export type LeafNode = GNode<true>; export type NonLeafNode = GNode<false>; export type Node = LeafNode | NonLeafNode; export type NullableNode = Node | undefined; export type DetermineNode<L extends boolean> = L extends true ? LeafNode : NonLeafNode; export type DetermineLeaf<L extends boolean> = L extends true ? BBox : Node; export interface BBox { minX:number; minY:number; minZ:number; maxX:number; maxY:number; maxZ:number; [k:number]:any; [k:string]:any; } export interface CompareAxis { (a:BBox, b:BBox):number; } export interface CompareEqual { (a:BBox, b:BBox):boolean; } export interface DistNode { dist:number; node?:BBox; } const nodePool:Node[] = []; const freeNode = (node:Node) => nodePool.push(node); const freeAllNode = (node:Node) => { if (node) { freeNode(node); if (!isLeaf(node)) { node.children.forEach(freeAllNode); } } }; const allowNode = <L extends boolean = true>(children:DetermineLeaf<L>[]) => { let node = nodePool.pop() as DetermineNode<L>; if (node) { node.children = children as any; node.height = 1; node.leaf = true; node.minX = Infinity; node.minY = Infinity; node.minZ = Infinity; node.maxX = -Infinity; node.maxY = -Infinity; node.maxZ = -Infinity; } else { node = { children: children, height: 1, leaf: true, minX: Infinity, minY: Infinity, minZ: Infinity, maxX: -Infinity, maxY: -Infinity, maxZ: -Infinity, } as typeof node; } return node; }; const distNodePool:DistNode[] = []; const freeDistNode = (node:DistNode) => distNodePool.push(node); const allowDistNode = (dist:number, node?:BBox) => { let heapNode = distNodePool.pop(); if (heapNode) { heapNode.dist = dist; heapNode.node = node; } else { heapNode = { dist, node }; } return heapNode; }; const isLeaf = (node:Node):node is LeafNode => { return node.leaf; }; const isLeafChild = (node:Node, child?:BBox | Node):child is BBox => { return node.leaf; }; const findItem = (item:BBox, items:BBox[], equalsFn?:CompareEqual) => { if (!equalsFn) return items.indexOf(item); for (let i = 0; i < items.length; i++) { if (equalsFn(item, items[i])) return i; } return -1; }; // calculate node's bbox from bboxes of its children const calcBBox = (node:Node) => { distBBox(node, 0, node.children.length, node); }; // min bounding rectangle of node children from k to p-1 const distBBox = (node:Node, k:number, p:number, destNode?:Node) => { let dNode = destNode; if (dNode) { dNode.minX = Infinity; dNode.minY = Infinity; dNode.minZ = Infinity; dNode.maxX = -Infinity; dNode.maxY = -Infinity; dNode.maxZ = -Infinity; } else { dNode = allowNode([]) as Node; } for (let i = k, child:typeof node.children[0]; i < p; i++) { child = node.children[i]; extend(dNode, child); } return dNode; }; const extend = (a:BBox, b:BBox) => { a.minX = Math.min(a.minX, b.minX); a.minY = Math.min(a.minY, b.minY); a.minZ = Math.min(a.minZ, b.minZ); a.maxX = Math.max(a.maxX, b.maxX); a.maxY = Math.max(a.maxY, b.maxY); a.maxZ = Math.max(a.maxZ, b.maxZ); return a; }; const bboxVolume = (a:BBox) => (a.maxX - a.minX) * (a.maxY - a.minY) * (a.maxZ - a.minZ); const bboxMargin = (a:BBox) => (a.maxX - a.minX) + (a.maxY - a.minY) + (a.maxZ - a.minZ); const enlargedVolume = (a:BBox, b:BBox) => { const minX = Math.min(a.minX, b.minX), minY = Math.min(a.minY, b.minY), minZ = Math.min(a.minZ, b.minZ), maxX = Math.max(a.maxX, b.maxX), maxY = Math.max(a.maxY, b.maxY), maxZ = Math.max(a.maxZ, b.maxZ); return (maxX - minX) * (maxY - minY) * (maxZ - minZ); }; const intersectionVolume = (a:BBox, b:BBox) => { const minX = Math.max(a.minX, b.minX), minY = Math.max(a.minY, b.minY), minZ = Math.max(a.minZ, b.minZ), maxX = Math.min(a.maxX, b.maxX), maxY = Math.min(a.maxY, b.maxY), maxZ = Math.min(a.maxZ, b.maxZ); return Math.max(0, maxX - minX) * Math.max(0, maxY - minY) * Math.max(0, maxZ - minZ); }; const contains = (a:BBox, b:BBox) => a.minX <= b.minX && a.minY <= b.minY && a.minZ <= b.minZ && b.maxX <= a.maxX && b.maxY <= a.maxY && b.maxZ <= a.maxZ; export const intersects = (a:BBox, b:BBox) => b.minX <= a.maxX && b.minY <= a.maxY && b.minZ <= a.maxZ && b.maxX >= a.minX && b.maxY >= a.minY && b.maxZ >= a.minZ; export const boxRayIntersects = (box:BBox, ox:number, oy:number, oz:number, idx:number, idy:number, idz:number) => { const tx0 = (box.minX - ox) * idx; const tx1 = (box.maxX - ox) * idx; const ty0 = (box.minY - oy) * idy; const ty1 = (box.maxY - oy) * idy; const tz0 = (box.minZ - oz) * idz; const tz1 = (box.maxZ - oz) * idz; const z0 = Math.min(tz0, tz1); const z1 = Math.max(tz0, tz1); const y0 = Math.min(ty0, ty1); const y1 = Math.max(ty0, ty1); const x0 = Math.min(tx0, tx1); const x1 = Math.max(tx0, tx1); const tmin = Math.max(0, x0, y0, z0); const tmax = Math.min(x1, y1, z1); return tmax >= tmin ? tmin : Infinity; }; // sort an array so that items come in groups of n unsorted items, with groups sorted between each other; // combines selection algorithm with binary divide & conquer approach const multiSelect = (arr:BBox[], left:number, right:number, n:number, compare:CompareAxis) => { const stack = [left, right]; var mid; while (stack.length) { right = stack.pop()!; left = stack.pop()!; if (right - left <= n) continue; mid = left + Math.ceil((right - left) / n / 2) * n; quickselect(arr, mid, left, right, compare); stack.push(left, mid, mid, right); } }; const compareMinX = (a:BBox, b:BBox) => a.minX - b.minX; const compareMinY = (a:BBox, b:BBox) => a.minY - b.minY; const compareMinZ = (a:BBox, b:BBox) => a.minZ - b.minZ; export class RBush3D { private data:Node; private maxEntries:number; private minEntries:number; private static pool:RBush3D[] = []; public static alloc() { return this.pool.pop() || new this(); } public static free(rbush:RBush3D) { rbush.clear(); this.pool.push(rbush); } constructor(maxEntries = 16) { this.maxEntries = Math.max(maxEntries, 8); this.minEntries = Math.max(4, Math.ceil(this.maxEntries * 0.4)); this.clear(); } public search(bbox:BBox) { let node:NullableNode = this.data; const result:BBox[] = []; if (!intersects(bbox, node)) return result; const nodesToSearch:Node[] = []; while (node) { for (let i = 0, len = node.children.length; i < len; i++) { // FIXME: remove ':any' when ts fix the bug const child:any = node.children[i]; if (intersects(bbox, child)) { if (isLeafChild(node, child)) result.push(child); else if (contains(bbox, child)) this._all(child, result); else nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return result; } public collides(bbox:BBox) { let node:NullableNode = this.data; if (!intersects(bbox, node)) return false; const nodesToSearch:Node[] = []; while (node) { for (let i = 0, len = node.children.length; i < len; i++) { // FIXME: remove ':any' when ts fix the bug const child:any = node.children[i]; if (intersects(bbox, child)) { if (isLeafChild(node, child) || contains(bbox, child)) return true; nodesToSearch.push(child); } } node = nodesToSearch.pop(); } return false; } public raycastInv(ox:number, oy:number, oz:number, idx:number, idy:number, idz:number, maxLen = Infinity):DistNode { let node = this.data; if (idx === Infinity && idy === Infinity && idz === Infinity) return allowDistNode(Infinity, undefined); if (boxRayIntersects(node, ox, oy, oz, idx, idy, idz) === Infinity) return allowDistNode(Infinity, undefined); const heap = [allowDistNode(0, node)]; const swap = (a:number, b:number) => { const t = heap[a]; heap[a] = heap[b]; heap[b] = t; }; const pop = () => { const top = heap[0]; const newLen = heap.length - 1; heap[0] = heap[newLen]; heap.length = newLen; let idx = 0; while (true) { let left = (idx << 1) | 1; if (left >= newLen) break; const right = left + 1; if (right < newLen && heap[right].dist < heap[left].dist) { left = right; } if (heap[idx].dist < heap[left].dist) break; swap(idx, left); idx = left; } freeDistNode(top); return top.node; }; const push = (dist:number, node:Node) => { let idx = heap.length; heap.push(allowDistNode(dist, node)); while (idx > 0) { const p = (idx - 1) >> 1; if (heap[p].dist <= heap[idx].dist) break; swap(idx, p); idx = p; } }; let dist = maxLen; let result:BBox|undefined; while (heap.length && heap[0].dist < dist) { node = pop() as Node; for (let i = 0, len = node.children.length; i < len; i++) { const child = node.children[i]; const d = boxRayIntersects(child, ox, oy, oz, idx, idy, idz); if (!isLeafChild(node, child)) { push(d, child); } else if (d < dist) { if (d === 0) { return allowDistNode(d, child); } dist = d; result = child; } } } return allowDistNode(dist < maxLen ? dist : Infinity, result); } public raycast(ox:number, oy:number, oz:number, dx:number, dy:number, dz:number, maxLen = Infinity) { return this.raycastInv(ox, oy, oz, 1 / dx, 1 / dy, 1 / dz, maxLen); } public all() { return this._all(this.data, []); } public load(data:BBox[]) { if (!(data && data.length)) return this; if (data.length < this.minEntries) { for (var i = 0, len = data.length; i < len; i++) { this.insert(data[i]); } return this; } // recursively build the tree with the given data from scratch using OMT algorithm var node = this.build(data.slice(), 0, data.length - 1, 0); if (!this.data.children.length) { // save as is if tree is empty this.data = node; } else if (this.data.height === node.height) { // split root if trees have the same height this.splitRoot(this.data, node); } else { if (this.data.height < node.height) { // swap trees if inserted one is bigger const tmpNode = this.data; this.data = node; node = tmpNode; } // insert the small tree into the large tree at appropriate level this._insert(node, this.data.height - node.height - 1, true); } return this; } public insert(item?:BBox) { if (item) this._insert(item, this.data.height - 1); return this; } public clear() { if (this.data) { freeAllNode(this.data); } this.data = allowNode([]); return this; } public remove(item?:BBox, equalsFn?:CompareEqual) { if (!item) return this; let node:NullableNode = this.data; let i = 0; let goingUp = false; let index:number; let parent:NonLeafNode | undefined; const path:Node[] = []; const indexes:number[] = []; // depth-first iterative tree traversal while (node || path.length) { if (!node) { // go up node = path.pop()!; i = indexes.pop()!; parent = path[path.length - 1] as NonLeafNode; goingUp = true; } if (isLeaf(node)) { // check current node index = findItem(item, node.children, equalsFn); if (index !== -1) { // item found, remove the item and condense tree upwards node.children.splice(index, 1); path.push(node); this.condense(path); return this; } } if (!goingUp && !isLeaf(node) && contains(node, item)) { // go down path.push(node); indexes.push(i); i = 0; parent = node; node = node.children[0]; } else if (parent) { // go right i++; node = parent.children[i]; goingUp = false; } else { node = undefined; // nothing found } } return this; } public toJSON() { return this.data; } public fromJSON(data:Node) { freeAllNode(this.data); this.data = data; return this; } private build(items:BBox[], left:number, right:number, height:number) { const N = right - left + 1; let M = this.maxEntries; let node:Node; if (N <= M) { // reached leaf level; return leaf node = allowNode(items.slice(left, right + 1)); calcBBox(node); return node; } if (!height) { // target height of the bulk-loaded tree height = Math.ceil(Math.log(N) / Math.log(M)); // target number of root entries to maximize storage utilization M = Math.ceil(N / Math.pow(M, height - 1)); } node = allowNode<false>([]); node.leaf = false; node.height = height; // split the items into M mostly square tiles const N3 = Math.ceil(N / M), N2 = N3 * Math.ceil(Math.pow(M, 2 / 3)), N1 = N3 * Math.ceil(Math.pow(M, 1 / 3)); multiSelect(items, left, right, N1, compareMinX); for (let i = left; i <= right; i += N1) { const right2 = Math.min(i + N1 - 1, right); multiSelect(items, i, right2, N2, compareMinY); for (let j = i; j <= right2; j += N2) { const right3 = Math.min(j + N2 - 1, right2); multiSelect(items, j, right3, N3, compareMinZ); for (let k = j; k <= right3; k += N3) { const right4 = Math.min(k + N3 - 1, right3); // pack each entry recursively (node.children as any[]).push(this.build(items, k, right4, height - 1)); } } } calcBBox(node); return node; } private _all(node:Node | undefined, result:BBox[]) { const nodesToSearch:Node[] = []; while (node) { if (isLeaf(node)) result.push(...node.children); else nodesToSearch.push(...node.children); node = nodesToSearch.pop(); } return result; } private chooseSubtree(bbox:BBox, node:Node, level:number, path:Node[]) { let minVolume:number; let minEnlargement:number; let targetNode:NullableNode; while (true) { path.push(node); if (isLeaf(node) || path.length - 1 === level) break; minVolume = minEnlargement = Infinity; for (let i = 0, len = node.children.length; i < len; i++) { const child = node.children[i]; const volume = bboxVolume(child); const enlargement = enlargedVolume(bbox, child) - volume; // choose entry with the least volume enlargement if (enlargement < minEnlargement) { minEnlargement = enlargement; minVolume = volume < minVolume ? volume : minVolume; targetNode = child; } else if (enlargement === minEnlargement) { // otherwise choose one with the smallest volume if (volume < minVolume) { minVolume = volume; targetNode = child; } } } node = targetNode || node.children[0]; } return node; } // split overflowed node into two private split(insertPath:Node[], level:number) { const node = insertPath[level]; const M = node.children.length; const m = this.minEntries; this.chooseSplitAxis(node, m, M); const splitIndex = this.chooseSplitIndex(node, m, M); const newNode = allowNode<typeof node.leaf>(node.children.splice(splitIndex, node.children.length - splitIndex)); newNode.height = node.height; newNode.leaf = node.leaf; calcBBox(node); calcBBox(newNode); if (level) (insertPath[level - 1] as NonLeafNode).children.push(newNode); else this.splitRoot(node, newNode); } private splitRoot(node:Node, newNode:Node) { // split root node this.data = allowNode<false>([node, newNode]); this.data.height = node.height + 1; this.data.leaf = false; calcBBox(this.data); } private chooseSplitIndex(node:Node, m:number, M:number) { let minOverlap = Infinity; let minVolume = Infinity; let index:number; for (let i = m; i <= M - m; i++) { const bbox1 = distBBox(node, 0, i); const bbox2 = distBBox(node, i, M); const overlap = intersectionVolume(bbox1, bbox2); const volume = bboxVolume(bbox1) + bboxVolume(bbox2); // choose distribution with minimum overlap if (overlap < minOverlap) { minOverlap = overlap; index = i; minVolume = volume < minVolume ? volume : minVolume; } else if (overlap === minOverlap) { // otherwise choose distribution with minimum volume if (volume < minVolume) { minVolume = volume; index = i; } } } return index!; } // sorts node children by the best axis for split private chooseSplitAxis(node:Node, m:number, M:number) { const xMargin = this.allDistMargin(node, m, M, compareMinX); const yMargin = this.allDistMargin(node, m, M, compareMinY); const zMargin = this.allDistMargin(node, m, M, compareMinZ); // if total distributions margin value is minimal for x, sort by minX, // if total distributions margin value is minimal for y, sort by minY, // otherwise it's already sorted by minZ if (xMargin < yMargin && xMargin < zMargin) { (node.children as any[]).sort(compareMinX as any); } else if (yMargin < xMargin && yMargin < zMargin) { (node.children as any[]).sort(compareMinY as any); } } // total margin of all possible split distributions where each node is at least m full private allDistMargin(node:Node, m:number, M:number, compare:typeof node extends LeafNode ? CompareAxis : Function) { (node.children as any).sort(compare); const leftBBox = distBBox(node, 0, m); const rightBBox = distBBox(node, M - m, M); let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox); for (let i = m; i < M - m; i++) { const child = node.children[i]; extend(leftBBox, child); margin += bboxMargin(leftBBox); } for (let i = M - m - 1; i >= m; i--) { const child = node.children[i]; extend(rightBBox, child); margin += bboxMargin(rightBBox); } return margin; } private adjustParentBBoxes(bbox:BBox, path:Node[], level:number) { // adjust bboxes along the given tree path for (let i = level; i >= 0; i--) { extend(path[i], bbox); } } private condense(path:Node[]) { // go through the path, removing empty nodes and updating bboxes for (let i = path.length - 1, siblings:Node[]; i >= 0; i--) { if (path[i].children.length === 0) { if (i > 0) { siblings = path[i - 1].children as Node[]; siblings.splice(siblings.indexOf(path[i]), 1); freeNode(path[i]); } else { this.clear(); } } else { calcBBox(path[i]); } } } private _insert(item:BBox | Node, level:number, isNode?:boolean) { const insertPath:Node[] = []; // find the best node for accommodating the item, saving all nodes along the path too const node = this.chooseSubtree(item, this.data, level, insertPath); // put the item into the node (node.children as any[]).push(item); extend(node, item); // split on node overflow; propagate upwards if necessary while (level >= 0) { if (insertPath[level].children.length > this.maxEntries) { this.split(insertPath, level); level--; } else break; } // adjust bboxes along the insertion path this.adjustParentBBoxes(item, insertPath, level); } }
the_stack
import * as result from './result' import { Result } from './result' type ParseResult<T,E> = Result<{ output: T, rest: string },E> type EvalResult<T,E> = Result<T,E> export type Pos = { /** How long is the input string at the start of parsing? */ startLen: number, /** How long is the input string at the end of parsing? */ endLen: number } type Pattern = string | RegExp /** Internal, low level parse errors */ export type LibParseError = LibParseErrorMatchString | LibParseErrorMustTakeWhile | LibParseErrorMustSepBy | LibParseErrorEndOfString | LibParseErrorNotANumber type LibParseErrorNotANumber = { kind: 'NOT_A_NUMBER' input: string } type LibParseErrorEndOfString = { kind: 'EXPECTS_A_CHAR' input: "" expects?: string } type LibParseErrorMatchString = { kind: 'EXPECTS_A_STRING' expectedOneOf: string[] input: string } type LibParseErrorMustTakeWhile = { kind: 'EXPECTS_PATTERN' expectedPattern: RegExp | String input: string } type LibParseErrorMustSepBy = { kind: 'EXPECTS_A_SEPARATOR' input: string } export class Parser<T,E> { private constructor(readonly _fn_: (input: string) => ParseResult<T, E>) {} eval(input: string): EvalResult<T,E> { const res = this._fn_(input) return result.map(res, val => val.output) } parse(input: string): ParseResult<T,E> { return this._fn_(input) } /** A parser that does nothing */ static ok<T,E>(val: T): Parser<T,E> { return new Parser(input => { return result.ok({ output: val, rest: input }) }) } /** Any one character. Only fails on an empty string */ static anyChar(): Parser<string,LibParseError> { return new Parser(input => { if (input.length) { return result.ok({ output: input.slice(0,1), rest: input.slice(1) }) } else { return result.err({ kind: 'EXPECTS_A_CHAR', input: "" }) } }) } /** * Parse a string. * Expects strings to be surrounded in single or double quotes. * backslash to escape; anything can be escaped. */ static string(): Parser<string,LibParseError> { return new Parser(input => { const thisDelim = input[0] if (thisDelim !== '"' && thisDelim !== "'") { return result.err({ kind: 'EXPECTS_A_STRING', expectedOneOf: ['"', "'"], input }) } let i = 1 let lastEscape = false let s = "" while (i < input.length) { let char = input[i] // escape if backslash: if (!lastEscape && char === '\\') { lastEscape = true } // return if closing delim, unescaped: else if (!lastEscape && char === thisDelim) { return result.ok({ output: s, rest: input.slice(i+1) }) } // Append char, unset escape mode if set: else { s += char lastEscape = false } i++ } // We haven't returned a string, so we ran out of chars: return result.err({ kind: 'EXPECTS_A_CHAR', input: '' }) }) } /** Parse a number as a string */ static numberStr(): Parser<string,LibParseError> { return new Parser(input => { let idx = 0 let nStr = "" // Return this on total failure: function nan(): ParseResult<string,LibParseError> { return result.err({ kind: 'NOT_A_NUMBER', input }) } // Prefix: function pushSign () { if (input[idx] === '+') { idx++ } else if (input[idx] === '-') { idx++ nStr += '-' } } // Leading digits: function pushDigits () { let hasNumbers = false let charCode = input.charCodeAt(idx) while (charCode >= 48 /* 0 */ && charCode <= 57 /* 9 */) { nStr += input[idx] idx++ hasNumbers = true charCode = input.charCodeAt(idx) } return hasNumbers } pushSign() const hasLeadingDigits = pushDigits() let hasDecimalPlaces = false // Decimal place and numbers after it: if (input[idx] === '.') { if (!hasLeadingDigits) nStr += '0' nStr += '.' idx++ if (!pushDigits()) { if (!hasLeadingDigits) { return nan() } else { // failed to push digits, so remove the '.' // and return the number we've got so far: return result.ok({ output: nStr.slice(0, -1), rest: input.slice(idx - 1) }) } } hasDecimalPlaces = true } // A number has to have trailing digits or decimal // places, otherwise it's not valid: if (!hasLeadingDigits && !hasDecimalPlaces) { return nan() } // Exponent (e/E followed by optional sign and digits): let e = input[idx] if (e === 'e' || e === 'E') { const eIdx = idx nStr += 'e' idx++ pushSign() if (!pushDigits()) { // If no digits after E, roll back to last // valid number and return that: idx = eIdx nStr = nStr.slice(0,eIdx) } } return result.ok({ output: nStr, rest: input.slice(idx) }) }) } /** A convenience function to turn a function scope into a parser to avoid reuse of vars */ static lazy<T,E>(fn: () => Parser<T,E>): Parser<T,E> { return new Parser(input => { return fn().parse(input) }) } /** Return a parser that matches a given string */ static matchString(...strings: string[]): Parser<string,LibParseError> { return new Parser(input => { for(const s of strings) { if (input.slice(0, s.length) === s) { return result.ok({ output: s, rest: input.slice(s.length) }) } } return result.err({ kind: 'EXPECTS_A_STRING', expectedOneOf: strings, input }) }) } /** Take characters while the fn provided matches them to a max of n */ static takeWhileN(n: number, pat: Pattern): Parser<string,never> { const fn = pat instanceof RegExp ? (c: string) => pat.test(c) : typeof pat === 'string' ? (c: string) => pat === c : pat return new Parser(input => { let i = 0 while (i < n && fn(input.charAt(i))) { i++ } return result.ok({ output: input.slice(0,i), rest: input.slice(i) }) }) } static takeWhile(pat: Pattern): Parser<string,never> { return Parser.takeWhileN(Infinity, pat) } /** Take characters while the fn provided matches them to a max of n */ static mustTakeWhileN(n: number, pat: Pattern): Parser<string,LibParseError> { return new Parser(input => { const res = Parser.takeWhileN(n, pat).parse(input) if (result.isOk(res) && !res.value.output.length) { return result.err({ kind: 'EXPECTS_PATTERN', expectedPattern: pat, input }) } else { return res } }) } static mustTakeWhile(pat: Pattern): Parser<string,LibParseError> { return Parser.mustTakeWhileN(Infinity, pat) } /** Run this on a parser to peek at the available position information (distances from end) */ mapWithPosition<T2>(fn: (res: T, pos: Pos) => T2): Parser<T2,E> { return new Parser(input => { return result.map(this.parse(input), val => { const startLen = input.length const endLen = val.rest.length return { output: fn(val.output, { startLen, endLen }), rest: val.rest } }) }) } /** Make the success of this parser optional */ optional(): Parser<Result<T,E>,E> { return new Parser(input => { const res = this.parse(input) if (result.isOk(res)) { return result.map(res, o => { return { output: result.ok(o.output), rest: o.rest } }) } else { return result.ok({ output: result.err(res.value), rest: input }) } }) } /** Map this parser result into something else */ map<T2>(fn: (result: T) => T2): Parser<T2,E> { return new Parser(input => { return result.map(this.parse(input), val => { return { output: fn(val.output), rest: val.rest } }) }) } mapErr<E2>(fn: (err: E) => E2): Parser<T,E2> { return new Parser(input => { return result.mapErr(this.parse(input), err => { return fn(err) }) }) } /** Succeeds if the current parser or the one provided succeeds */ or(other: Parser<T,E>): Parser<T,E> { return new Parser(input => { const res1 = this.parse(input) if (result.isErr(res1)) { return other.parse(input) } else { return res1 } }) } /** Pass the result of the this parser to a function which returns the next parser */ andThen<T2>(next: (result: T) => Parser<T2,E>): Parser<T2,E> { return new Parser(input => { const res1 = this.parse(input) if (result.isOk(res1)) { return next(res1.value.output).parse(res1.value.rest) } else { return res1 } }) } sepBy<S>(sep: Parser<S,unknown>): Parser<{ results: T[], separators: S[]},E> { return new Parser(input => { let results: T[] = [] let separators: S[] = [] let restOfInput = input // parse the first result, bailing if we can't even do that: const res = this.parse(restOfInput) if (result.isOk(res)) { results.push(res.value.output) restOfInput = res.value.rest } else { return res } // now, expect sep + result each time to keep going: while (true) { const sepRes = sep.parse(restOfInput) if (result.isErr(sepRes)) { break } const res = this.parse(sepRes.value.rest) if (result.isErr(res)) { break } separators.push(sepRes.value.output) results.push(res.value.output) restOfInput = res.value.rest } return result.ok({ output: { results, separators }, rest: restOfInput }) }) } mustSepBy<S>(sep: Parser<S,unknown>): Parser<{ results: T[], separators: S[]},E | LibParseError> { return new Parser(input => { const res = this.sepBy(sep).parse(input) if (result.isOk(res) && !res.value.output.separators.length) { return result.err<any,E|LibParseError>({ kind: 'EXPECTS_A_SEPARATOR', input }) } else { return res } }) } }
the_stack
import hypergeometric = require( './index' ); // TESTS // // The function returns a number... { hypergeometric( 10, 5, 7 ); // $ExpectType number hypergeometric( 5, 3, 2 ); // $ExpectType number } // The compiler throws an error if the function is provided values other than three numbers... { hypergeometric( true, 3, 2 ); // $ExpectError hypergeometric( false, 2, 2 ); // $ExpectError hypergeometric( '5', 1, 2 ); // $ExpectError hypergeometric( [], 1, 2 ); // $ExpectError hypergeometric( {}, 2, 2 ); // $ExpectError hypergeometric( ( x: number ): number => x, 2, 2 ); // $ExpectError hypergeometric( 9, true, 2 ); // $ExpectError hypergeometric( 9, false, 2 ); // $ExpectError hypergeometric( 5, '5', 2 ); // $ExpectError hypergeometric( 8, [], 2 ); // $ExpectError hypergeometric( 9, {}, 2 ); // $ExpectError hypergeometric( 8, ( x: number ): number => x, 2 ); // $ExpectError hypergeometric( 9, 3, true ); // $ExpectError hypergeometric( 9, 3, false ); // $ExpectError hypergeometric( 5, 5, '5' ); // $ExpectError hypergeometric( 8, 8, [] ); // $ExpectError hypergeometric( 9, 3, {} ); // $ExpectError hypergeometric( 8, 4, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { hypergeometric(); // $ExpectError hypergeometric( 4 ); // $ExpectError hypergeometric( 4, 2 ); // $ExpectError hypergeometric( 4, 2, 2, 4, 8 ); // $ExpectError } // Attached to main export is a `factory` method which returns a function... { hypergeometric.factory( 4, 2, 2 ); // $ExpectType NullaryFunction hypergeometric.factory(); // $ExpectType BinaryFunction hypergeometric.factory( { 'copy': false } ); // $ExpectType BinaryFunction } // The `factory` method returns a function which returns a number... { const fcn1 = hypergeometric.factory( 4, 2, 2 ); fcn1(); // $ExpectType number const fcn2 = hypergeometric.factory(); fcn2( 4, 2, 2 ); // $ExpectType number } // The compiler throws an error if the function returned by the `factory` method is provided invalid arguments... { const fcn1 = hypergeometric.factory( 5, 3, 2 ); fcn1( 12 ); // $ExpectError fcn1( true ); // $ExpectError fcn1( false ); // $ExpectError fcn1( '5' ); // $ExpectError fcn1( [] ); // $ExpectError fcn1( {} ); // $ExpectError fcn1( ( x: number ): number => x ); // $ExpectError const fcn2 = hypergeometric.factory(); fcn2( true, 2, 2 ); // $ExpectError fcn2( false, 2, 2 ); // $ExpectError fcn2( '5', 2, 2 ); // $ExpectError fcn2( [], 2, 2 ); // $ExpectError fcn2( {}, 2, 2 ); // $ExpectError fcn2( ( x: number ): number => x, 2, 2 ); // $ExpectError fcn2( 10, true, 2 ); // $ExpectError fcn2( 10, false, 2 ); // $ExpectError fcn2( 10, '5', 2 ); // $ExpectError fcn2( 10, [], 2 ); // $ExpectError fcn2( 10, {}, 2 ); // $ExpectError fcn2( 10, ( x: number ): number => x, 2 ); // $ExpectError fcn2( 10, 5, true ); // $ExpectError fcn2( 10, 5, false ); // $ExpectError fcn2( 10, 5, '5' ); // $ExpectError fcn2( 10, 5, [] ); // $ExpectError fcn2( 10, 5, {} ); // $ExpectError fcn2( 10, 5, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function returned by the `factory` method is provided an unsupported number of arguments... { const fcn1 = hypergeometric.factory( 20, 10, 5 ); fcn1( 1 ); // $ExpectError fcn1( 2, 1 ); // $ExpectError fcn1( 2, 1, 1 ); // $ExpectError const fcn2 = hypergeometric.factory(); fcn2(); // $ExpectError fcn2( 1 ); // $ExpectError fcn2( 2, 1 ); // $ExpectError } // The compiler throws an error if the `factory` method is provided values other than three numbers aside from an options object... { hypergeometric.factory( true, 3, 1 ); // $ExpectError hypergeometric.factory( false, 2, 1 ); // $ExpectError hypergeometric.factory( '5', 1, 1 ); // $ExpectError hypergeometric.factory( [], 1, 1 ); // $ExpectError hypergeometric.factory( {}, 2, 1 ); // $ExpectError hypergeometric.factory( ( x: number ): number => x, 2, 1 ); // $ExpectError hypergeometric.factory( 9, true, 1 ); // $ExpectError hypergeometric.factory( 9, false, 1 ); // $ExpectError hypergeometric.factory( 5, '5', 1 ); // $ExpectError hypergeometric.factory( 8, [], 1 ); // $ExpectError hypergeometric.factory( 9, {}, 1 ); // $ExpectError hypergeometric.factory( 8, ( x: number ): number => x, 1 ); // $ExpectError hypergeometric.factory( 9, 3, true ); // $ExpectError hypergeometric.factory( 9, 3, false ); // $ExpectError hypergeometric.factory( 5, 3, '5' ); // $ExpectError hypergeometric.factory( 8, 3, [] ); // $ExpectError hypergeometric.factory( 9, 3, {} ); // $ExpectError hypergeometric.factory( 8, 8, ( x: number ): number => x ); // $ExpectError hypergeometric.factory( true, 3, 1, {} ); // $ExpectError hypergeometric.factory( false, 2, 1, {} ); // $ExpectError hypergeometric.factory( '5', 1, 1, {} ); // $ExpectError hypergeometric.factory( [], 1, 1, {} ); // $ExpectError hypergeometric.factory( {}, 2, 1, {} ); // $ExpectError hypergeometric.factory( ( x: number ): number => x, 2, 1, {} ); // $ExpectError hypergeometric.factory( 9, true, 1, {} ); // $ExpectError hypergeometric.factory( 9, false, 1, {} ); // $ExpectError hypergeometric.factory( 5, '5', 1, {} ); // $ExpectError hypergeometric.factory( 8, [], 1, {} ); // $ExpectError hypergeometric.factory( 9, {}, 1, {} ); // $ExpectError hypergeometric.factory( 8, ( x: number ): number => x, 1, {} ); // $ExpectError hypergeometric.factory( 9, 3, true, {} ); // $ExpectError hypergeometric.factory( 9, 3, false, {} ); // $ExpectError hypergeometric.factory( 5, 3, '5', {} ); // $ExpectError hypergeometric.factory( 8, 3, [], {} ); // $ExpectError hypergeometric.factory( 9, 3, {}, {} ); // $ExpectError hypergeometric.factory( 8, 8, ( x: number ): number => x, {} ); // $ExpectError } // The compiler throws an error if the `factory` method is provided an options argument which is not an object... { hypergeometric.factory( null ); // $ExpectError hypergeometric.factory( 4, 2, 1, null ); // $ExpectError } // The compiler throws an error if the `factory` method is provided a `prng` option which is not a pseudorandom number generator... { hypergeometric.factory( 5, 3, 2, { 'prng': 123 } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'prng': 'abc' } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'prng': null } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'prng': [] } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'prng': {} } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'prng': true ); // $ExpectError hypergeometric.factory( { 'prng': 123 } ); // $ExpectError hypergeometric.factory( { 'prng': 'abc' } ); // $ExpectError hypergeometric.factory( { 'prng': null } ); // $ExpectError hypergeometric.factory( { 'prng': [] } ); // $ExpectError hypergeometric.factory( { 'prng': {} } ); // $ExpectError hypergeometric.factory( { 'prng': true ); // $ExpectError } // The compiler throws an error if the `factory` method is provided a `seed` option which is not a valid seed... { hypergeometric.factory( 5, 3, 2, { 'seed': true } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'seed': 'abc' } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'seed': null } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'seed': [ 'a' ] } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'seed': {} } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'seed': ( x: number ): number => x } ); // $ExpectError hypergeometric.factory( { 'seed': true } ); // $ExpectError hypergeometric.factory( { 'seed': 'abc' } ); // $ExpectError hypergeometric.factory( { 'seed': null } ); // $ExpectError hypergeometric.factory( { 'seed': [ 'a' ] } ); // $ExpectError hypergeometric.factory( { 'seed': {} } ); // $ExpectError hypergeometric.factory( { 'seed': ( x: number ): number => x } ); // $ExpectError } // The compiler throws an error if the `factory` method is provided a `state` option which is not a valid state... { hypergeometric.factory( 5, 3, 2, { 'state': 123 } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': 'abc' } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': null } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': [] } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': {} } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': true ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'state': ( x: number ): number => x } ); // $ExpectError hypergeometric.factory( { 'state': 123 } ); // $ExpectError hypergeometric.factory( { 'state': 'abc' } ); // $ExpectError hypergeometric.factory( { 'state': null } ); // $ExpectError hypergeometric.factory( { 'state': [] } ); // $ExpectError hypergeometric.factory( { 'state': {} } ); // $ExpectError hypergeometric.factory( { 'state': true ); // $ExpectError hypergeometric.factory( { 'state': ( x: number ): number => x } ); // $ExpectError } // The compiler throws an error if the `factory` method is provided a `copy` option which is not a boolean... { hypergeometric.factory( 5, 3, 2, { 'copy': 123 } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'copy': 'abc' } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'copy': null } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'copy': [] } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'copy': {} } ); // $ExpectError hypergeometric.factory( 5, 3, 2, { 'copy': ( x: number ): number => x } ); // $ExpectError hypergeometric.factory( { 'copy': 123 } ); // $ExpectError hypergeometric.factory( { 'copy': 'abc' } ); // $ExpectError hypergeometric.factory( { 'copy': null } ); // $ExpectError hypergeometric.factory( { 'copy': [] } ); // $ExpectError hypergeometric.factory( { 'copy': {} } ); // $ExpectError hypergeometric.factory( { 'copy': ( x: number ): number => x } ); // $ExpectError } // The compiler throws an error if the `factory` method is provided more than four arguments... { hypergeometric.factory( 20, 10, 6, {}, 2 ); // $ExpectError }
the_stack
'use strict'; // tslint:disable no-unused-expression import * as vscode from 'vscode'; import * as fs from 'fs-extra'; import * as sinon from 'sinon'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { SampleGalleryView } from '../../extension/webview/SampleGalleryView'; import { View } from '../../extension/webview/View'; import { TestUtil } from '../TestUtil'; import { GlobalState } from '../../extension/util/GlobalState'; import { ExtensionCommands } from '../../ExtensionCommands'; chai.use(sinonChai); describe('SampleGalleryView', () => { const mySandBox: sinon.SinonSandbox = sinon.createSandbox(); let context: vscode.ExtensionContext; let createWebviewPanelStub: sinon.SinonStub; let postMessageStub: sinon.SinonStub; let executeCommandStub: sinon.SinonStub; let onDidReceiveMessagePromises: any[]; const repositories: { repositories: any[] } = { repositories: [ { name: 'fabric-samples', orgName: 'hyperledger', remote: 'https://github.com/hyperledger/fabric-samples.git', tutorials: [], samples: [ { name: 'FabCar', description: 'Basic sample based on cars: the "hello world" of Hyperledger Fabric samples.', readme: 'https://raw.githubusercontent.com/hyperledger/fabric-samples/master/README.md', category: { contracts: [ { name: 'FabCar Contract', languages: [ { type: 'Go', version: '1.0.0', workspaceLabel: 'fabcar-contract-go', remote: { branch: 'master', path: 'chaincode/fabcar/go' } }, { type: 'Java', version: '1.0.0', workspaceLabel: 'fabcar-contract-java', remote: { branch: 'master', path: 'chaincode/fabcar/java' } }, { type: 'JavaScript', version: '1.0.0', workspaceLabel: 'fabcar-contract-javascript', remote: { branch: 'master', path: 'chaincode/fabcar/javascript' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] }, { type: 'TypeScript', version: '1.0.0', workspaceLabel: 'fabcar-contract-typescript', remote: { branch: 'master', path: 'chaincode/fabcar/typescript' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] } ] } ], applications: [ { name: 'Java Application', type: 'Web', version: '1.0.0', language: 'Java', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'fabcar-app-java', remote: { branch: 'master', path: 'fabcar/java' } }, { name: 'JavaScript Application', type: 'Web', version: '1.0.0', language: 'JavaScript', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'fabcar-app-javascript', remote: { branch: 'master', path: 'fabcar/javascript' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] }, { name: 'TypeScript Application', type: 'Web', version: '1.0.0', language: 'TypeScript', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'fabcar-app-typescript', remote: { branch: 'master', path: 'fabcar/typescript' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] } ] } }, { name: 'Commercial Paper', description: 'Based on a real-world financial use-case, with multiple parties sharing a ledger.', readme: 'https://raw.githubusercontent.com/hyperledger/fabric-samples/master/README.md', category: { contracts: [ { name: 'Digibank Contract', languages: [ { type: 'Java', version: '0.0.1', workspaceLabel: 'cp-digibank-contract-java', remote: { branch: 'master', path: 'commercial-paper/organization/digibank/contract-java' } }, { type: 'JavaScript', version: '0.0.1', workspaceLabel: 'cp-digibank-contract-javascript', remote: { branch: 'master', path: 'commercial-paper/organization/digibank/contract' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] } ] }, { name: 'MagnetoCorp Contract', languages: [ { type: 'Java', version: '0.0.1', workspaceLabel: 'cp-magnetocorp-contract-java', remote: { branch: 'master', path: 'commercial-paper/organization/magnetocorp/contract-java' } }, { type: 'JavaScript', version: '0.0.1', workspaceLabel: 'cp-magnetocorp-contract-java', remote: { branch: 'master', path: 'commercial-paper/organization/magnetocorp/contract' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] } ] } ], applications: [ { name: 'Digibank Application', type: 'Web', version: '1.0.0', language: 'Java', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'cp-digibank-app-java', remote: { branch: 'master', path: 'commercial-paper/organization/digibank/application-java' } }, { name: 'Digibank Application', type: 'Web', version: '1.0.0', language: 'JavaScript', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'cp-digibank-app-javascript', remote: { branch: 'master', path: 'commercial-paper/organization/digibank/application' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] }, { name: 'MagnetoCorp Application', type: 'Web', version: '1.0.0', language: 'Java', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'cp-magnetocorp-contract-java', remote: { branch: 'master', path: 'commercial-paper/organization/magnetocorp/application-java' } }, { name: 'MagnetoCorp Application', type: 'Web', version: '1.0.0', language: 'JavaScript', readme: 'https://github.com/hyperledger/fabric-samples', workspaceLabel: 'cp-magnetocorp-contract-javascript', remote: { branch: 'master', path: 'commercial-paper/organization/magnetocorp/application' }, onOpen: [ { message: 'Installing Node.js dependencies ...', command: 'npm', arguments: ['install'] } ] } ] } } ] } ] }; const initialMessage: {path: string, repositoryData: { repositories: any[]} } = { path: '/samples', repositoryData: repositories }; before(async () => { await TestUtil.setupTests(mySandBox); }); beforeEach(async () => { context = GlobalState.getExtensionContext(); executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.callThrough(); createWebviewPanelStub = mySandBox.stub(vscode.window, 'createWebviewPanel'); postMessageStub = mySandBox.stub().resolves(); View['openPanels'].splice(0, View['openPanels'].length); mySandBox.stub(fs, 'readJson').resolves(repositories); }); afterEach(() => { mySandBox.restore(); }); it('should register and show the sample gallery', async () => { createWebviewPanelStub.returns({ title: 'Sample Gallery', webview: { postMessage: postMessageStub, onDidReceiveMessage: mySandBox.stub(), asWebviewUri: mySandBox.stub() }, reveal: mySandBox.stub(), dispose: mySandBox.stub(), onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub() }); const sampleGalleryView: SampleGalleryView = new SampleGalleryView(context); await sampleGalleryView.openView(false); createWebviewPanelStub.should.have.been.called; const call: sinon.SinonSpyCall = postMessageStub.getCall(0); call.args[0].should.deep.equal(initialMessage); }); it('should execute a command with args specified in a received message', async () => { onDidReceiveMessagePromises = []; onDidReceiveMessagePromises.push(new Promise((resolve: any): void => { createWebviewPanelStub.returns({ webview: { postMessage: mySandBox.stub(), onDidReceiveMessage: async (callback: any): Promise<void> => { await callback({ command: ExtensionCommands.OPEN_SAMPLE_PAGE, data: [ 'fabric-samples', 'FabCar' ] }); resolve(); }, asWebviewUri: mySandBox.stub() }, reveal: (): void => { return; }, onDidDispose: mySandBox.stub(), onDidChangeViewState: mySandBox.stub() }); })); executeCommandStub.withArgs(ExtensionCommands.OPEN_SAMPLE_PAGE).resolves(); const sampleGalleryView: SampleGalleryView = new SampleGalleryView(context); await sampleGalleryView.openView(false); await Promise.all(onDidReceiveMessagePromises); executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_SAMPLE_PAGE, 'fabric-samples', 'FabCar'); }); });
the_stack
import {Component, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Params} from "@angular/router"; import {ReportsService} from "./reports.service"; import {AppEvent, AppEventCode, AppService} from "../app.service"; import {ToastrService} from "../toastr.service"; import {TopNavService} from "../topnav.service"; import {ElasticSearchService} from "../elasticsearch.service"; import {EveboxSubscriptionTracker} from "../subscription-tracker"; import {loadingAnimation} from "../animations"; import {humanizeFileSize} from "../humanize.service"; import {ApiService} from "../api.service"; import { finalize } from "rxjs/operators"; import { Observable } from "rxjs"; import * as moment from "moment"; @Component({ template: ` <div class="content" [@loadingState]="(loading > 0) ? 'true' : 'false'"> <br/> <loading-spinner [loading]="loading > 0"></loading-spinner> <div class="row"> <div class="col-md-6 col-sm-6"> <button type="button" class="btn btn-secondary" (click)="refresh()"> Refresh </button> </div> <div class="col-md-6 col-sm-6"> <evebox-filter-input [queryString]="queryString"></evebox-filter-input> </div> </div> <br/> <div *ngIf="noEvents" style="text-align: center;"> <hr/> No netflow events found. <hr/> </div> <metrics-graphic *ngIf="eventsOverTime" graphId="eventsOverTime" title="Netflow Events Over Time" [data]="eventsOverTime"></metrics-graphic> <div class="row"> <div class="col-md-6"> <report-data-table *ngIf="topSourcesByBytes" title="Top Sources by Bytes" [rows]="topSourcesByBytes" [headers]="['#', 'Source']"></report-data-table> <br/> <report-data-table *ngIf="topSourcesByPackets" title="Top Sources by Packets" [rows]="topSourcesByPackets" [headers]="['#', 'Source']"> </report-data-table> </div> <br/> <div class="col-md-6"> <report-data-table *ngIf="topDestinationsByBytes" title="Top Destinations By Bytes" [rows]="topDestinationsByBytes" [headers]="['#', 'Destination']"></report-data-table> <br/> <report-data-table *ngIf="topDestinationsByPackets" title="Top Destinations by Packets" [rows]="topDestinationsByPackets" [headers]="['#', 'Destination']"> </report-data-table> </div> </div> <br/> <div *ngIf="topByBytes" class="card"> <div class="card-header"> <b>Top Flows by Bytes</b> </div> <eveboxEventTable2 [rows]="topByBytes" [showEventType]="false" [showActiveEvent]="false"></eveboxEventTable2> </div> <br/> <div *ngIf="topFlowsByPackets" class="card"> <div class="card-header"> <b>Top Flows by Packets</b> </div> <eveboxEventTable2 [rows]="topFlowsByPackets" [showEventType]="false" [showActiveEvent]="false"></eveboxEventTable2> </div> <br/> </div>`, animations: [ loadingAnimation, ] }) export class NetflowReportComponent implements OnInit, OnDestroy { eventsOverTime: any[]; topSourcesByBytes: any[]; topSourcesByPackets: any[]; topDestinationsByBytes: any[]; topDestinationsByPackets: any[]; topByBytes: any[]; topFlowsByPackets: any[]; loading = 0; queryString = ""; // A flag that will be set to true if not events to report on were found. noEvents = false; subTracker: EveboxSubscriptionTracker = new EveboxSubscriptionTracker(); constructor(private reportsService: ReportsService, private elasticsearch: ElasticSearchService, private appService: AppService, private route: ActivatedRoute, private toastr: ToastrService, private api: ApiService, private topNavService: TopNavService) { } ngOnInit() { this.route.queryParams.subscribe((params: Params) => { this.queryString = params["q"] || ""; this.refresh(); }); this.subTracker.subscribe(this.appService, (event: AppEvent) => { if (event.event === AppEventCode.TIME_RANGE_CHANGED) { this.refresh(); } }); } ngOnDestroy() { this.subTracker.unsubscribe(); } refresh() { this.checkForEvents().then((hasEvents: boolean) => { if (hasEvents) { this.load(); } else { this.noEvents = true; this.toastr.warning("No netflow events found."); } }); } checkForEvents() { let query: any = { query: { bool: { filter: [ // Somewhat limit to eve events of netflow only. {exists: {field: "event_type"}}, {term: {event_type: "netflow"}} ] } }, size: 0, }; return this.elasticsearch.search(query).then((response: any) => { return response.hits.total > 0; }); } private wrapPromise(fn: any) { this.loading++; fn().then(() => { this.loading--; }); } private wrapObservable(observable: Observable<any>) { this.loading++; return observable.pipe(finalize(() => { this.loading--; })); } load() { this.loading++; let range = this.topNavService.getTimeRangeAsSeconds(); let now = moment(); this.wrapPromise(() => { return this.api.reportHistogram({ timeRange: range, interval: this.reportsService.histogramTimeInterval(range), eventType: "netflow", queryString: this.queryString, }).then((response: any) => { this.eventsOverTime = response.data.map((x: any) => { return { date: moment(x.key).toDate(), value: x.count }; }); }); }); this.wrapObservable(this.api.eventQuery({ queryString: this.queryString, eventType: "netflow", size: 10, timeRange: range, sortBy: "netflow.pkts", sortOrder: "desc", })).subscribe((response) => { this.topFlowsByPackets = response.data; }); this.wrapObservable(this.api.eventQuery({ queryString: this.queryString, eventType: "netflow", size: 10, timeRange: range, sortBy: "netflow.bytes", sortOrder: "desc", })).subscribe((response) => { this.topByBytes = response.data; }); let query: any = { query: { bool: { filter: [ // Somewhat limit to eve events of netflow only. {exists: {field: "event_type"}}, {term: {event_type: "netflow"}} ] } }, size: 0, sort: [ {"@timestamp": {order: "desc"}} ], aggs: { sourcesByBytes: { terms: { field: this.elasticsearch.asKeyword("src_ip"), order: { "bytes": "desc" }, }, aggs: { bytes: { sum: { field: "netflow.bytes" } } } }, sourcesByPackets: { terms: { field: this.elasticsearch.asKeyword("src_ip"), order: { "packets": "desc" } }, aggs: { packets: { sum: { field: "netflow.pkts" } } } }, topDestinationsByBytes: { terms: { field: this.elasticsearch.asKeyword("dest_ip"), order: { "bytes": "desc" }, }, aggs: { bytes: { sum: { field: "netflow.bytes", } } } }, topDestinationsByPackets: { terms: { field: this.elasticsearch.asKeyword("dest_ip"), order: { "packets": "desc" }, }, aggs: { packets: { sum: { field: "netflow.pkts" } } } }, } }; if (this.queryString && this.queryString != "") { query.query.bool.filter.push({ query_string: { query: this.queryString } }); } this.elasticsearch.addTimeRangeFilter(query, now, range); this.elasticsearch.search(query).then((response: any) => { if (response.error) { console.log("Errors returned:"); console.log(response.error); let error = response.error; if (error.root_cause && error.root_cause.length > 0) { this.toastr.error(error.root_cause[0].reason); } this.loading--; return; } this.topSourcesByBytes = response.aggregations.sourcesByBytes.buckets.map((bucket: any) => { return { key: bucket.key, count: humanizeFileSize(bucket.bytes.value), }; }); this.topDestinationsByBytes = response.aggregations.topDestinationsByBytes.buckets.map((bucket: any) => { return { key: bucket.key, count: humanizeFileSize(bucket.bytes.value), }; }); this.topSourcesByPackets = response.aggregations.sourcesByPackets.buckets.map((bucket: any) => { return { key: bucket.key, count: bucket.packets.value, }; }); this.topDestinationsByPackets = response.aggregations.topDestinationsByPackets.buckets.map((bucket: any) => { return { key: bucket.key, count: bucket.packets.value, }; }); this.loading--; }, error => { console.log("Search error:"); console.log(error); this.loading--; }); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Manages an EKS Node Group, which can provision and optionally update an Auto Scaling Group of Kubernetes worker nodes compatible with EKS. Additional documentation about this functionality can be found in the [EKS User Guide](https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html). * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.eks.NodeGroup("example", { * clusterName: aws_eks_cluster.example.name, * nodeRoleArn: aws_iam_role.example.arn, * subnetIds: aws_subnet.example.map(__item => __item.id), * scalingConfig: { * desiredSize: 1, * maxSize: 1, * minSize: 1, * }, * updateConfig: { * maxUnavailable: 2, * }, * }, { * dependsOn: [ * aws_iam_role_policy_attachment["example-AmazonEKSWorkerNodePolicy"], * aws_iam_role_policy_attachment["example-AmazonEKS_CNI_Policy"], * aws_iam_role_policy_attachment["example-AmazonEC2ContainerRegistryReadOnly"], * ], * }); * ``` * ### Ignoring Changes to Desired Size * * You can utilize [ignoreChanges](https://www.pulumi.com/docs/intro/concepts/programming-model/#ignorechanges) create an EKS Node Group with an initial size of running instances, then ignore any changes to that count caused externally (e.g. Application Autoscaling). * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * // ... other configurations ... * const example = new aws.eks.NodeGroup("example", {scalingConfig: { * desiredSize: 2, * }}); * ``` * ### Example IAM Role for EKS Node Group * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.iam.Role("example", {assumeRolePolicy: JSON.stringify({ * Statement: [{ * Action: "sts:AssumeRole", * Effect: "Allow", * Principal: { * Service: "ec2.amazonaws.com", * }, * }], * Version: "2012-10-17", * })}); * const example_AmazonEKSWorkerNodePolicy = new aws.iam.RolePolicyAttachment("example-AmazonEKSWorkerNodePolicy", { * policyArn: "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy", * role: example.name, * }); * const example_AmazonEKSCNIPolicy = new aws.iam.RolePolicyAttachment("example-AmazonEKSCNIPolicy", { * policyArn: "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy", * role: example.name, * }); * const example_AmazonEC2ContainerRegistryReadOnly = new aws.iam.RolePolicyAttachment("example-AmazonEC2ContainerRegistryReadOnly", { * policyArn: "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly", * role: example.name, * }); * ``` * * ## Import * * EKS Node Groups can be imported using the `cluster_name` and `node_group_name` separated by a colon (`:`), e.g. * * ```sh * $ pulumi import aws:eks/nodeGroup:NodeGroup my_node_group my_cluster:my_node_group * ``` */ export class NodeGroup extends pulumi.CustomResource { /** * Get an existing NodeGroup 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?: NodeGroupState, opts?: pulumi.CustomResourceOptions): NodeGroup { return new NodeGroup(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:eks/nodeGroup:NodeGroup'; /** * Returns true if the given object is an instance of NodeGroup. 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 NodeGroup { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === NodeGroup.__pulumiType; } /** * Type of Amazon Machine Image (AMI) associated with the EKS Node Group. Defaults to `AL2_x86_64`. Valid values: `AL2_x86_64`, `AL2_x86_64_GPU`, `AL2_ARM_64`, `CUSTOM`. This provider will only perform drift detection if a configuration value is provided. */ public readonly amiType!: pulumi.Output<string>; /** * Amazon Resource Name (ARN) of the EKS Node Group. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Type of capacity associated with the EKS Node Group. Valid values: `ON_DEMAND`, `SPOT`. This provider will only perform drift detection if a configuration value is provided. */ public readonly capacityType!: pulumi.Output<string>; /** * Name of the EKS Cluster. Must be between 1-100 characters in length. Must begin with an alphanumeric character, and must only contain alphanumeric characters, dashes and underscores (`^[0-9A-Za-z][A-Za-z0-9\-_]+$`). */ public readonly clusterName!: pulumi.Output<string>; /** * Disk size in GiB for worker nodes. Defaults to `20`. This provider will only perform drift detection if a configuration value is provided. */ public readonly diskSize!: pulumi.Output<number>; /** * Force version update if existing pods are unable to be drained due to a pod disruption budget issue. */ public readonly forceUpdateVersion!: pulumi.Output<boolean | undefined>; /** * Set of instance types associated with the EKS Node Group. Defaults to `["t3.medium"]`. This provider will only perform drift detection if a configuration value is provided. */ public readonly instanceTypes!: pulumi.Output<string[]>; /** * Key-value map of Kubernetes labels. Only labels that are applied with the EKS API are managed by this argument. Other Kubernetes labels applied to the EKS Node Group will not be managed. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * Configuration block with Launch Template settings. Detailed below. */ public readonly launchTemplate!: pulumi.Output<outputs.eks.NodeGroupLaunchTemplate | undefined>; /** * Name of the EKS Node Group. If omitted, this provider will assign a random, unique name. Conflicts with `nodeGroupNamePrefix`. */ public readonly nodeGroupName!: pulumi.Output<string>; /** * Creates a unique name beginning with the specified prefix. Conflicts with `nodeGroupName`. */ public readonly nodeGroupNamePrefix!: pulumi.Output<string>; /** * Amazon Resource Name (ARN) of the IAM Role that provides permissions for the EKS Node Group. */ public readonly nodeRoleArn!: pulumi.Output<string>; /** * AMI version of the EKS Node Group. Defaults to latest version for Kubernetes version. */ public readonly releaseVersion!: pulumi.Output<string>; /** * Configuration block with remote access settings. Detailed below. */ public readonly remoteAccess!: pulumi.Output<outputs.eks.NodeGroupRemoteAccess | undefined>; /** * List of objects containing information about underlying resources. */ public /*out*/ readonly resources!: pulumi.Output<outputs.eks.NodeGroupResource[]>; /** * Configuration block with scaling settings. Detailed below. */ public readonly scalingConfig!: pulumi.Output<outputs.eks.NodeGroupScalingConfig>; /** * Status of the EKS Node Group. */ public /*out*/ readonly status!: pulumi.Output<string>; /** * Identifiers of EC2 Subnets to associate with the EKS Node Group. These subnets must have the following resource tag: `kubernetes.io/cluster/CLUSTER_NAME` (where `CLUSTER_NAME` is replaced with the name of the EKS Cluster). */ public readonly subnetIds!: pulumi.Output<string[]>; /** * Key-value map of resource tags. If configured with a provider defaultTags present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider. */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * The Kubernetes taints to be applied to the nodes in the node group. Maximum of 50 taints per node group. Detailed below. */ public readonly taints!: pulumi.Output<outputs.eks.NodeGroupTaint[] | undefined>; public readonly updateConfig!: pulumi.Output<outputs.eks.NodeGroupUpdateConfig>; /** * EC2 Launch Template version number. While the API accepts values like `$Default` and `$Latest`, the API will convert the value to the associated version number (e.g. `1`) on read and This provider will show a difference on next plan. Using the `defaultVersion` or `latestVersion` attribute of the `aws.ec2.LaunchTemplate` resource or data source is recommended for this argument. */ public readonly version!: pulumi.Output<string>; /** * Create a NodeGroup 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: NodeGroupArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: NodeGroupArgs | NodeGroupState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as NodeGroupState | undefined; inputs["amiType"] = state ? state.amiType : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["capacityType"] = state ? state.capacityType : undefined; inputs["clusterName"] = state ? state.clusterName : undefined; inputs["diskSize"] = state ? state.diskSize : undefined; inputs["forceUpdateVersion"] = state ? state.forceUpdateVersion : undefined; inputs["instanceTypes"] = state ? state.instanceTypes : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["launchTemplate"] = state ? state.launchTemplate : undefined; inputs["nodeGroupName"] = state ? state.nodeGroupName : undefined; inputs["nodeGroupNamePrefix"] = state ? state.nodeGroupNamePrefix : undefined; inputs["nodeRoleArn"] = state ? state.nodeRoleArn : undefined; inputs["releaseVersion"] = state ? state.releaseVersion : undefined; inputs["remoteAccess"] = state ? state.remoteAccess : undefined; inputs["resources"] = state ? state.resources : undefined; inputs["scalingConfig"] = state ? state.scalingConfig : undefined; inputs["status"] = state ? state.status : undefined; inputs["subnetIds"] = state ? state.subnetIds : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["taints"] = state ? state.taints : undefined; inputs["updateConfig"] = state ? state.updateConfig : undefined; inputs["version"] = state ? state.version : undefined; } else { const args = argsOrState as NodeGroupArgs | undefined; if ((!args || args.clusterName === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterName'"); } if ((!args || args.nodeRoleArn === undefined) && !opts.urn) { throw new Error("Missing required property 'nodeRoleArn'"); } if ((!args || args.scalingConfig === undefined) && !opts.urn) { throw new Error("Missing required property 'scalingConfig'"); } if ((!args || args.subnetIds === undefined) && !opts.urn) { throw new Error("Missing required property 'subnetIds'"); } inputs["amiType"] = args ? args.amiType : undefined; inputs["capacityType"] = args ? args.capacityType : undefined; inputs["clusterName"] = args ? args.clusterName : undefined; inputs["diskSize"] = args ? args.diskSize : undefined; inputs["forceUpdateVersion"] = args ? args.forceUpdateVersion : undefined; inputs["instanceTypes"] = args ? args.instanceTypes : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["launchTemplate"] = args ? args.launchTemplate : undefined; inputs["nodeGroupName"] = args ? args.nodeGroupName : undefined; inputs["nodeGroupNamePrefix"] = args ? args.nodeGroupNamePrefix : undefined; inputs["nodeRoleArn"] = args ? args.nodeRoleArn : undefined; inputs["releaseVersion"] = args ? args.releaseVersion : undefined; inputs["remoteAccess"] = args ? args.remoteAccess : undefined; inputs["scalingConfig"] = args ? args.scalingConfig : undefined; inputs["subnetIds"] = args ? args.subnetIds : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["taints"] = args ? args.taints : undefined; inputs["updateConfig"] = args ? args.updateConfig : undefined; inputs["version"] = args ? args.version : undefined; inputs["arn"] = undefined /*out*/; inputs["resources"] = undefined /*out*/; inputs["status"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(NodeGroup.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering NodeGroup resources. */ export interface NodeGroupState { /** * Type of Amazon Machine Image (AMI) associated with the EKS Node Group. Defaults to `AL2_x86_64`. Valid values: `AL2_x86_64`, `AL2_x86_64_GPU`, `AL2_ARM_64`, `CUSTOM`. This provider will only perform drift detection if a configuration value is provided. */ amiType?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the EKS Node Group. */ arn?: pulumi.Input<string>; /** * Type of capacity associated with the EKS Node Group. Valid values: `ON_DEMAND`, `SPOT`. This provider will only perform drift detection if a configuration value is provided. */ capacityType?: pulumi.Input<string>; /** * Name of the EKS Cluster. Must be between 1-100 characters in length. Must begin with an alphanumeric character, and must only contain alphanumeric characters, dashes and underscores (`^[0-9A-Za-z][A-Za-z0-9\-_]+$`). */ clusterName?: pulumi.Input<string>; /** * Disk size in GiB for worker nodes. Defaults to `20`. This provider will only perform drift detection if a configuration value is provided. */ diskSize?: pulumi.Input<number>; /** * Force version update if existing pods are unable to be drained due to a pod disruption budget issue. */ forceUpdateVersion?: pulumi.Input<boolean>; /** * Set of instance types associated with the EKS Node Group. Defaults to `["t3.medium"]`. This provider will only perform drift detection if a configuration value is provided. */ instanceTypes?: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of Kubernetes labels. Only labels that are applied with the EKS API are managed by this argument. Other Kubernetes labels applied to the EKS Node Group will not be managed. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block with Launch Template settings. Detailed below. */ launchTemplate?: pulumi.Input<inputs.eks.NodeGroupLaunchTemplate>; /** * Name of the EKS Node Group. If omitted, this provider will assign a random, unique name. Conflicts with `nodeGroupNamePrefix`. */ nodeGroupName?: pulumi.Input<string>; /** * Creates a unique name beginning with the specified prefix. Conflicts with `nodeGroupName`. */ nodeGroupNamePrefix?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the IAM Role that provides permissions for the EKS Node Group. */ nodeRoleArn?: pulumi.Input<string>; /** * AMI version of the EKS Node Group. Defaults to latest version for Kubernetes version. */ releaseVersion?: pulumi.Input<string>; /** * Configuration block with remote access settings. Detailed below. */ remoteAccess?: pulumi.Input<inputs.eks.NodeGroupRemoteAccess>; /** * List of objects containing information about underlying resources. */ resources?: pulumi.Input<pulumi.Input<inputs.eks.NodeGroupResource>[]>; /** * Configuration block with scaling settings. Detailed below. */ scalingConfig?: pulumi.Input<inputs.eks.NodeGroupScalingConfig>; /** * Status of the EKS Node Group. */ status?: pulumi.Input<string>; /** * Identifiers of EC2 Subnets to associate with the EKS Node Group. These subnets must have the following resource tag: `kubernetes.io/cluster/CLUSTER_NAME` (where `CLUSTER_NAME` is replaced with the name of the EKS Cluster). */ subnetIds?: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of resource tags. If configured with a provider defaultTags present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider. */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Kubernetes taints to be applied to the nodes in the node group. Maximum of 50 taints per node group. Detailed below. */ taints?: pulumi.Input<pulumi.Input<inputs.eks.NodeGroupTaint>[]>; updateConfig?: pulumi.Input<inputs.eks.NodeGroupUpdateConfig>; /** * EC2 Launch Template version number. While the API accepts values like `$Default` and `$Latest`, the API will convert the value to the associated version number (e.g. `1`) on read and This provider will show a difference on next plan. Using the `defaultVersion` or `latestVersion` attribute of the `aws.ec2.LaunchTemplate` resource or data source is recommended for this argument. */ version?: pulumi.Input<string>; } /** * The set of arguments for constructing a NodeGroup resource. */ export interface NodeGroupArgs { /** * Type of Amazon Machine Image (AMI) associated with the EKS Node Group. Defaults to `AL2_x86_64`. Valid values: `AL2_x86_64`, `AL2_x86_64_GPU`, `AL2_ARM_64`, `CUSTOM`. This provider will only perform drift detection if a configuration value is provided. */ amiType?: pulumi.Input<string>; /** * Type of capacity associated with the EKS Node Group. Valid values: `ON_DEMAND`, `SPOT`. This provider will only perform drift detection if a configuration value is provided. */ capacityType?: pulumi.Input<string>; /** * Name of the EKS Cluster. Must be between 1-100 characters in length. Must begin with an alphanumeric character, and must only contain alphanumeric characters, dashes and underscores (`^[0-9A-Za-z][A-Za-z0-9\-_]+$`). */ clusterName: pulumi.Input<string>; /** * Disk size in GiB for worker nodes. Defaults to `20`. This provider will only perform drift detection if a configuration value is provided. */ diskSize?: pulumi.Input<number>; /** * Force version update if existing pods are unable to be drained due to a pod disruption budget issue. */ forceUpdateVersion?: pulumi.Input<boolean>; /** * Set of instance types associated with the EKS Node Group. Defaults to `["t3.medium"]`. This provider will only perform drift detection if a configuration value is provided. */ instanceTypes?: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of Kubernetes labels. Only labels that are applied with the EKS API are managed by this argument. Other Kubernetes labels applied to the EKS Node Group will not be managed. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block with Launch Template settings. Detailed below. */ launchTemplate?: pulumi.Input<inputs.eks.NodeGroupLaunchTemplate>; /** * Name of the EKS Node Group. If omitted, this provider will assign a random, unique name. Conflicts with `nodeGroupNamePrefix`. */ nodeGroupName?: pulumi.Input<string>; /** * Creates a unique name beginning with the specified prefix. Conflicts with `nodeGroupName`. */ nodeGroupNamePrefix?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the IAM Role that provides permissions for the EKS Node Group. */ nodeRoleArn: pulumi.Input<string>; /** * AMI version of the EKS Node Group. Defaults to latest version for Kubernetes version. */ releaseVersion?: pulumi.Input<string>; /** * Configuration block with remote access settings. Detailed below. */ remoteAccess?: pulumi.Input<inputs.eks.NodeGroupRemoteAccess>; /** * Configuration block with scaling settings. Detailed below. */ scalingConfig: pulumi.Input<inputs.eks.NodeGroupScalingConfig>; /** * Identifiers of EC2 Subnets to associate with the EKS Node Group. These subnets must have the following resource tag: `kubernetes.io/cluster/CLUSTER_NAME` (where `CLUSTER_NAME` is replaced with the name of the EKS Cluster). */ subnetIds: pulumi.Input<pulumi.Input<string>[]>; /** * Key-value map of resource tags. If configured with a provider defaultTags present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Kubernetes taints to be applied to the nodes in the node group. Maximum of 50 taints per node group. Detailed below. */ taints?: pulumi.Input<pulumi.Input<inputs.eks.NodeGroupTaint>[]>; updateConfig?: pulumi.Input<inputs.eks.NodeGroupUpdateConfig>; /** * EC2 Launch Template version number. While the API accepts values like `$Default` and `$Latest`, the API will convert the value to the associated version number (e.g. `1`) on read and This provider will show a difference on next plan. Using the `defaultVersion` or `latestVersion` attribute of the `aws.ec2.LaunchTemplate` resource or data source is recommended for this argument. */ version?: pulumi.Input<string>; }
the_stack
import { DisplayObject } from '@pixi/display'; import { isMobile, removeItems } from '@pixi/utils'; import { accessibleTarget } from './accessibleTarget'; import type { Rectangle } from '@pixi/math'; import type { Container } from '@pixi/display'; import type { Renderer, AbstractRenderer } from '@pixi/core'; import type { IAccessibleHTMLElement } from './accessibleTarget'; // add some extra variables to the container.. DisplayObject.mixin(accessibleTarget); const KEY_CODE_TAB = 9; const DIV_TOUCH_SIZE = 100; const DIV_TOUCH_POS_X = 0; const DIV_TOUCH_POS_Y = 0; const DIV_TOUCH_ZINDEX = 2; const DIV_HOOK_SIZE = 1; const DIV_HOOK_POS_X = -1000; const DIV_HOOK_POS_Y = -1000; const DIV_HOOK_ZINDEX = 2; /** * The Accessibility manager recreates the ability to tab and have content read by screen readers. * This is very important as it can possibly help people with disabilities access PixiJS content. * * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the * events as if the mouse was being used, minimizing the effort required to implement. * * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` * * @class * @memberof PIXI */ export class AccessibilityManager { /** Setting this to true will visually show the divs. */ public debug = false; /** * The renderer this accessibility manager works for. * * @type {PIXI.CanvasRenderer|PIXI.Renderer} */ public renderer: AbstractRenderer|Renderer; /** Internal variable, see isActive getter. */ private _isActive = false; /** Internal variable, see isMobileAccessibility getter. */ private _isMobileAccessibility = false; /** Button element for handling touch hooks. */ private _hookDiv: HTMLElement; /** This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. */ private div: HTMLElement; /** A simple pool for storing divs. */ private pool: IAccessibleHTMLElement[] = []; /** This is a tick used to check if an object is no longer being rendered. */ private renderId = 0; /** The array of currently active accessible items. */ private children: DisplayObject[] = []; /** Count to throttle div updates on android devices. */ private androidUpdateCount = 0; /** The frequency to update the div elements. */ private androidUpdateFrequency = 500; // 2fps /** * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer */ constructor(renderer: AbstractRenderer|Renderer) { this._hookDiv = null; if (isMobile.tablet || isMobile.phone) { this.createTouchHook(); } // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. const div = document.createElement('div'); div.style.width = `${DIV_TOUCH_SIZE}px`; div.style.height = `${DIV_TOUCH_SIZE}px`; div.style.position = 'absolute'; div.style.top = `${DIV_TOUCH_POS_X}px`; div.style.left = `${DIV_TOUCH_POS_Y}px`; div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); this.div = div; this.renderer = renderer; /** * pre-bind the functions * * @type {Function} * @private */ this._onKeyDown = this._onKeyDown.bind(this); /** * pre-bind the functions * * @type {Function} * @private */ this._onMouseMove = this._onMouseMove.bind(this); // let listen for tab.. once pressed we can fire up and show the accessibility layer self.addEventListener('keydown', this._onKeyDown, false); } /** * Value of `true` if accessibility is currently active and accessibility layers are showing. * @member {boolean} * @readonly */ get isActive(): boolean { return this._isActive; } /** * Value of `true` if accessibility is enabled for touch devices. * @member {boolean} * @readonly */ get isMobileAccessibility(): boolean { return this._isMobileAccessibility; } /** * Creates the touch hooks. * * @private */ private createTouchHook(): void { const hookDiv = document.createElement('button'); hookDiv.style.width = `${DIV_HOOK_SIZE}px`; hookDiv.style.height = `${DIV_HOOK_SIZE}px`; hookDiv.style.position = 'absolute'; hookDiv.style.top = `${DIV_HOOK_POS_X}px`; hookDiv.style.left = `${DIV_HOOK_POS_Y}px`; hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); hookDiv.style.backgroundColor = '#FF0000'; hookDiv.title = 'select to enable accessibility for this content'; hookDiv.addEventListener('focus', () => { this._isMobileAccessibility = true; this.activate(); this.destroyTouchHook(); }); document.body.appendChild(hookDiv); this._hookDiv = hookDiv; } /** * Destroys the touch hooks. * * @private */ private destroyTouchHook(): void { if (!this._hookDiv) { return; } document.body.removeChild(this._hookDiv); this._hookDiv = null; } /** * Activating will cause the Accessibility layer to be shown. * This is called when a user presses the tab key. * * @private */ private activate(): void { if (this._isActive) { return; } this._isActive = true; self.document.addEventListener('mousemove', this._onMouseMove, true); self.removeEventListener('keydown', this._onKeyDown, false); this.renderer.on('postrender', this.update, this); this.renderer.view.parentNode?.appendChild(this.div); } /** * Deactivating will cause the Accessibility layer to be hidden. * This is called when a user moves the mouse. * * @private */ private deactivate(): void { if (!this._isActive || this._isMobileAccessibility) { return; } this._isActive = false; self.document.removeEventListener('mousemove', this._onMouseMove, true); self.addEventListener('keydown', this._onKeyDown, false); this.renderer.off('postrender', this.update); this.div.parentNode?.removeChild(this.div); } /** * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. * * @private * @param {PIXI.Container} displayObject - The DisplayObject to check. */ private updateAccessibleObjects(displayObject: Container): void { if (!displayObject.visible || !displayObject.accessibleChildren) { return; } if (displayObject.accessible && displayObject.interactive) { if (!displayObject._accessibleActive) { this.addChild(displayObject); } displayObject.renderId = this.renderId; } const children = displayObject.children; if (children) { for (let i = 0; i < children.length; i++) { this.updateAccessibleObjects(children[i] as Container); } } } /** * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. * * @private */ private update(): void { /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, * so I am just running update every half a second, seems to fix it. */ const now = performance.now(); if (isMobile.android.device && now < this.androidUpdateCount) { return; } this.androidUpdateCount = now + this.androidUpdateFrequency; if (!(this.renderer as Renderer).renderingToScreen) { return; } // update children... if (this.renderer._lastObjectRendered) { this.updateAccessibleObjects(this.renderer._lastObjectRendered as Container); } const { left, top, width, height } = this.renderer.view.getBoundingClientRect(); const { width: viewWidth, height: viewHeight, resolution } = this.renderer; const sx = (width / viewWidth) * resolution; const sy = (height / viewHeight) * resolution; let div = this.div; div.style.left = `${left}px`; div.style.top = `${top}px`; div.style.width = `${viewWidth}px`; div.style.height = `${viewHeight}px`; for (let i = 0; i < this.children.length; i++) { const child = this.children[i]; if (child.renderId !== this.renderId) { child._accessibleActive = false; removeItems(this.children, i, 1); this.div.removeChild(child._accessibleDiv); this.pool.push(child._accessibleDiv); child._accessibleDiv = null; i--; } else { // map div to display.. div = child._accessibleDiv; let hitArea = child.hitArea as Rectangle; const wt = child.worldTransform; if (child.hitArea) { div.style.left = `${(wt.tx + (hitArea.x * wt.a)) * sx}px`; div.style.top = `${(wt.ty + (hitArea.y * wt.d)) * sy}px`; div.style.width = `${hitArea.width * wt.a * sx}px`; div.style.height = `${hitArea.height * wt.d * sy}px`; } else { hitArea = child.getBounds(); this.capHitArea(hitArea); div.style.left = `${hitArea.x * sx}px`; div.style.top = `${hitArea.y * sy}px`; div.style.width = `${hitArea.width * sx}px`; div.style.height = `${hitArea.height * sy}px`; // update button titles and hints if they exist and they've changed if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { div.title = child.accessibleTitle; } if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { div.setAttribute('aria-label', child.accessibleHint); } } // the title or index may have changed, if so lets update it! if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { div.title = child.accessibleTitle; div.tabIndex = child.tabIndex; if (this.debug) this.updateDebugHTML(div); } } } // increment the render id.. this.renderId++; } /** * private function that will visually add the information to the * accessability div * * @param {HTMLElement} div */ public updateDebugHTML(div: IAccessibleHTMLElement): void { div.innerHTML = `type: ${div.type}</br> title : ${div.title}</br> tabIndex: ${div.tabIndex}`; } /** * Adjust the hit area based on the bounds of a display object * * @param {PIXI.Rectangle} hitArea - Bounds of the child */ public capHitArea(hitArea: Rectangle): void { if (hitArea.x < 0) { hitArea.width += hitArea.x; hitArea.x = 0; } if (hitArea.y < 0) { hitArea.height += hitArea.y; hitArea.y = 0; } const { width: viewWidth, height: viewHeight } = this.renderer; if (hitArea.x + hitArea.width > viewWidth) { hitArea.width = viewWidth - hitArea.x; } if (hitArea.y + hitArea.height > viewHeight) { hitArea.height = viewHeight - hitArea.y; } } /** * Adds a DisplayObject to the accessibility manager * * @private * @param {PIXI.DisplayObject} displayObject - The child to make accessible. */ private addChild<T extends DisplayObject>(displayObject: T): void { // this.activate(); let div = this.pool.pop(); if (!div) { div = document.createElement('button'); div.style.width = `${DIV_TOUCH_SIZE}px`; div.style.height = `${DIV_TOUCH_SIZE}px`; div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; div.style.position = 'absolute'; div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); div.style.borderStyle = 'none'; // ARIA attributes ensure that button title and hint updates are announced properly if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. div.setAttribute('aria-live', 'off'); } else { div.setAttribute('aria-live', 'polite'); } if (navigator.userAgent.match(/rv:.*Gecko\//)) { // FireFox needs this to announce only the new button name div.setAttribute('aria-relevant', 'additions'); } else { // required by IE, other browsers don't much care div.setAttribute('aria-relevant', 'text'); } div.addEventListener('click', this._onClick.bind(this)); div.addEventListener('focus', this._onFocus.bind(this)); div.addEventListener('focusout', this._onFocusOut.bind(this)); } // set pointer events div.style.pointerEvents = displayObject.accessiblePointerEvents; // set the type, this defaults to button! div.type = displayObject.accessibleType; if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { div.title = displayObject.accessibleTitle; } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { div.title = `displayObject ${displayObject.tabIndex}`; } if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { div.setAttribute('aria-label', displayObject.accessibleHint); } if (this.debug) this.updateDebugHTML(div); displayObject._accessibleActive = true; displayObject._accessibleDiv = div; div.displayObject = displayObject; this.children.push(displayObject); this.div.appendChild(displayObject._accessibleDiv); displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; } /** * Maps the div button press to pixi's InteractionManager (click) * * @private * @param {MouseEvent} e - The click event. */ private _onClick(e: MouseEvent): void { const interactionManager = this.renderer.plugins.interaction; const { displayObject } = e.target as IAccessibleHTMLElement; const { eventData } = interactionManager; interactionManager.dispatchEvent(displayObject, 'click', eventData); interactionManager.dispatchEvent(displayObject, 'pointertap', eventData); interactionManager.dispatchEvent(displayObject, 'tap', eventData); } /** * Maps the div focus events to pixi's InteractionManager (mouseover) * * @private * @param {FocusEvent} e - The focus event. */ private _onFocus(e: FocusEvent): void { if (!(e.target as Element).getAttribute('aria-live')) { (e.target as Element).setAttribute('aria-live', 'assertive'); } const interactionManager = this.renderer.plugins.interaction; const { displayObject } = e.target as IAccessibleHTMLElement; const { eventData } = interactionManager; interactionManager.dispatchEvent(displayObject, 'mouseover', eventData); } /** * Maps the div focus events to pixi's InteractionManager (mouseout) * * @private * @param {FocusEvent} e - The focusout event. */ private _onFocusOut(e: FocusEvent): void { if (!(e.target as Element).getAttribute('aria-live')) { (e.target as Element).setAttribute('aria-live', 'polite'); } const interactionManager = this.renderer.plugins.interaction; const { displayObject } = e.target as IAccessibleHTMLElement; const { eventData } = interactionManager; interactionManager.dispatchEvent(displayObject, 'mouseout', eventData); } /** * Is called when a key is pressed * * @private * @param {KeyboardEvent} e - The keydown event. */ private _onKeyDown(e: KeyboardEvent): void { if (e.keyCode !== KEY_CODE_TAB) { return; } this.activate(); } /** * Is called when the mouse moves across the renderer element * * @private * @param {MouseEvent} e - The mouse event. */ private _onMouseMove(e: MouseEvent): void { if (e.movementX === 0 && e.movementY === 0) { return; } this.deactivate(); } /** * Destroys the accessibility manager * */ public destroy(): void { this.destroyTouchHook(); this.div = null; self.document.removeEventListener('mousemove', this._onMouseMove, true); self.removeEventListener('keydown', this._onKeyDown); this.pool = null; this.children = null; this.renderer = null; } }
the_stack
import moment from 'moment-es6'; import { WidgetVisibilityModel } from '../../../models/widget-visibility.model'; import { ContainerColumnModel } from './container-column.model'; import { ErrorMessageModel } from './error-message.model'; import { FormFieldMetadata } from './form-field-metadata'; import { FormFieldOption } from './form-field-option'; import { FormFieldTypes } from './form-field-types'; import { NumberFieldValidator } from './form-field-validator'; import { FormWidgetModel } from './form-widget.model'; import { FormModel } from './form.model'; // Maps to FormFieldRepresentation export class FormFieldModel extends FormWidgetModel { private _value: string; private _readOnly: boolean = false; private _isValid: boolean = true; private _required: boolean = false; readonly defaultDateFormat: string = 'D-M-YYYY'; readonly defaultDateTimeFormat: string = 'D-M-YYYY hh:mm A'; // model members fieldType: string; id: string; name: string; type: string; overrideId: boolean; tab: string; rowspan: number = 1; colspan: number = 1; placeholder: string = null; tooltip: string = null; minLength: number = 0; maxLength: number = 0; minValue: string; maxValue: string; regexPattern: string; options: FormFieldOption[] = []; restUrl: string; roles: string[]; restResponsePath: string; restIdProperty: string; restLabelProperty: string; hasEmptyValue: boolean; className: string; optionType: string; params: FormFieldMetadata = {}; hyperlinkUrl: string; displayText: string; isVisible: boolean = true; visibilityCondition: WidgetVisibilityModel = null; enableFractions: boolean = false; currency: string = null; dateDisplayFormat: string = this.defaultDateFormat; // container model members numberOfColumns: number = 1; fields: FormFieldModel[] = []; columns: ContainerColumnModel[] = []; // util members emptyOption: FormFieldOption; validationSummary: ErrorMessageModel; get value(): any { return this._value; } set value(v: any) { this._value = v; this.updateForm(); } get readOnly(): boolean { if (this.form && this.form.readOnly) { return true; } return this._readOnly; } set readOnly(readOnly: boolean) { this._readOnly = readOnly; this.updateForm(); } get required(): boolean { return this._required; } set required(value: boolean) { this._required = value; this.updateForm(); } get isValid(): boolean { return this._isValid; } markAsInvalid() { this._isValid = false; } validate(): boolean { this.validationSummary = new ErrorMessageModel(); if (!this.readOnly) { const validators = this.form.fieldValidators || []; for (const validator of validators) { if (!validator.validate(this)) { this._isValid = false; return this._isValid; } } } this._isValid = true; return this._isValid; } constructor(form: FormModel, json?: any) { super(form, json); if (json) { this.fieldType = json.fieldType; this.id = json.id; this.name = json.name; this.type = json.type; this.roles = json.roles; this._required = <boolean> json.required; this._readOnly = <boolean> json.readOnly || json.type === 'readonly'; this.overrideId = <boolean> json.overrideId; this.tab = json.tab; this.restUrl = json.restUrl; this.restResponsePath = json.restResponsePath; this.restIdProperty = json.restIdProperty; this.restLabelProperty = json.restLabelProperty; this.colspan = <number> json.colspan; this.rowspan = <number> json.rowspan; this.minLength = <number> json.minLength || 0; this.maxLength = <number> json.maxLength || 0; this.minValue = json.minValue; this.maxValue = json.maxValue; this.regexPattern = json.regexPattern; this.options = <FormFieldOption[]> json.options || []; this.hasEmptyValue = <boolean> json.hasEmptyValue; this.className = json.className; this.optionType = json.optionType; this.params = <FormFieldMetadata> json.params || {}; this.hyperlinkUrl = json.hyperlinkUrl; this.displayText = json.displayText; this.visibilityCondition = json.visibilityCondition ? new WidgetVisibilityModel(json.visibilityCondition) : undefined; this.enableFractions = <boolean> json.enableFractions; this.currency = json.currency; this.dateDisplayFormat = json.dateDisplayFormat || this.getDefaultDateFormat(json); this._value = this.parseValue(json); this.validationSummary = new ErrorMessageModel(); this.tooltip = json.tooltip; if (json.placeholder && json.placeholder !== '' && json.placeholder !== 'null') { this.placeholder = json.placeholder; } if (FormFieldTypes.isReadOnlyType(this.type)) { if (this.params && this.params.field) { let valueFound = false; if (form.processVariables) { const processVariable = this.getProcessVariableValue(this.params.field, form); if (processVariable) { valueFound = true; this.value = processVariable; } } if (!valueFound && this.params.responseVariable) { const defaultValue = form.getFormVariableValue(this.params.field.name); if (defaultValue) { valueFound = true; this.value = defaultValue; } } } } if (FormFieldTypes.isContainerType(this.type)) { this.containerFactory(json, form); } } if (this.hasEmptyValue && this.options && this.options.length > 0) { this.emptyOption = this.options[0]; } this.updateForm(); } private getDefaultDateFormat(jsonField: any): string { let originalType = jsonField.type; if (FormFieldTypes.isReadOnlyType(jsonField.type) && jsonField.params && jsonField.params.field) { originalType = jsonField.params.field.type; } return originalType === FormFieldTypes.DATETIME ? this.defaultDateTimeFormat : this.defaultDateFormat; } private isTypeaheadFieldType(type: string): boolean { return type === 'typeahead'; } private getFieldNameWithLabel(name: string): string { return name + '_LABEL'; } private getProcessVariableValue(field: any, form: FormModel): any { let fieldName = field.name; if (this.isTypeaheadFieldType(field.type)) { fieldName = this.getFieldNameWithLabel(field.id); } return form.getProcessVariableValue(fieldName); } private containerFactory(json: any, form: FormModel): void { this.numberOfColumns = <number> json.numberOfColumns || 1; this.fields = json.fields; this.rowspan = 1; this.colspan = 1; if (json.fields) { for (const currentField in json.fields) { if (json.fields.hasOwnProperty(currentField)) { const col = new ContainerColumnModel(); const fields: FormFieldModel[] = (json.fields[currentField] || []).map((field) => new FormFieldModel(form, field)); col.fields = fields; col.rowspan = json.fields[currentField].length; col.fields.forEach((colFields: any) => { this.colspan = colFields.colspan > this.colspan ? colFields.colspan : this.colspan; }); this.rowspan = this.rowspan < col.rowspan ? col.rowspan : this.rowspan; this.columns.push(col); } } } } parseValue(json: any): any { let value = json.hasOwnProperty('value') && json.value !== undefined ? json.value : null; /* This is needed due to Activiti issue related to reading dropdown values as value string but saving back as object: { id: <id>, name: <name> } */ if (json.type === FormFieldTypes.DROPDOWN) { if (json.options) { const options = <FormFieldOption[]> json.options || []; if (options.length > 0) { if (json.hasEmptyValue) { const emptyOption = json.options[0]; if (value === '' || value === emptyOption.id || value === emptyOption.name) { value = emptyOption.id; } } else { if (value?.id && value?.name) { value = value.id; } } } } } /* This is needed due to Activiti issue related to reading radio button values as value string but saving back as object: { id: <id>, name: <name> } */ if (json.type === FormFieldTypes.RADIO_BUTTONS) { // Activiti has a bug with default radio button value where initial selection passed as `name` value // so try resolving current one with a fallback to first entry via name or id // TODO: needs to be reported and fixed at Activiti side const entry: FormFieldOption[] = this.options.filter((opt) => opt.id === value || opt.name === value || (value && (opt.id === value.id || opt.name === value.name))); if (entry.length > 0) { value = entry[0].id; } } /* This is needed due to Activiti displaying/editing dates in d-M-YYYY format but storing on server in ISO8601 format (i.e. 2013-02-04T22:44:30.652Z) */ if (this.isDateField(json) || this.isDateTimeField(json)) { if (value) { let dateValue; if (NumberFieldValidator.isNumber(value)) { dateValue = moment(value); } else { dateValue = this.isDateTimeField(json) ? moment(value, 'YYYY-MM-DD hh:mm A') : moment(value.split('T')[0], 'YYYY-M-D'); } if (dateValue && dateValue.isValid()) { value = dateValue.format(this.dateDisplayFormat); } } } if (this.isCheckboxField(json)) { value = json.value === 'true' || json.value === true; } return value; } updateForm() { if (!this.form) { return; } switch (this.type) { case FormFieldTypes.DROPDOWN: /* This is needed due to Activiti reading dropdown values as string but saving back as object: { id: <id>, name: <name> } */ if (this.value === 'empty' || this.value === '') { this.form.values[this.id] = {}; } else { const entry: FormFieldOption[] = this.options.filter((opt) => opt.id === this.value); if (entry.length > 0) { this.form.values[this.id] = entry[0]; } } break; case FormFieldTypes.RADIO_BUTTONS: /* This is needed due to Activiti issue related to reading radio button values as value string but saving back as object: { id: <id>, name: <name> } */ const radioButton: FormFieldOption[] = this.options.filter((opt) => opt.id === this.value); if (radioButton.length > 0) { this.form.values[this.id] = radioButton[0]; } break; case FormFieldTypes.UPLOAD: this.form.hasUpload = true; if (this.value && this.value.length > 0) { this.form.values[this.id] = Array.isArray(this.value) ? this.value.map((elem) => elem.id).join(',') : [this.value]; } else { this.form.values[this.id] = null; } break; case FormFieldTypes.TYPEAHEAD: const typeAheadEntry: FormFieldOption[] = this.options.filter((opt) => opt.id === this.value || opt.name === this.value); if (typeAheadEntry.length > 0) { this.form.values[this.id] = typeAheadEntry[0]; } else if (this.options.length > 0) { this.form.values[this.id] = null; } break; case FormFieldTypes.DATE: if (typeof this.value === 'string' && this.value === 'today') { this.value = moment(new Date()).format(this.dateDisplayFormat); } const dateValue = moment(this.value, this.dateDisplayFormat, true); if (dateValue && dateValue.isValid()) { this.form.values[this.id] = `${dateValue.format('YYYY-MM-DD')}T00:00:00.000Z`; } else { this.form.values[this.id] = null; this._value = this.value; } break; case FormFieldTypes.DATETIME: if (typeof this.value === 'string' && this.value === 'now') { this.value = moment(new Date()).format(this.dateDisplayFormat); } const dateTimeValue = moment(this.value, this.dateDisplayFormat, true).utc(); if (dateTimeValue && dateTimeValue.isValid()) { /* cspell:disable-next-line */ this.form.values[this.id] = `${dateTimeValue.format('YYYY-MM-DDTHH:mm:ss')}.000Z`; } else { this.form.values[this.id] = null; this._value = this.value; } break; case FormFieldTypes.NUMBER: this.form.values[this.id] = this.enableFractions ? parseFloat(this.value) : parseInt(this.value, 10); break; case FormFieldTypes.AMOUNT: this.form.values[this.id] = this.enableFractions ? parseFloat(this.value) : parseInt(this.value, 10); break; case FormFieldTypes.BOOLEAN: this.form.values[this.id] = (this.value !== null && this.value !== undefined) ? this.value : false; break; case FormFieldTypes.PEOPLE: this.form.values[this.id] = this.value ? this.value : null; break; case FormFieldTypes.FUNCTIONAL_GROUP: this.form.values[this.id] = this.value ? this.value : null; break; default: if (!FormFieldTypes.isReadOnlyType(this.type) && !this.isInvalidFieldType(this.type)) { this.form.values[this.id] = this.value; } } this.form.onFormFieldChanged(this); } /** * Skip the invalid field type * @param type */ isInvalidFieldType(type: string) { return type === 'container'; } getOptionName(): string { const option: FormFieldOption = this.options.find((opt) => opt.id === this.value); return option ? option.name : null; } hasOptions() { return this.options && this.options.length > 0; } private isDateField(json: any) { return (json.params && json.params.field && json.params.field.type === FormFieldTypes.DATE) || json.type === FormFieldTypes.DATE; } private isDateTimeField(json: any): boolean { return (json.params && json.params.field && json.params.field.type === FormFieldTypes.DATETIME) || json.type === FormFieldTypes.DATETIME; } private isCheckboxField(json: any): boolean { return (json.params && json.params.field && json.params.field.type === FormFieldTypes.BOOLEAN) || json.type === FormFieldTypes.BOOLEAN; } }
the_stack
import { Observable, ObservableInput } from '../Observable'; import { ArrayObservable } from '../observable/ArrayObservable'; import { isArray } from '../util/isArray'; import { Operator } from '../Operator'; import { PartialObserver } from '../Observer'; import { Subscriber } from '../Subscriber'; import { OuterSubscriber } from '../OuterSubscriber'; import { InnerSubscriber } from '../InnerSubscriber'; import { subscribeToResult } from '../util/subscribeToResult'; import { $$iterator } from '../symbol/iterator'; /* tslint:disable:max-line-length */ export function zipProto<T, R>(this: Observable<T>, project: (v1: T) => R): Observable<R>; export function zipProto<T, T2, R>(this: Observable<T>, v2: ObservableInput<T2>, project: (v1: T, v2: T2) => R): Observable<R>; export function zipProto<T, T2, T3, R>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, project: (v1: T, v2: T2, v3: T3) => R): Observable<R>; export function zipProto<T, T2, T3, T4, R>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): Observable<R>; export function zipProto<T, T2, T3, T4, T5, R>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): Observable<R>; export function zipProto<T, T2, T3, T4, T5, T6, R>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): Observable<R> ; export function zipProto<T, T2>(this: Observable<T>, v2: ObservableInput<T2>): Observable<[T, T2]>; export function zipProto<T, T2, T3>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<[T, T2, T3]>; export function zipProto<T, T2, T3, T4>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<[T, T2, T3, T4]>; export function zipProto<T, T2, T3, T4, T5>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<[T, T2, T3, T4, T5]>; export function zipProto<T, T2, T3, T4, T5, T6>(this: Observable<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<[T, T2, T3, T4, T5, T6]> ; export function zipProto<T, R>(this: Observable<T>, ...observables: Array<ObservableInput<T> | ((...values: Array<T>) => R)>): Observable<R>; export function zipProto<T, R>(this: Observable<T>, array: Array<ObservableInput<T>>): Observable<R>; export function zipProto<T, TOther, R>(this: Observable<T>, array: Array<ObservableInput<TOther>>, project: (v1: T, ...values: Array<TOther>) => R): Observable<R>; /* tslint:enable:max-line-length */ /** * @param observables * @return {Observable<R>} * @method zip * @owner Observable */ export function zipProto<T, R>(this: Observable<T>, ...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R> { return this.lift.call(zipStatic<R>(this, ...observables)); } /* tslint:disable:max-line-length */ export function zipStatic<T, T2>(v1: ObservableInput<T>, v2: ObservableInput<T2>): Observable<[T, T2]>; export function zipStatic<T, T2, T3>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>): Observable<[T, T2, T3]>; export function zipStatic<T, T2, T3, T4>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>): Observable<[T, T2, T3, T4]>; export function zipStatic<T, T2, T3, T4, T5>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>): Observable<[T, T2, T3, T4, T5]>; export function zipStatic<T, T2, T3, T4, T5, T6>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>): Observable<[T, T2, T3, T4, T5, T6]>; export function zipStatic<T, R>(v1: ObservableInput<T>, project: (v1: T) => R): Observable<R>; export function zipStatic<T, T2, R>(v1: ObservableInput<T>, v2: ObservableInput<T2>, project: (v1: T, v2: T2) => R): Observable<R>; export function zipStatic<T, T2, T3, R>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, project: (v1: T, v2: T2, v3: T3) => R): Observable<R>; export function zipStatic<T, T2, T3, T4, R>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, project: (v1: T, v2: T2, v3: T3, v4: T4) => R): Observable<R>; export function zipStatic<T, T2, T3, T4, T5, R>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => R): Observable<R>; export function zipStatic<T, T2, T3, T4, T5, T6, R>(v1: ObservableInput<T>, v2: ObservableInput<T2>, v3: ObservableInput<T3>, v4: ObservableInput<T4>, v5: ObservableInput<T5>, v6: ObservableInput<T6>, project: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => R): Observable<R>; export function zipStatic<T>(array: ObservableInput<T>[]): Observable<T[]>; export function zipStatic<R>(array: ObservableInput<any>[]): Observable<R>; export function zipStatic<T, R>(array: ObservableInput<T>[], project: (...values: Array<T>) => R): Observable<R>; export function zipStatic<R>(array: ObservableInput<any>[], project: (...values: Array<any>) => R): Observable<R>; export function zipStatic<T>(...observables: Array<ObservableInput<T>>): Observable<T[]>; export function zipStatic<T, R>(...observables: Array<ObservableInput<T> | ((...values: Array<T>) => R)>): Observable<R>; export function zipStatic<R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R>; /* tslint:enable:max-line-length */ /** * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each * of its input Observables. * * If the latest parameter is a function, this function is used to compute the created value from the input values. * Otherwise, an array of the input values is returned. * * @example <caption>Combine age and name from different sources</caption> * * let age$ = Observable.of<number>(27, 25, 29); * let name$ = Observable.of<string>('Foo', 'Bar', 'Beer'); * let isDev$ = Observable.of<boolean>(true, true, false); * * Observable * .zip(age$, * name$, * isDev$, * (age: number, name: string, isDev: boolean) => ({ age, name, isDev })) * .subscribe(x => console.log(x)); * * // outputs * // { age: 27, name: 'Foo', isDev: true } * // { age: 25, name: 'Bar', isDev: true } * // { age: 29, name: 'Beer', isDev: false } * * @param observables * @return {Observable<R>} * @static true * @name zip * @owner Observable */ export function zipStatic<T, R>(...observables: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): Observable<R> { const project = <((...ys: Array<any>) => R)> observables[observables.length - 1]; if (typeof project === 'function') { observables.pop(); } return new ArrayObservable(observables).lift(new ZipOperator(project)); } export class ZipOperator<T, R> implements Operator<T, R> { project: (...values: Array<any>) => R; constructor(project?: (...values: Array<any>) => R) { this.project = project; } call(subscriber: Subscriber<R>, source: any): any { return source.subscribe(new ZipSubscriber(subscriber, this.project)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class ZipSubscriber<T, R> extends Subscriber<T> { private values: any; private project: (...values: Array<any>) => R; private iterators: LookAheadIterator<any>[] = []; private active = 0; constructor(destination: Subscriber<R>, project?: (...values: Array<any>) => R, values: any = Object.create(null)) { super(destination); this.project = (typeof project === 'function') ? project : null; this.values = values; } protected _next(value: any) { const iterators = this.iterators; if (isArray(value)) { iterators.push(new StaticArrayIterator(value)); } else if (typeof value[$$iterator] === 'function') { iterators.push(new StaticIterator(value[$$iterator]())); } else { iterators.push(new ZipBufferIterator(this.destination, this, value)); } } protected _complete() { const iterators = this.iterators; const len = iterators.length; this.active = len; for (let i = 0; i < len; i++) { let iterator: ZipBufferIterator<any, any> = <any>iterators[i]; if (iterator.stillUnsubscribed) { this.add(iterator.subscribe(iterator, i)); } else { this.active--; // not an observable } } } notifyInactive() { this.active--; if (this.active === 0) { this.destination.complete(); } } checkIterators() { const iterators = this.iterators; const len = iterators.length; const destination = this.destination; // abort if not all of them have values for (let i = 0; i < len; i++) { let iterator = iterators[i]; if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { return; } } let shouldComplete = false; const args: any[] = []; for (let i = 0; i < len; i++) { let iterator = iterators[i]; let result = iterator.next(); // check to see if it's completed now that you've gotten // the next value. if (iterator.hasCompleted()) { shouldComplete = true; } if (result.done) { destination.complete(); return; } args.push(result.value); } if (this.project) { this._tryProject(args); } else { destination.next(args); } if (shouldComplete) { destination.complete(); } } protected _tryProject(args: any[]) { let result: any; try { result = this.project.apply(this, args); } catch (err) { this.destination.error(err); return; } this.destination.next(result); } } interface LookAheadIterator<T> extends Iterator<T> { hasValue(): boolean; hasCompleted(): boolean; } class StaticIterator<T> implements LookAheadIterator<T> { private nextResult: IteratorResult<T>; constructor(private iterator: Iterator<T>) { this.nextResult = iterator.next(); } hasValue() { return true; } next(): IteratorResult<T> { const result = this.nextResult; this.nextResult = this.iterator.next(); return result; } hasCompleted() { const nextResult = this.nextResult; return nextResult && nextResult.done; } } class StaticArrayIterator<T> implements LookAheadIterator<T> { private index = 0; private length = 0; constructor(private array: T[]) { this.length = array.length; } [$$iterator]() { return this; } next(value?: any): IteratorResult<T> { const i = this.index++; const array = this.array; return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; } hasValue() { return this.array.length > this.index; } hasCompleted() { return this.array.length === this.index; } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ class ZipBufferIterator<T, R> extends OuterSubscriber<T, R> implements LookAheadIterator<T> { stillUnsubscribed = true; buffer: T[] = []; isComplete = false; constructor(destination: PartialObserver<T>, private parent: ZipSubscriber<T, R>, private observable: Observable<T>) { super(destination); } [$$iterator]() { return this; } // NOTE: there is actually a name collision here with Subscriber.next and Iterator.next // this is legit because `next()` will never be called by a subscription in this case. next(): IteratorResult<T> { const buffer = this.buffer; if (buffer.length === 0 && this.isComplete) { return { value: null, done: true }; } else { return { value: buffer.shift(), done: false }; } } hasValue() { return this.buffer.length > 0; } hasCompleted() { return this.buffer.length === 0 && this.isComplete; } notifyComplete() { if (this.buffer.length > 0) { this.isComplete = true; this.parent.notifyInactive(); } else { this.destination.complete(); } } notifyNext(outerValue: T, innerValue: any, outerIndex: number, innerIndex: number, innerSub: InnerSubscriber<T, R>): void { this.buffer.push(innerValue); this.parent.checkIterators(); } subscribe(value: any, index: number) { return subscribeToResult<any, any>(this, this.observable, this, index); } }
the_stack
import joplin from 'api'; import { SettingItemType } from 'api/types'; import { ChangeEvent } from 'api/JoplinSettings'; /** * Advanced style setting default values. * Used when setting is set to 'default'. */ enum SettingDefaults { Default = 'default', FontFamily = 'var(--joplin-font-family)', FontSize = 'var(--joplin-font-size)', Background = 'var(--joplin-background-color3)', HoverBackground = 'var(--joplin-background-color-hover3)', // var(--joplin-background-hover) Foreground = 'var(--joplin-color-faded)', ActiveBackground = 'var(--joplin-background-color)', ActiveForeground = 'var(--joplin-color)', DividerColor = 'var(--joplin-divider-color)' } export enum AddBehavior { Temporary, Pinned } export enum UnpinBehavior { Keep, LastActive, LeftTab, RightTab } export enum LayoutMode { Auto, Horizontal, Vertical } /** * Definitions of plugin settings. */ export class Settings { // private settings private _noteTabs: any[] = new Array(); // general settings private _enableDragAndDrop: boolean = true; private _showTodoCheckboxes: boolean = false; private _showBreadcrumbs: boolean = false; private _showNavigationButtons: boolean = false; private _showChecklistStatus: boolean = false; private _pinEditedNotes: boolean = false; private _unpinCompletedTodos: boolean = false; private _addBehavior: AddBehavior = AddBehavior.Temporary; private _unpinBehavior: UnpinBehavior = UnpinBehavior.Keep; private _layoutMode: number = LayoutMode.Auto; // advanced settings private _tabHeight: number = 35; private _minTabWidth: number = 50; private _maxTabWidth: number = 150; private _breadcrumbsMaxWidth: number = 100; private _fontFamily: string = SettingDefaults.Default; private _fontSize: string = SettingDefaults.Default; private _background: string = SettingDefaults.Default; private _hoverBackground: string = SettingDefaults.Default; private _actBackground: string = SettingDefaults.Default; private _breadcrumbsBackground: string = SettingDefaults.Default; private _foreground: string = SettingDefaults.Default; private _actForeground: string = SettingDefaults.Default; private _dividerColor: string = SettingDefaults.Default; // internals private _defaultRegExp: RegExp = new RegExp(SettingDefaults.Default, "i"); constructor() { } //#region GETTER get noteTabs(): any[] { return this._noteTabs; } get enableDragAndDrop(): boolean { return this._enableDragAndDrop; } get showTodoCheckboxes(): boolean { return this._showTodoCheckboxes; } get showBreadcrumbs(): boolean { return this._showBreadcrumbs; } get showNavigationButtons(): boolean { return this._showNavigationButtons; } get showChecklistStatus(): boolean { return this._showChecklistStatus; } get pinEditedNotes(): boolean { return this._pinEditedNotes; } get unpinCompletedTodos(): boolean { return this._unpinCompletedTodos; } hasAddBehavior(behavior: AddBehavior): boolean { return (this._addBehavior === behavior); } get unpinBehavior(): UnpinBehavior { return this._unpinBehavior; } hasLayoutMode(mode: LayoutMode): boolean { return (this._layoutMode === mode); } get tabHeight(): number { return this._tabHeight; } get minTabWidth(): number { return this._minTabWidth; } get maxTabWidth(): number { return this._maxTabWidth; } get breadcrumbsMaxWidth(): number { return this._breadcrumbsMaxWidth; } get fontFamily(): string { return this._fontFamily; } get fontSize(): string { return this._fontSize; } get background(): string { return this._background; } get hoverBackground(): string { return this._hoverBackground; } get actBackground(): string { return this._actBackground; } get breadcrumbsBackground(): string { return this._breadcrumbsBackground; } get foreground(): string { return this._foreground; } get actForeground(): string { return this._actForeground; } get dividerColor(): string { return this._dividerColor; } //#endregion //#region GLOBAL VALUES get showCompletedTodos(): Promise<boolean> { return joplin.settings.globalValue('showCompletedTodos'); } //#endregion /** * Register settings section with all options and intially read them at the end. */ async register() { // register settings in own section await joplin.settings.registerSection('note.tabs.settings', { label: 'Note Tabs', iconName: 'fas fa-window-maximize' }); await joplin.settings.registerSettings({ // private settings noteTabs: { value: [], type: SettingItemType.Array, section: 'note.tabs.settings', public: false, label: 'Note tabs' }, // general settings enableDragAndDrop: { value: this._enableDragAndDrop, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Enable drag & drop of tabs', description: 'If disabled, position of tabs can be change via commands or move buttons.' }, showTodoCheckboxes: { value: this._showTodoCheckboxes, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Show to-do checkboxes on tabs', description: 'If enabled, to-dos can be completed directly on the tabs.' }, showBreadcrumbs: { value: this._showBreadcrumbs, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Show breadcrumbs', description: 'Display full breadcrumbs for selected note. Displayed below the tabs in horizontal layout only.' }, showNavigationButtons: { value: this._showNavigationButtons, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Show navigation buttons', description: 'Display history backward and forward buttons. Displayed below the tabs in horizontal layout only.' }, showChecklistStatus: { value: this._showChecklistStatus, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Show checklist completion status', description: 'Display completion status of all checklists in the selected note. Displayed below the tabs in horizontal layout only.' }, pinEditedNotes: { value: this._pinEditedNotes, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Automatically pin notes when edited', description: 'Pin notes automatically as soon as the title, content or any other attribute changes.' }, unpinCompletedTodos: { value: this._unpinCompletedTodos, type: SettingItemType.Bool, section: 'note.tabs.settings', public: true, label: 'Automatically unpin completed to-dos', description: 'Unpin notes automatically as soon as the to-do status changes to completed. ' + 'Removes the tab completely unless it is the selected note.' }, addBehavior: { value: AddBehavior.Temporary, type: SettingItemType.Int, section: 'note.tabs.settings', isEnum: true, public: true, label: 'Add tab behavior', description: 'Specify how new tabs are added to the panel. Either as temporary or directly as pinned tab. ' + 'Only one temporary tab (italic font) exists at a time.', options: { '0': 'Temporary', '1': 'Pinned' } }, unpinBehavior: { value: UnpinBehavior.Keep, type: SettingItemType.Int, section: 'note.tabs.settings', isEnum: true, public: true, label: 'Unpin active tab behavior', description: 'Specify the behavior when unpinning the current active tab. ' + 'Either keep the active tab selected or select another one, depending on the setting.' + "In case 'Keep selected' is set, the temporary tab (shown with italic font in the tab list) may be replaced with the current active tab.", options: { '0': 'Keep selected', '1': 'Select last active tab', '2': 'Select left tab', '3': 'Select right tab' } }, layoutMode: { value: LayoutMode.Auto, type: SettingItemType.Int, section: 'note.tabs.settings', isEnum: true, public: true, label: 'Force tabs layout', description: 'Force tabs horizontal or vertical layout. If Auto, the layout switches automatically at a width of about 400px. Requires restart to be applied.', options: { '0': 'Auto', '1': 'Horizontal', '2': 'Vertical' } }, // advanced settings tabHeight: { value: this._tabHeight, type: SettingItemType.Int, section: 'note.tabs.settings', public: true, advanced: true, label: 'Note Tabs height (px)', description: 'Height of the tabs. Row height in vertical layout.' }, minTabWidth: { value: this._minTabWidth, type: SettingItemType.Int, section: 'note.tabs.settings', public: true, advanced: true, label: 'Minimum Tab width (px)', description: 'Minimum width of one tab in pixel.' }, maxTabWidth: { value: this._maxTabWidth, type: SettingItemType.Int, section: 'note.tabs.settings', public: true, advanced: true, label: 'Maximum Tab width (px)', description: 'Maximum width of one tab in pixel.' }, breadcrumbsMaxWidth: { value: this._breadcrumbsMaxWidth, type: SettingItemType.Int, section: 'note.tabs.settings', public: true, advanced: true, label: 'Maximum breadcrumb width (px)', description: 'Maximum width of one breadcrumb in pixel.' }, fontFamily: { value: this._fontFamily, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Font family', description: "Font family used in the panel. Font families other than 'default' must be installed on the system. If the font is incorrect or empty, it might default to a generic sans-serif font. (default: App default)" }, fontSize: { value: this._fontSize, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Font size', description: "Font size used in the panel. Values other than 'default' must be specified in valid CSS syntax, e.g. '13px'. (default: App default font size)" }, mainBackground: { value: this._background, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Background color', description: 'Main background color of the panel. (default: Note list background color)' }, hoverBackground: { value: this._hoverBackground, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Hover Background color', description: 'Background color used when hovering a favorite. (default: Note list hover color)' }, activeBackground: { value: this._actBackground, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Active background color', description: 'Background color of the current active tab. (default: Editor background color)' }, breadcrumbsBackground: { value: this._breadcrumbsBackground, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Infobar background color', description: 'Background color of the info bar (incl. breadcrumbs, etc.) below the tabs. (default: Editor background color)' }, mainForeground: { value: this._foreground, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Foreground color', description: 'Foreground color used for text and icons. (default: App faded color)' }, activeForeground: { value: this._actForeground, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Active foreground color', description: 'Foreground color of the current active tab. (default: Editor font color)' }, dividerColor: { value: this._dividerColor, type: SettingItemType.String, section: 'note.tabs.settings', public: true, advanced: true, label: 'Divider color', description: 'Color of the divider between the tabs. (default: App default border color)' } }); this._noteTabs = await joplin.settings.value('noteTabs'); // initially read settings await this.read(); } private async getOrDefault(event: ChangeEvent, localVar: any, setting: string, defaultValue?: string): Promise<any> { const read: boolean = (!event || event.keys.includes(setting)); if (read) { const value: string = await joplin.settings.value(setting); if (defaultValue && value.match(this._defaultRegExp)) { return defaultValue; } else { return value; } } return localVar; } /** * Update settings. Either all or only changed ones. */ async read(event?: ChangeEvent) { this._enableDragAndDrop = await this.getOrDefault(event, this._enableDragAndDrop, 'enableDragAndDrop'); this._showTodoCheckboxes = await this.getOrDefault(event, this._showTodoCheckboxes, 'showTodoCheckboxes'); this._showBreadcrumbs = await this.getOrDefault(event, this._showBreadcrumbs, 'showBreadcrumbs'); this._showNavigationButtons = await this.getOrDefault(event, this._showNavigationButtons, 'showNavigationButtons'); this._showChecklistStatus = await this.getOrDefault(event, this._showChecklistStatus, 'showChecklistStatus'); this._pinEditedNotes = await this.getOrDefault(event, this._pinEditedNotes, 'pinEditedNotes'); this._unpinCompletedTodos = await this.getOrDefault(event, this._unpinCompletedTodos, 'unpinCompletedTodos'); this._addBehavior = await this.getOrDefault(event, this._addBehavior, 'addBehavior'); this._unpinBehavior = await this.getOrDefault(event, this._unpinBehavior, 'unpinBehavior'); this._layoutMode = await this.getOrDefault(event, this._layoutMode, 'layoutMode'); this._tabHeight = await this.getOrDefault(event, this._tabHeight, 'tabHeight'); this._minTabWidth = await this.getOrDefault(event, this._minTabWidth, 'minTabWidth'); this._maxTabWidth = await this.getOrDefault(event, this._maxTabWidth, 'maxTabWidth'); this._breadcrumbsMaxWidth = await this.getOrDefault(event, this._breadcrumbsMaxWidth, 'breadcrumbsMaxWidth'); this._fontFamily = await this.getOrDefault(event, this._fontFamily, 'fontFamily', SettingDefaults.FontFamily); this._fontSize = await this.getOrDefault(event, this._fontSize, 'fontSize', SettingDefaults.FontSize); this._background = await this.getOrDefault(event, this._background, 'mainBackground', SettingDefaults.Background); this._hoverBackground = await this.getOrDefault(event, this._hoverBackground, 'hoverBackground', SettingDefaults.HoverBackground); this._actBackground = await this.getOrDefault(event, this._actBackground, 'activeBackground', SettingDefaults.ActiveBackground); this._breadcrumbsBackground = await this.getOrDefault(event, this._breadcrumbsBackground, 'breadcrumbsBackground', SettingDefaults.ActiveBackground); this._foreground = await this.getOrDefault(event, this._foreground, 'mainForeground', SettingDefaults.Foreground); this._actForeground = await this.getOrDefault(event, this._actForeground, 'activeForeground', SettingDefaults.ActiveForeground); this._dividerColor = await this.getOrDefault(event, this._dividerColor, 'dividerColor', SettingDefaults.DividerColor); } /** * Store the tabs array back to the settings. */ async storeTabs() { await joplin.settings.setValue('noteTabs', this._noteTabs); } /** * Clear the settings tabs array. */ async clearTabs() { this._noteTabs = []; await this.storeTabs(); } }
the_stack
import { Component, OnInit, ViewChild, AfterViewInit, QueryList, ViewChildren } from '@angular/core'; import { FilteringExpressionsTree, FilteringLogic, IgxNumberSummaryOperand, IgxSummaryResult, IGridState, IgxGridStateDirective, IgxExpansionPanelComponent, IgxGridBaseDirective, IGridStateOptions, GridFeatures, GridColumnDataType } from 'igniteui-angular'; import { take } from 'rxjs/operators'; import { Router } from '@angular/router'; import { TREEGRID_FLAT_DATA, EMPLOYEE_DATA, employeesData } from './data'; class MySummary extends IgxNumberSummaryOperand { constructor() { super(); } public operate(data?: any[]): IgxSummaryResult[] { const result = super.operate(data); result.push({ key: 'test', label: 'Test', summaryResult: data.filter(rec => rec > 10 && rec < 30).length }); return result; } } interface GridState { field: string; header: string; width: any; maxWidth?: any; minWidth?: any; dataType: GridColumnDataType; pinned?: boolean; groupable?: boolean; movable?: boolean; sortable?: boolean; filterable?: boolean; hasSummary?: boolean; resizable?: boolean; hidden?: boolean; summaries?: any; } @Component({ selector: 'app-grid', styleUrls: ['./grid-state.component.scss'], templateUrl: './grid-state.component.html' }) export class GridSaveStateComponent implements OnInit, AfterViewInit { @ViewChild(IgxExpansionPanelComponent, { static: true }) private igxExpansionPanel: IgxExpansionPanelComponent; @ViewChildren(IgxGridStateDirective) private state: QueryList<IgxGridStateDirective>; public localData = employeesData; public hierData = this.generateDataUneven(10, 3); public treeGridFlatData = TREEGRID_FLAT_DATA; public employees = EMPLOYEE_DATA; public gridId = 'grid1'; public hGridId = 'hGrid1'; public treeGridId = 'treeGrid1'; public mcGridId = 'mcGrid1'; public treeGridHierId = 'treeGridH1'; public gridState: IGridState; public serialize = true; public templatedIcon = false; public features: { key: GridFeatures; shortName: string }[] = [ { key: 'advancedFiltering', shortName: 'Adv Filt' }, { key: 'cellSelection', shortName: 'Cell Sel' }, { key: 'columns', shortName: 'Columns' } , { key: 'columnSelection', shortName: 'Cols Sel' }, { key: 'expansion', shortName: 'Expansion' }, { key: 'filtering', shortName: 'Filt' }, { key: 'paging', shortName: 'Paging' }, { key: 'rowPinning', shortName: 'Row Pining' }, { key: 'rowSelection', shortName: 'Row Sel' }, { key: 'sorting', shortName: 'Sorting' }, { key: 'groupBy', shortName: 'GroupBy'} ]; public options: IGridStateOptions = { cellSelection: true, rowSelection: true, columnSelection: true, filtering: true, advancedFiltering: true, paging: true, sorting: true, groupBy: true, columns: true, expansion: true, rowPinning: true }; public initialColumns: GridState [] = [ /* eslint-disable max-len */ { field: 'FirstName', header: 'First Name', width: '150px', dataType: 'string', pinned: true, movable: true, sortable: true, filterable: true, summaries: MySummary }, { field: 'LastName', header: 'Last Name', width: '150px', dataType: 'string', pinned: true, movable: true, sortable: true, filterable: true}, { field: 'Country', header: 'Country', width: '140px', dataType: 'string', groupable: true, movable: true, sortable: true, filterable: true, resizable: true }, { field: 'Age', header: 'Age', width: '110px', dataType: 'number', movable: true, sortable: true, filterable: true, hasSummary: true, summaries: MySummary, resizable: true}, { field: 'RegistererDate', header: 'Registerer Date', width: '180px', dataType: 'date', movable: true, sortable: true, filterable: true, resizable: true }, { field: 'IsActive', header: 'Is Active', width: '140px', dataType: 'boolean', groupable: true, movable: true, sortable: true, filterable: true } ]; public treeGridColumns: GridState [] = [ { field: 'employeeID', header: 'ID', width: 200, resizable: true, movable: true, dataType: 'number', hasSummary: false }, { field: 'Salary', header: 'Salary', width: 200, resizable: true, movable: true, dataType: 'number', hasSummary: true }, { field: 'firstName', header: 'First Name', width: 300, resizable: true, movable: true, dataType: 'string', hasSummary: false }, { field: 'lastName', header: 'Last Name', width: 150, resizable: true, movable: true, dataType: 'string', hasSummary: false }, { field: 'Title', header: 'Title', width: 200, resizable: true, movable: true, dataType: 'string', hasSummary: true } ]; public hierGridColumns: GridState [] = [ { field: 'ID', header: 'ID', width: 200, resizable: true, sortable: true, filterable: true, pinned: true, dataType: 'number', hasSummary: true }, { field: 'ChildLevels', header: 'Child Levels', width: 200, resizable: true, sortable: true, filterable: true, groupable: true, dataType: 'number', hasSummary: true }, { field: 'ProductName', header: 'Product Name', width: 300, resizable: true, sortable: true, filterable: true, movable: true, dataType: 'string', hasSummary: false } ]; /* eslint-enable max-len */ constructor(private router: Router) { } public ngOnInit() { this.router.events.pipe(take(1)).subscribe(() => { this.saveGridState(null); }); } public ngAfterViewInit() { // const gridFilteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And); // const productFilteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And, 'ProductName'); // const productExpression = { // condition: IgxStringFilteringOperand.instance().condition('contains'), // fieldName: 'FirstName', // ignoreCase: true, // searchVal: 'c' // }; // productFilteringExpressionsTree.filteringOperands.push(productExpression); // gridFilteringExpressionsTree.filteringOperands.push(productFilteringExpressionsTree); // this.grid.filteringExpressionsTree = gridFilteringExpressionsTree; // this.restoreGridState(); } public getContext(grid: IgxGridBaseDirective) { if (this.state) { const stateDirective = this.state.find(st => st.grid.id === grid.id); return { $implicit: grid, stateDirective}; } return { $implicit: grid }; } // save state for all grids on the page public saveGridState(stateDirective: IgxGridStateDirective) { if (stateDirective) { let state = stateDirective.getState(this.serialize); if (typeof state !== 'string') { state = JSON.stringify(state); } try { window.localStorage.setItem(`${stateDirective.grid.id}-state`, state); } catch (e) { console.log('Storage is full, or the value that you try to se is too long to be written in single item, Please empty data'); } } else { this.state.forEach(stateDir => { let state = stateDir.getState(this.serialize); if (typeof state !== 'string') { state = JSON.stringify(state); } try { window.localStorage.setItem(`${stateDir.grid.id}-state`, state); } catch (e) { console.log('Storage is full, or the value that you try to se is too long to be written in single item, Please empty data'); } }); } } // restores grid state for the passed stateDirective only public restoreGridState(stateDirective: IgxGridStateDirective) { const key = `${stateDirective.grid.id}-state`; const state = window.localStorage.getItem(key); if (state) { stateDirective.setState(state); } } public restoreFeature(stateDirective: IgxGridStateDirective, feature: string) { const key = `${stateDirective.grid.id}-state`; const state = this.getFeatureState(key, feature); if (state) { const featureState = { } as IGridState; featureState[feature] = state; stateDirective.setState(featureState); } } public getFeatureState(stateKey: string, feature: string) { let state = window.localStorage.getItem(stateKey); state = state ? JSON.parse(state)[feature] : null; return state; } public resetGridState(grid) { grid.filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And); grid.advancedFilteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And); grid.sortingExpressions = []; grid.groupingExpressions = []; grid.deselectAllRows(); grid.clearCellSelection(); } public onChange(event: any, action: string, state: IgxGridStateDirective) { state.options[action] = event.checked; } public clearStorage(grid) { const key = `${grid.id}-state`; window.localStorage.removeItem(key); } public reloadPage() { window.location.reload(); } public templateIcon() { this.templatedIcon = !this.templatedIcon; } public collapsed() { return this.igxExpansionPanel && this.igxExpansionPanel.collapsed; } public generateDataUneven(count: number, level: number, parentID: string = null) { const prods = []; const currLevel = level; let children; for (let i = 0; i < count; i++) { const rowID = parentID ? parentID + i : i.toString(); if (level > 0) { // Have child grids for row with even id less rows by not multiplying by 2 children = this.generateDataUneven(((i % 2) + 1) * Math.round(count / 3), currLevel - 1, rowID); } prods.push({ ID: rowID, ChildLevels: currLevel, ProductName: 'Product: A' + i, Col1: i, Col2: i, Col3: i, childData: children, childData2: i % 2 ? [] : children, hasChild: true }); } return prods; } }
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const postOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { source: [ 'contentApi', ], resource: [ 'post', ], }, }, options: [ { name: 'Get', value: 'get', description: 'Get a post', }, { name: 'Get All', value: 'getAll', description: 'Get all posts', }, ], default: 'get', description: 'The operation to perform.', }, { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a post', }, { name: 'Delete', value: 'delete', description: 'Delete a post', }, { name: 'Get', value: 'get', description: 'Get a post', }, { name: 'Get All', value: 'getAll', description: 'Get all posts', }, { name: 'Update', value: 'update', description: 'Update a post', }, ], default: 'get', description: 'The operation to perform.', }, ]; export const postFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* post:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Title', name: 'title', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'create', ], }, }, description: `Post's title.`, }, { displayName: 'Content Format', name: 'contentFormat', type: 'options', displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'create', ], }, }, options: [ { name: 'HTML', value: 'html', }, { name: 'Mobile Doc', value: 'mobileDoc', }, ], default: 'html', description: `The format of the post.`, }, { displayName: 'Content', name: 'content', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'create', ], contentFormat: [ 'html', ], }, }, default: '', description: 'The content of the post to create.', }, { displayName: 'Content (JSON)', name: 'content', type: 'json', displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'create', ], contentFormat: [ 'mobileDoc', ], }, }, default: '', description: 'Mobiledoc is the raw JSON format that Ghost uses to store post contents. <a href="https://ghost.org/docs/concepts/posts/#document-storage">Info</a>', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Authors IDs', name: 'authors', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getAuthors', }, default: [], }, { displayName: 'Cannonical URL', name: 'canonical_url', type: 'string', default: '', }, { displayName: 'Code Injection Foot', name: 'codeinjection_foot', type: 'string', default: '', description: 'The Code Injection allows you inject a small snippet into your Ghost site', }, { displayName: 'Code Injection Head', name: 'codeinjection_head', type: 'string', default: '', description: 'The Code Injection allows you inject a small snippet into your Ghost site', }, { displayName: 'Featured', name: 'featured', type: 'boolean', default: false, }, { displayName: 'Meta Description', name: 'meta_description', type: 'string', default: '', }, { displayName: 'Meta Title', name: 'meta_title', type: 'string', default: '', }, { displayName: 'Open Graph Description', name: 'og_description', type: 'string', default: '', }, { displayName: 'Open Graph Title', name: 'og_title', type: 'string', default: '', }, { displayName: 'Open Graph Image', name: 'og_image', type: 'string', default: '', description: 'URL of the image', }, { displayName: 'Published At', name: 'published_at', type: 'dateTime', default: '', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', }, { displayName: 'Status', name: 'status', type: 'options', options: [ { name: 'Draft', value: 'draft', }, { name: 'Published', value: 'published', }, { name: 'Scheduled', value: 'scheduled', }, ], default: 'draft', }, { displayName: 'Tags IDs', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'Twitter Description', name: 'twitter_description', type: 'string', default: '', }, { displayName: 'Twitter Image', name: 'twitter_image', type: 'string', default: '', description: 'URL of the image', }, { displayName: 'Twitter Title', name: 'twitter_title', type: 'string', default: '', }, ], }, /* -------------------------------------------------------------------------- */ /* post:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Post ID', name: 'postId', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'delete', ], }, }, description: 'The ID of the post to delete.', }, /* -------------------------------------------------------------------------- */ /* post:get */ /* -------------------------------------------------------------------------- */ { displayName: 'By', name: 'by', type: 'options', default: '', required: true, options: [ { name: 'ID', value: 'id', }, { name: 'Slug', value: 'slug', }, ], displayOptions: { show: { source: [ 'contentApi', 'adminApi', ], resource: [ 'post', ], operation: [ 'get', ], }, }, description: 'Get the post either by slug or ID.', }, { displayName: 'Identifier', name: 'identifier', type: 'string', default: '', required: true, displayOptions: { show: { source: [ 'contentApi', 'adminApi', ], resource: [ 'post', ], operation: [ 'get', ], }, }, description: 'The ID or slug of the post to get.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'get', ], }, }, options: [ { displayName: 'Fields', name: 'fields', type: 'string', default: '', description: 'Limit the fields returned in the response object. E.g. for posts fields=title,url.', }, { displayName: 'Formats', name: 'formats', type: 'multiOptions', options: [ { name: 'HTML', value: 'html', }, { name: 'Mobile Doc', value: 'mobiledoc', }, ], default: [ 'mobiledoc', ], }, ], }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { source: [ 'contentApi', ], resource: [ 'post', ], operation: [ 'get', ], }, }, options: [ { displayName: 'Fields', name: 'fields', type: 'string', default: '', description: 'Limit the fields returned in the response object. E.g. for posts fields=title,url.', }, { displayName: 'Formats', name: 'formats', type: 'multiOptions', options: [ { name: 'HTML', value: 'html', }, { name: 'Plaintext', value: 'plaintext', }, ], default: [ 'html', ], }, ], }, /* -------------------------------------------------------------------------- */ /* post:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { source: [ 'contentApi', 'adminApi', ], resource: [ 'post', ], operation: [ 'getAll', ], }, }, default: false, description: 'Returns a list of your user contacts.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { source: [ 'adminApi', 'contentApi', ], resource: [ 'post', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 100, }, default: 50, description: 'How many results to return.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { source: [ 'contentApi', ], resource: [ 'post', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Include', name: 'include', type: 'multiOptions', options: [ { name: 'Authors', value: 'authors', }, { name: 'Tags', value: 'tags', }, ], default: [], description: 'Tells the API to return additional data related to the resource you have requested', }, { displayName: 'Fields', name: 'fields', type: 'string', default: '', description: 'Limit the fields returned in the response object. E.g. for posts fields=title,url.', }, { displayName: 'Formats', name: 'formats', type: 'multiOptions', options: [ { name: 'HTML', value: 'html', }, { name: 'Plaintext', value: 'plaintext', }, ], default: [ 'html', ], description: `By default, only html is returned, however each post and page in Ghost has 2 available formats: html and plaintext.`, }, ], }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Include', name: 'include', type: 'multiOptions', options: [ { name: 'Authors', value: 'authors', }, { name: 'Tags', value: 'tags', }, ], default: [], description: 'Tells the API to return additional data related to the resource you have requested', }, { displayName: 'Fields', name: 'fields', type: 'string', default: '', description: 'Limit the fields returned in the response object. E.g. for posts fields=title,url.', }, { displayName: 'Formats', name: 'formats', type: 'multiOptions', options: [ { name: 'HTML', value: 'html', }, { name: 'Mobile Doc', value: 'mobiledoc', }, ], default: [ 'mobiledoc', ], }, ], }, /* -------------------------------------------------------------------------- */ /* post:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Post ID', name: 'postId', type: 'string', displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'update', ], }, }, default: '', description: 'The ID of the post to update.', }, { displayName: 'Content Format', name: 'contentFormat', type: 'options', displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'update', ], }, }, options: [ { name: 'HTML', value: 'html', }, { name: 'Mobile Doc', value: 'mobileDoc', }, ], default: 'html', description: `The format of the post.`, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { source: [ 'adminApi', ], resource: [ 'post', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Authors IDs', name: 'authors', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getAuthors', }, default: [], }, { displayName: 'Cannonical URL', name: 'canonical_url', type: 'string', default: '', }, { displayName: 'Code Injection Foot', name: 'codeinjection_foot', type: 'string', default: '', }, { displayName: 'Code Injection Head', name: 'codeinjection_head', type: 'string', default: '', }, { displayName: 'Content', name: 'content', type: 'string', displayOptions: { show: { '/contentFormat': [ 'html', ], }, }, typeOptions: { alwaysOpenEditWindow: true, }, default: '', }, { displayName: 'Content (JSON)', name: 'contentJson', type: 'json', displayOptions: { show: { '/contentFormat': [ 'mobileDoc', ], }, }, default: '', description: 'Mobiledoc is the raw JSON format that Ghost uses to store post contents. <a href="https://ghost.org/docs/concepts/posts/#document-storage">Info.</a>', }, { displayName: 'Featured', name: 'featured', type: 'boolean', default: false, }, { displayName: 'Meta Description', name: 'meta_description', type: 'string', default: '', }, { displayName: 'Meta Title', name: 'meta_title', type: 'string', default: '', }, { displayName: 'Open Graph Description', name: 'og_description', type: 'string', default: '', }, { displayName: 'Open Graph Title', name: 'og_title', type: 'string', default: '', }, { displayName: 'Open Graph Image', name: 'og_image', type: 'string', default: '', description: 'URL of the image', }, { displayName: 'Published At', name: 'published_at', type: 'dateTime', default: '', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', }, { displayName: 'Status', name: 'status', type: 'options', options: [ { name: 'Draft', value: 'draft', }, { name: 'Published', value: 'published', }, { name: 'Scheduled', value: 'scheduled', }, ], default: 'draft', }, { displayName: 'Tags IDs', name: 'tags', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getTags', }, default: [], }, { displayName: 'Title', name: 'title', type: 'string', default: '', description: `Post's title`, }, { displayName: 'Twitter Description', name: 'twitter_description', type: 'string', default: '', }, { displayName: 'Twitter Image', name: 'twitter_image', type: 'string', default: '', description: 'URL of the image', }, { displayName: 'Twitter Title', name: 'twitter_title', type: 'string', default: '', }, ], }, ];
the_stack
import { BBoxProperty } from '../boundingBoxes/GameBoundingBoxTypes'; import { GameCheckpoint } from '../chapter/GameChapterTypes'; import { GamePosition, ItemId } from '../commons/CommonTypes'; import GameMap from '../location/GameMap'; import { GameItemType, LocationId } from '../location/GameMapTypes'; import { GameMode } from '../mode/GameModeTypes'; import GameObjective from '../objective/GameObjective'; import { ObjectProperty } from '../objects/GameObjectTypes'; import { convertMapToArray } from '../save/GameSaveHelper'; import GameGlobalAPI from '../scenes/gameManager/GameGlobalAPI'; import SourceAcademyGame from '../SourceAcademyGame'; import { mandatory } from '../utils/GameUtils'; import { StateObserver } from './GameStateTypes'; /** * Manages all states related to story, chapter, or checkpoint; * e.g. checkpoint objectives, objects' property, bboxes' property. * * Other than this manager, all other manager should not need to * manage their own state. * * Employs observer pattern, and notifies its subjects on state update. */ class GameStateManager { // Subscribers private subscribers: Map<GameItemType, StateObserver>; // Game State private gameMap: GameMap; private checkpointObjective: GameObjective; private chapterNewlyCompleted: boolean; // Triggered Interactions private updatedLocations: Set<LocationId>; private triggeredInteractions: Map<ItemId, boolean>; private triggeredStateChangeActions: ItemId[]; constructor(gameCheckpoint: GameCheckpoint) { this.subscribers = new Map<GameItemType, StateObserver>(); this.gameMap = gameCheckpoint.map; this.checkpointObjective = gameCheckpoint.objectives; this.chapterNewlyCompleted = false; this.updatedLocations = new Set(this.gameMap.getLocationIds()); this.triggeredInteractions = new Map<ItemId, boolean>(); this.triggeredStateChangeActions = []; this.loadStatesFromSaveManager(); } /** * Loads some game states from the save manager */ private loadStatesFromSaveManager() { this.triggeredStateChangeActions = this.getSaveManager().getTriggeredStateChangeActions(); this.getSaveManager() .getTriggeredInteractions() .forEach(interactionId => this.triggerInteraction(interactionId)); this.getSaveManager() .getCompletedObjectives() .forEach(objective => this.checkpointObjective.setObjective(objective, true)); this.chapterNewlyCompleted = this.getSaveManager().getChapterNewlyCompleted(); } /////////////////////////////// // Subscribers // /////////////////////////////// /** * This function is called to set state observers * * @param gameItemType Type of game item the observer wants to watch * @param stateObserver reference to state observer */ public watchGameItemType(gameItemType: GameItemType, stateObserver: StateObserver) { this.subscribers.set(gameItemType, stateObserver); } /** * Obtains the subscriber that watches the game item * * @param gameItemType the type of item being watched */ private getSubscriberForItemType(gameItemType: GameItemType) { return this.subscribers.get(gameItemType); } /////////////////////////////// // Interaction // /////////////////////////////// /** * Record that an interaction has been triggered. * * @param id id of interaction */ public triggerInteraction(id: string): void { this.triggeredInteractions.set(id, true); } /** * Record a state-change action that has been triggered. * State-change actions refer to actions that modify the map's * original state * * @param actionId actionId of interaction */ public triggerStateChangeAction(actionId: ItemId): void { this.triggeredStateChangeActions.push(actionId); } /** * Checks whether an interaction ID has been triggered or not. * * @param id id of interaction * @returns {boolean} */ public hasTriggeredInteraction(id: string): boolean | undefined { return this.triggeredInteractions.get(id); } /////////////////////////////// // Notifs // /////////////////////////////// /** * Adds a location notification for a locationId * * @param locationId locationId of location you want to add notif to */ public addLocationNotif(locationId: LocationId) { this.updatedLocations.add(locationId); } /** * Removes a location notification for a locationId * * @param locationId locationId of location you want to remove notif of */ public removeLocationNotif(locationId: LocationId) { this.updatedLocations.delete(locationId); } /** * Gets whether or not the location has a notif * * @param locationId locationId of location you want to find out if got notif */ public hasLocationNotif(locationId: LocationId) { return this.updatedLocations.has(locationId); } /** * Function to check if current location is the given locationId * * @param locationId locationId that you want to check whether is current one */ public isCurrentLocation(locationId: LocationId) { return locationId === GameGlobalAPI.getInstance().getCurrLocId(); } /////////////////////////////// // Location Mode // /////////////////////////////// /** * Get modes available to a location based on the location ID. * * @param locationId location ID * @returns {GameMode[]} game modes */ public getLocationModes(locationId: LocationId): GameMode[] { return Array.from(this.gameMap.getLocationAtId(locationId).modes) || []; } /** * Add a mode to a location. If this is not the current location, * then add a notification. * * @param locationId location ID * @param mode game mode to add */ public addLocationMode(locationId: LocationId, mode: GameMode) { this.gameMap.getLocationAtId(locationId).modes.add(mode); !this.isCurrentLocation(locationId) && this.addLocationNotif(locationId); } /** * Remove a mode from a location. If this is not the current location, * then add a notification. * * @param locationId location ID * @param mode game mode to remove */ public removeLocationMode(locationId: LocationId, mode: GameMode) { this.gameMap.getLocationAtId(locationId).modes.delete(mode); !this.isCurrentLocation(locationId) && this.addLocationNotif(locationId); } /////////////////////////////// // State Check // /////////////////////////////// /** * Get all IDs of a type of game item in a location. * * @param gameItemType type of game item * @param locationId id of location * @returns {ItemId[]} items IDS of all game items of that type in the location */ public getGameItemsInLocation(gameItemType: GameItemType, locationId: LocationId): ItemId[] { return Array.from(this.gameMap.getLocationAtId(locationId)[gameItemType]) || []; } /** * Add an item ID of a game item type in gamemap's location. * * Either render the change instantly, or place a notification inside another location * * @param gameItemType type of game item * @param locationId id of location to add items to * @param itemId item ID to be added */ public addItem(gameItemType: GameItemType, locationId: LocationId, itemId: ItemId) { this.gameMap.getLocationAtId(locationId)[gameItemType]?.add(itemId); this.isCurrentLocation(locationId) ? this.getSubscriberForItemType(gameItemType)?.handleAdd(itemId) : this.addLocationNotif(locationId); } /** * Remove an item ID from game items in gamemap's location. * If ID is not found within the game item list, nothing will be executed. * * Either render the change instantly, or place a notification inside another location * * @param gameItemType type of game item to remove * @param locationId id of location to remove items from * @param itemId item ID to be removed */ public removeItem(gameItemType: GameItemType, locationId: LocationId, itemId: string) { this.gameMap.getLocationAtId(locationId)[gameItemType]?.delete(itemId); this.isCurrentLocation(locationId) ? this.getSubscriberForItemType(gameItemType)?.handleDelete(itemId) : this.addLocationNotif(locationId); } /** * Replace an object property of the given ID with the new object * property. Commonly used to update a specific object property. * * @param id id of object to change * @param newObjProp new object property to replace the old one */ public setObjProperty(id: ItemId, newObjProp: ObjectProperty) { this.gameMap.setItemInMap(GameItemType.objects, id, newObjProp); // Update every location that has the object this.gameMap.getLocations().forEach((location, locId) => { if (!location.objects.has(id)) return; this.isCurrentLocation(locId) ? this.getSubscriberForItemType(GameItemType.objects)?.handleMutate(id) : this.addLocationNotif(locId); }); } /** * Replace a bbox property of the given ID with the new bbox * property. Commonly used to update a specific bbox property. * * @param id id of object to change * @param newBBoxProp new object property to replace the old one */ public setBBoxProperty(id: ItemId, newBBoxProp: BBoxProperty) { this.gameMap.setItemInMap(GameItemType.boundingBoxes, id, newBBoxProp); // Update every location that has the bbox this.gameMap.getLocations().forEach((location, locId) => { if (!location.boundingBoxes.has(id)) return; this.isCurrentLocation(locId) ? this.getSubscriberForItemType(GameItemType.boundingBoxes)?.handleMutate(id) : this.addLocationNotif(locId); }); } /** * Moves a character to another location and another position * * @param id id of character to change * @param newLocation new location to put this character inside of * @param newPosition new position of the character */ public moveCharacter(id: ItemId, newLocation: LocationId, newPosition: GamePosition) { // Move position this.getCharacterAtId(id).defaultPosition = newPosition; // Find location with character and remove him this.gameMap.getLocations().forEach((location, locId) => { if (!location.characters.has(id)) return; this.removeItem(GameItemType.characters, locId, id); }); // Add updated character to new location this.addItem(GameItemType.characters, newLocation, id); } /** * Changes the default expression of a character * * @param id id of character to change * @param newExpression new expression of the character */ public updateCharacter(id: ItemId, newExpression: string) { this.getCharacterAtId(id).defaultExpression = newExpression; // Update every location that has the character this.gameMap.getLocations().forEach((location, locId) => { if (!location.characters.has(id)) return; this.isCurrentLocation(locId) ? this.getSubscriberForItemType(GameItemType.characters)?.handleMutate(id) : this.addLocationNotif(locId); }); } /////////////////////////////// // Chapter Objectives // /////////////////////////////// /** * Checks whether all the checkpoint objectives has been completed. * @returns {boolean} */ public isAllComplete(): boolean { return this.checkpointObjective.isAllComplete(); } /** * Checks whether a specific objective has been completed. * If the objective does not exist, this method still return true. * * @param key objective name * @returns {boolean} */ public isObjectiveComplete(key: string): boolean { const isComplete = this.checkpointObjective.getObjectiveState(key); if (isComplete === undefined || isComplete) { return true; } return false; } /** * Check whether the objectives are complete or not. * All specified objectives must be complete for this method * to return true. * * @param keys objective names * @returns {boolean} */ public areObjectivesComplete(keys: string[]): boolean { let result = true; keys.forEach(key => (result = result && this.isObjectiveComplete(key))); return result; } /** * Record that an objective has been completed. * * @param key objective name */ public completeObjective(key: string): void { this.checkpointObjective.setObjective(key, true); } /////////////////////////////// // Saving // /////////////////////////////// /** * Gets array of all objectives that have been completed. * * @returns {ItemId[]} */ public getCompletedObjectives(): ItemId[] { return convertMapToArray(this.checkpointObjective.getObjectives()); } /** * Return an array interactions that have been triggered * * @returns {string[]} */ public getTriggeredInteractions(): string[] { return convertMapToArray(this.triggeredInteractions); } /** * Return an array interactions of state-change actions that have been triggered * State-change actions refer to actions that modify the game map's original state * * @returns {string[]} */ public getTriggeredStateChangeActions(): string[] { return this.triggeredStateChangeActions; } public getGameMap = () => this.gameMap; public getCharacterAtId = (id: ItemId) => mandatory(this.gameMap.getCharacterMap().get(id)); private getSaveManager = () => SourceAcademyGame.getInstance().getSaveManager(); public getChapterNewlyCompleted = () => this.chapterNewlyCompleted; } export default GameStateManager;
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [codecommit](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodecommit.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Codecommit extends PolicyStatement { public servicePrefix = 'codecommit'; /** * Statement provider for service [codecommit](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodecommit.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 associate an approval rule template with a repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_AssociateApprovalRuleTemplateWithRepository.html */ public toAssociateApprovalRuleTemplateWithRepository() { return this.to('AssociateApprovalRuleTemplateWithRepository'); } /** * Grants permission to associate an approval rule template with multiple repositories in a single operation * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_BatchAssociateApprovalRuleTemplateWithRepositories.html */ public toBatchAssociateApprovalRuleTemplateWithRepositories() { return this.to('BatchAssociateApprovalRuleTemplateWithRepositories'); } /** * Grants permission to get information about multiple merge conflicts when attempting to merge two commits using either the three-way merge or the squash merge option * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_BatchDescribeMergeConflicts.html */ public toBatchDescribeMergeConflicts() { return this.to('BatchDescribeMergeConflicts'); } /** * Grants permission to remove the association between an approval rule template and multiple repositories in a single operation * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_BatchDisassociateApprovalRuleTemplateFromRepositories.html */ public toBatchDisassociateApprovalRuleTemplateFromRepositories() { return this.to('BatchDisassociateApprovalRuleTemplateFromRepositories'); } /** * Grants permission to get return information about one or more commits in an AWS CodeCommit repository. * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_BatchGetCommits.html */ public toBatchGetCommits() { return this.to('BatchGetCommits'); } /** * Grants permission to return information about one or more pull requests in an AWS CodeCommit repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-pr */ public toBatchGetPullRequests() { return this.to('BatchGetPullRequests'); } /** * Grants permission to get information about multiple repositories * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_BatchGetRepositories.html */ public toBatchGetRepositories() { return this.to('BatchGetRepositories'); } /** * Grants permission to cancel the uploading of an archive to a pipeline in AWS CodePipeline * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-acp */ public toCancelUploadArchive() { return this.to('CancelUploadArchive'); } /** * Grants permission to create an approval rule template that will automatically create approval rules in pull requests that match the conditions defined in the template; does not grant permission to create approval rules for individual pull requests * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateApprovalRuleTemplate.html */ public toCreateApprovalRuleTemplate() { return this.to('CreateApprovalRuleTemplate'); } /** * Grants permission to create a branch in an AWS CodeCommit repository with this API; does not control Git create branch actions * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateBranch.html */ public toCreateBranch() { return this.to('CreateBranch'); } /** * Grants permission to add, copy, move or update single or multiple files in a branch in an AWS CodeCommit repository, and generate a commit for the changes in the specified branch. * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateCommit.html */ public toCreateCommit() { return this.to('CreateCommit'); } /** * Grants permission to create a pull request in the specified repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreatePullRequest.html */ public toCreatePullRequest() { return this.to('CreatePullRequest'); } /** * Grants permission to create an approval rule specific to an individual pull request; does not grant permission to create approval rule templates * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreatePullRequestApprovalRule.html */ public toCreatePullRequestApprovalRule() { return this.to('CreatePullRequestApprovalRule'); } /** * Grants permission to create an AWS CodeCommit repository * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateRepository.html */ public toCreateRepository() { return this.to('CreateRepository'); } /** * Grants permission to create an unreferenced commit that contains the result of merging two commits using either the three-way or the squash merge option; does not control Git merge actions * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_CreateUnreferencedMergeCommit.html */ public toCreateUnreferencedMergeCommit() { return this.to('CreateUnreferencedMergeCommit'); } /** * Grants permission to delete an approval rule template * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeleteApprovalRuleTemplate.html */ public toDeleteApprovalRuleTemplate() { return this.to('DeleteApprovalRuleTemplate'); } /** * Grants permission to delete a branch in an AWS CodeCommit repository with this API; does not control Git delete branch actions * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeleteBranch.html */ public toDeleteBranch() { return this.to('DeleteBranch'); } /** * Grants permission to delete the content of a comment made on a change, file, or commit in a repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeleteCommentContent.html */ public toDeleteCommentContent() { return this.to('DeleteCommentContent'); } /** * Grants permission to delete a specified file from a specified branch * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeleteFile.html */ public toDeleteFile() { return this.to('DeleteFile'); } /** * Grants permission to delete approval rule created for a pull request if the rule was not created by an approval rule template * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeletePullRequestApprovalRule.html */ public toDeletePullRequestApprovalRule() { return this.to('DeletePullRequestApprovalRule'); } /** * Grants permission to delete an AWS CodeCommit repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DeleteRepository.html */ public toDeleteRepository() { return this.to('DeleteRepository'); } /** * Grants permission to get information about specific merge conflicts when attempting to merge two commits using either the three-way or the squash merge option * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DescribeMergeConflicts.html */ public toDescribeMergeConflicts() { return this.to('DescribeMergeConflicts'); } /** * Grants permission to return information about one or more pull request events * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DescribePullRequestEvents.html */ public toDescribePullRequestEvents() { return this.to('DescribePullRequestEvents'); } /** * Grants permission to remove the association between an approval rule template and a repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_DisassociateApprovalRuleTemplateFromRepository.html */ public toDisassociateApprovalRuleTemplateFromRepository() { return this.to('DisassociateApprovalRuleTemplateFromRepository'); } /** * Grants permission to evaluate whether a pull request is mergable based on its current approval state and approval rule requirements * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_EvaluatePullRequestApprovalRules.html */ public toEvaluatePullRequestApprovalRules() { return this.to('EvaluatePullRequestApprovalRules'); } /** * Grants permission to return information about an approval rule template * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetApprovalRuleTemplate.html */ public toGetApprovalRuleTemplate() { return this.to('GetApprovalRuleTemplate'); } /** * Grants permission to view the encoded content of an individual file in an AWS CodeCommit repository from the AWS CodeCommit console * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetBlob.html */ public toGetBlob() { return this.to('GetBlob'); } /** * Grants permission to get details about a branch in an AWS CodeCommit repository with this API; does not control Git branch actions * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetBranch.html */ public toGetBranch() { return this.to('GetBranch'); } /** * Grants permission to get the content of a comment made on a change, file, or commit in a repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetComment.html */ public toGetComment() { return this.to('GetComment'); } /** * Grants permission to get the reactions on a comment * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetCommentReactions.html */ public toGetCommentReactions() { return this.to('GetCommentReactions'); } /** * Grants permission to get information about comments made on the comparison between two commits * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetCommentsForComparedCommit.html */ public toGetCommentsForComparedCommit() { return this.to('GetCommentsForComparedCommit'); } /** * Grants permission to get comments made on a pull request * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetCommentsForPullRequest.html */ public toGetCommentsForPullRequest() { return this.to('GetCommentsForPullRequest'); } /** * Grants permission to return information about a commit, including commit message and committer information, with this API; does not control Git log actions * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetCommit.html */ public toGetCommit() { return this.to('GetCommit'); } /** * Grants permission to get information about the history of commits in a repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-code */ public toGetCommitHistory() { return this.to('GetCommitHistory'); } /** * Grants permission to get information about the difference between commits in the context of a potential merge * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-pr */ public toGetCommitsFromMergeBase() { return this.to('GetCommitsFromMergeBase'); } /** * Grants permission to view information about the differences between valid commit specifiers such as a branch, tag, HEAD, commit ID, or other fully qualified reference * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetDifferences.html */ public toGetDifferences() { return this.to('GetDifferences'); } /** * Grants permission to return the base-64 encoded contents of a specified file and its metadata * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetFile.html */ public toGetFile() { return this.to('GetFile'); } /** * Grants permission to return the contents of a specified folder in a repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetFolder.html */ public toGetFolder() { return this.to('GetFolder'); } /** * Grants permission to get information about a merge commit created by one of the merge options for pull requests that creates merge commits. Not all merge options create merge commits. This permission does not control Git merge actions * * Access Level: Read * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetMergeCommit.html */ public toGetMergeCommit() { return this.to('GetMergeCommit'); } /** * Grants permission to get information about merge conflicts between the before and after commit IDs for a pull request in a repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetMergeConflicts.html */ public toGetMergeConflicts() { return this.to('GetMergeConflicts'); } /** * Grants permission to get information about merge options for pull requests that can be used to merge two commits; does not control Git merge actions * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetMergeOptions.html */ public toGetMergeOptions() { return this.to('GetMergeOptions'); } /** * Grants permission to resolve blobs, trees, and commits to their identifier * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-code */ public toGetObjectIdentifier() { return this.to('GetObjectIdentifier'); } /** * Grants permission to get information about a pull request in a specified repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetPullRequest.html */ public toGetPullRequest() { return this.to('GetPullRequest'); } /** * Grants permission to retrieve the current approvals on an inputted pull request * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetPullRequestApprovalStates.html */ public toGetPullRequestApprovalStates() { return this.to('GetPullRequestApprovalStates'); } /** * Grants permission to retrieve the current override state of a given pull request * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetPullRequestOverrideState.html */ public toGetPullRequestOverrideState() { return this.to('GetPullRequestOverrideState'); } /** * Grants permission to get details about references in an AWS CodeCommit repository; does not control Git reference actions * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-code */ public toGetReferences() { return this.to('GetReferences'); } /** * Grants permission to get information about an AWS CodeCommit repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetRepository.html */ public toGetRepository() { return this.to('GetRepository'); } /** * Grants permission to get information about triggers configured for a repository * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetRepositoryTriggers.html */ public toGetRepositoryTriggers() { return this.to('GetRepositoryTriggers'); } /** * Grants permission to view the contents of a specified tree in an AWS CodeCommit repository from the AWS CodeCommit console * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-code */ public toGetTree() { return this.to('GetTree'); } /** * Grants permission to get status information about an archive upload to a pipeline in AWS CodePipeline * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-acp */ public toGetUploadArchiveStatus() { return this.to('GetUploadArchiveStatus'); } /** * Grants permission to pull information from an AWS CodeCommit repository to a local repo * * Access Level: Read * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-git */ public toGitPull() { return this.to('GitPull'); } /** * Grants permission to push information from a local repo to an AWS CodeCommit repository * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-git */ public toGitPush() { return this.to('GitPush'); } /** * Grants permission to list all approval rule templates in an AWS Region for the AWS account * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListApprovalRuleTemplates.html */ public toListApprovalRuleTemplates() { return this.to('ListApprovalRuleTemplates'); } /** * Grants permission to list approval rule templates that are associated with a repository * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListAssociatedApprovalRuleTemplatesForRepository.html */ public toListAssociatedApprovalRuleTemplatesForRepository() { return this.to('ListAssociatedApprovalRuleTemplatesForRepository'); } /** * Grants permission to list branches for an AWS CodeCommit repository with this API; does not control Git branch actions * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListBranches.html */ public toListBranches() { return this.to('ListBranches'); } /** * Grants permission to list pull requests for a specified repository * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListPullRequests.html */ public toListPullRequests() { return this.to('ListPullRequests'); } /** * Grants permission to list information about AWS CodeCommit repositories in the current Region for your AWS account * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListRepositories.html */ public toListRepositories() { return this.to('ListRepositories'); } /** * Grants permission to list repositories that are associated with an approval rule template * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListRepositoriesForApprovalRuleTemplate.html */ public toListRepositoriesForApprovalRuleTemplate() { return this.to('ListRepositoriesForApprovalRuleTemplate'); } /** * Grants permission to list the resource attached to a CodeCommit resource ARN * * Access Level: List * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to merge two commits into the specified destination branch using the fast-forward merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergeBranchesByFastForward.html */ public toMergeBranchesByFastForward() { return this.to('MergeBranchesByFastForward'); } /** * Grants permission to merge two commits into the specified destination branch using the squash merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergeBranchesBySquash.html */ public toMergeBranchesBySquash() { return this.to('MergeBranchesBySquash'); } /** * Grants permission to merge two commits into the specified destination branch using the three-way merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergeBranchesByThreeWay.html */ public toMergeBranchesByThreeWay() { return this.to('MergeBranchesByThreeWay'); } /** * Grants permission to close a pull request and attempt to merge it into the specified destination branch for that pull request at the specified commit using the fast-forward merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergePullRequestByFastForward.html */ public toMergePullRequestByFastForward() { return this.to('MergePullRequestByFastForward'); } /** * Grants permission to close a pull request and attempt to merge it into the specified destination branch for that pull request at the specified commit using the squash merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergePullRequestBySquash.html */ public toMergePullRequestBySquash() { return this.to('MergePullRequestBySquash'); } /** * Grants permission to close a pull request and attempt to merge it into the specified destination branch for that pull request at the specified commit using the three-way merge option * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_MergePullRequestByThreeWay.html */ public toMergePullRequestByThreeWay() { return this.to('MergePullRequestByThreeWay'); } /** * Grants permission to override all approval rules for a pull request, including approval rules created by a template * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_OverridePullRequestApprovalRules.html */ public toOverridePullRequestApprovalRules() { return this.to('OverridePullRequestApprovalRules'); } /** * Grants permission to post a comment on the comparison between two commits * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PostCommentForComparedCommit.html */ public toPostCommentForComparedCommit() { return this.to('PostCommentForComparedCommit'); } /** * Grants permission to post a comment on a pull request * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PostCommentForPullRequest.html */ public toPostCommentForPullRequest() { return this.to('PostCommentForPullRequest'); } /** * Grants permission to post a comment in reply to a comment on a comparison between commits or a pull request * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PostCommentReply.html */ public toPostCommentReply() { return this.to('PostCommentReply'); } /** * Grants permission to post a reaction on a comment * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PutCommentReaction.html */ public toPutCommentReaction() { return this.to('PutCommentReaction'); } /** * Grants permission to add or update a file in a branch in an AWS CodeCommit repository, and generate a commit for the addition in the specified branch * * Access Level: Write * * Possible conditions: * - .ifReferences() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PutFile.html */ public toPutFile() { return this.to('PutFile'); } /** * Grants permission to create, update, or delete triggers for a repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PutRepositoryTriggers.html */ public toPutRepositoryTriggers() { return this.to('PutRepositoryTriggers'); } /** * Grants permission to attach resource tags to a CodeCommit resource ARN * * Access Level: Tagging * * Possible conditions: * - .ifAwsResourceTag() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to test the functionality of repository triggers by sending information to the trigger target * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_TestRepositoryTriggers.html */ public toTestRepositoryTriggers() { return this.to('TestRepositoryTriggers'); } /** * Grants permission to disassociate resource tags from a CodeCommit resource ARN * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the content of approval rule templates; does not grant permission to update content of approval rules created specifically for pull requests * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateApprovalRuleTemplateContent.html */ public toUpdateApprovalRuleTemplateContent() { return this.to('UpdateApprovalRuleTemplateContent'); } /** * Grants permission to update the description of approval rule templates * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateApprovalRuleTemplateDescription.html */ public toUpdateApprovalRuleTemplateDescription() { return this.to('UpdateApprovalRuleTemplateDescription'); } /** * Grants permission to update the name of approval rule templates * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateApprovalRuleTemplateName.html */ public toUpdateApprovalRuleTemplateName() { return this.to('UpdateApprovalRuleTemplateName'); } /** * Grants permission to update the contents of a comment if the identity matches the identity used to create the comment * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateComment.html */ public toUpdateComment() { return this.to('UpdateComment'); } /** * Grants permission to change the default branch in an AWS CodeCommit repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateDefaultBranch.html */ public toUpdateDefaultBranch() { return this.to('UpdateDefaultBranch'); } /** * Grants permission to update the content for approval rules created for a specific pull requests; does not grant permission to update approval rule content for rules created with an approval rule template * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdatePullRequestApprovalRuleContent.html */ public toUpdatePullRequestApprovalRuleContent() { return this.to('UpdatePullRequestApprovalRuleContent'); } /** * Grants permission to update the approval state for pull requests * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdatePullRequestApprovalState.html */ public toUpdatePullRequestApprovalState() { return this.to('UpdatePullRequestApprovalState'); } /** * Grants permission to update the description of a pull request * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdatePullRequestDescription.html */ public toUpdatePullRequestDescription() { return this.to('UpdatePullRequestDescription'); } /** * Grants permission to update the status of a pull request * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdatePullRequestStatus.html */ public toUpdatePullRequestStatus() { return this.to('UpdatePullRequestStatus'); } /** * Grants permission to update the title of a pull request * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdatePullRequestTitle.html */ public toUpdatePullRequestTitle() { return this.to('UpdatePullRequestTitle'); } /** * Grants permission to change the description of an AWS CodeCommit repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateRepositoryDescription.html */ public toUpdateRepositoryDescription() { return this.to('UpdateRepositoryDescription'); } /** * Grants permission to change the name of an AWS CodeCommit repository * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/APIReference/API_UpdateRepositoryName.html */ public toUpdateRepositoryName() { return this.to('UpdateRepositoryName'); } /** * Grants permission to the service role for AWS CodePipeline to upload repository changes into a pipeline * * Access Level: Write * * https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html#aa-acp */ public toUploadArchive() { return this.to('UploadArchive'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateApprovalRuleTemplateWithRepository", "BatchAssociateApprovalRuleTemplateWithRepositories", "BatchDisassociateApprovalRuleTemplateFromRepositories", "CreateApprovalRuleTemplate", "CreateBranch", "CreateCommit", "CreatePullRequest", "CreatePullRequestApprovalRule", "CreateRepository", "CreateUnreferencedMergeCommit", "DeleteApprovalRuleTemplate", "DeleteBranch", "DeleteCommentContent", "DeleteFile", "DeletePullRequestApprovalRule", "DeleteRepository", "DisassociateApprovalRuleTemplateFromRepository", "GitPush", "MergeBranchesByFastForward", "MergeBranchesBySquash", "MergeBranchesByThreeWay", "MergePullRequestByFastForward", "MergePullRequestBySquash", "MergePullRequestByThreeWay", "OverridePullRequestApprovalRules", "PostCommentForComparedCommit", "PostCommentForPullRequest", "PostCommentReply", "PutCommentReaction", "PutFile", "PutRepositoryTriggers", "TestRepositoryTriggers", "UpdateApprovalRuleTemplateContent", "UpdateApprovalRuleTemplateDescription", "UpdateApprovalRuleTemplateName", "UpdateComment", "UpdateDefaultBranch", "UpdatePullRequestApprovalRuleContent", "UpdatePullRequestApprovalState", "UpdatePullRequestDescription", "UpdatePullRequestStatus", "UpdatePullRequestTitle", "UpdateRepositoryDescription", "UpdateRepositoryName", "UploadArchive" ], "Read": [ "BatchDescribeMergeConflicts", "BatchGetCommits", "BatchGetPullRequests", "BatchGetRepositories", "CancelUploadArchive", "DescribeMergeConflicts", "DescribePullRequestEvents", "EvaluatePullRequestApprovalRules", "GetApprovalRuleTemplate", "GetBlob", "GetBranch", "GetComment", "GetCommentReactions", "GetCommentsForComparedCommit", "GetCommentsForPullRequest", "GetCommit", "GetCommitHistory", "GetCommitsFromMergeBase", "GetDifferences", "GetFile", "GetFolder", "GetMergeCommit", "GetMergeConflicts", "GetMergeOptions", "GetObjectIdentifier", "GetPullRequest", "GetPullRequestApprovalStates", "GetPullRequestOverrideState", "GetReferences", "GetRepository", "GetRepositoryTriggers", "GetTree", "GetUploadArchiveStatus", "GitPull" ], "List": [ "ListApprovalRuleTemplates", "ListAssociatedApprovalRuleTemplatesForRepository", "ListBranches", "ListPullRequests", "ListRepositories", "ListRepositoriesForApprovalRuleTemplate", "ListTagsForResource" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type repository to the statement * * https://docs.aws.amazon.com/codecommit/latest/userguide/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); } /** * Filters access by Git reference to specified AWS CodeCommit actions * * https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-conditional-branch.html * * Applies to actions: * - .toCreateBranch() * - .toCreateCommit() * - .toCreateUnreferencedMergeCommit() * - .toDeleteBranch() * - .toDeleteFile() * - .toGetMergeCommit() * - .toGitPush() * - .toMergeBranchesByFastForward() * - .toMergeBranchesBySquash() * - .toMergeBranchesByThreeWay() * - .toMergePullRequestByFastForward() * - .toMergePullRequestBySquash() * - .toMergePullRequestByThreeWay() * - .toPutFile() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifReferences(value: string | string[], operator?: Operator | string) { return this.if(`References`, value, operator || 'StringLike'); } }
the_stack
import { Entity, RELATION_OWNED_BY, RELATION_PART_OF, } from '@backstage/catalog-model'; import { entityRouteRef } from '@backstage/plugin-catalog-react'; import { renderInTestApp } from '@backstage/test-utils'; import React from 'react'; import { AboutContent } from './AboutContent'; describe('<AboutContent />', () => { describe('An unknown entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'custom.company/v1', kind: 'Unknown', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { owner: 'o', domain: 'd', system: 's', type: 't', lifecycle: 'l', }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/o', }, { type: RELATION_PART_OF, targetRef: 'system:default/s', }, { type: RELATION_PART_OF, targetRef: 'domain:default/d', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:o'); expect(getByText('Domain')).toBeInTheDocument(); expect(getByText('Domain').nextSibling).toHaveTextContent('d'); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('s'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('t'); expect(getByText('Lifecycle')).toBeInTheDocument(); expect(getByText('Lifecycle').nextSibling).toHaveTextContent('l'); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; entity.spec = {}; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(queryByText('Type')).not.toBeInTheDocument(); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); }); }); describe('API entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'API', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { type: 'openapi', lifecycle: 'production', owner: 'guest', definition: '...', system: 'system', }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/guest', }, { type: RELATION_PART_OF, targetRef: 'system:default/system', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('system'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('openapi'); expect(getByText('Lifecycle')).toBeInTheDocument(); expect(getByText('Lifecycle').nextSibling).toHaveTextContent( 'production', ); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; delete entity.spec!.type; delete entity.spec!.lifecycle; delete entity.spec!.system; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('No System'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('unknown'); expect(getByText('Lifecycle')).toBeInTheDocument(); expect(getByText('Lifecycle').nextSibling).toHaveTextContent('unknown'); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); describe('Component entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'v1', kind: 'Component', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { owner: 'guest', type: 'service', lifecycle: 'production', system: 'system', subcomponentOf: ['parent-software'], }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/guest', }, { type: RELATION_PART_OF, targetRef: 'system:default/system', }, { type: RELATION_PART_OF, targetRef: 'component:default/parent-software', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('system'); expect(getByText('Parent Component')).toBeInTheDocument(); expect(getByText('Parent Component').nextSibling).toHaveTextContent( 'parent-software', ); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('service'); expect(getByText('Lifecycle')).toBeInTheDocument(); expect(getByText('Lifecycle').nextSibling).toHaveTextContent( 'production', ); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; delete entity.spec!.type; delete entity.spec!.lifecycle; delete entity.spec!.system; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('No System'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('unknown'); expect(getByText('Lifecycle')).toBeInTheDocument(); expect(getByText('Lifecycle').nextSibling).toHaveTextContent('unknown'); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); describe('Domain entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'Domain', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { owner: 'guest', }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/guest', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(queryByText('Type')).not.toBeInTheDocument(); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(queryByText('Type')).not.toBeInTheDocument(); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); describe('Location entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'Location', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { type: 'root', }, relations: [], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('root'); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; delete entity.spec!.type; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('unknown'); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); describe('Resource entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'Resource', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { type: 's3', owner: 'guest', system: 'system', }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/guest', }, { type: RELATION_PART_OF, targetRef: 'system:default/system', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('system'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('s3'); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; delete entity.spec!.type; delete entity.spec!.system; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(queryByText('Domain')).not.toBeInTheDocument(); expect(getByText('System')).toBeInTheDocument(); expect(getByText('System').nextSibling).toHaveTextContent('No System'); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(getByText('Type')).toBeInTheDocument(); expect(getByText('Type').nextSibling).toHaveTextContent('unknown'); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); describe('System entity', () => { let entity: Entity; beforeEach(() => { entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'System', metadata: { name: 'software', description: 'This is the description', tags: ['tag-1'], }, spec: { owner: 'guest', domain: 'domain', }, relations: [ { type: RELATION_OWNED_BY, targetRef: 'user:default/guest', }, { type: RELATION_PART_OF, targetRef: 'domain:default/domain', }, ], }; }); it('renders info', async () => { const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('user:guest'); expect(getByText('Domain')).toBeInTheDocument(); expect(getByText('Domain').nextSibling).toHaveTextContent('domain'); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(queryByText('Type')).not.toBeInTheDocument(); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('tag-1'); }); it('highlights missing required fields', async () => { delete entity.metadata.tags; delete entity.spec!.domain; entity.relations = []; const { getByText, queryByText } = await renderInTestApp( <AboutContent entity={entity} />, { mountedRoutes: { '/catalog/:namespace/:kind/:name': entityRouteRef, }, }, ); expect(getByText('Description')).toBeInTheDocument(); expect(getByText('Description').nextSibling).toHaveTextContent( 'This is the description', ); expect(getByText('Owner')).toBeInTheDocument(); expect(getByText('Owner').nextSibling).toHaveTextContent('No Owner'); expect(getByText('Domain')).toBeInTheDocument(); expect(getByText('Domain').nextSibling).toHaveTextContent('No Domain'); expect(queryByText('System')).not.toBeInTheDocument(); expect(queryByText('Parent Component')).not.toBeInTheDocument(); expect(queryByText('Type')).not.toBeInTheDocument(); expect(queryByText('Lifecycle')).not.toBeInTheDocument(); expect(getByText('Tags')).toBeInTheDocument(); expect(getByText('Tags').nextSibling).toHaveTextContent('No Tags'); }); }); });
the_stack
declare module 'vscode' { /** * Accessibility information which controls screen reader behavior. */ export interface AccessibilityInformation { /** * Label to be read out by a screen reader once the item has focus. */ label: string; /** * Role of the widget which defines how a screen reader interacts with it. * The role should be set in special cases when for example a tree-like element behaves like a checkbox. * If role is not specified VS Code will pick the appropriate role automatically. * More about aria roles can be found here https://w3c.github.io/aria/#widget_roles */ role?: string; } /** * Represents the configuration. It is a merged view of * * - Default configuration * - Global configuration * - Workspace configuration (if available) * - Workspace folder configuration of the requested resource (if available) * * *Global configuration* comes from User Settings and shadows Defaults. * * *Workspace configuration* comes from Workspace Settings and shadows Global configuration. * * *Workspace Folder configuration* comes from `.vscode` folder under one of the [workspace folders](#workspace.workspaceFolders). * * *Note:* Workspace and Workspace Folder configurations contains `launch` and `tasks` settings. Their basename will be * part of the section identifier. The following snippets shows how to retrieve all configurations * from `launch.json`: * * ```ts * // launch.json configuration * const config = workspace.getConfiguration('launch', vscode.window.activeTextEditor.document.uri); * * // retrieve values * const values = config.get('configurations'); * ``` * * Refer to [Settings](https://code.visualstudio.com/docs/getstarted/settings) for more information. */ export interface WorkspaceConfiguration { /** * Return a value from this configuration. * * @param section Configuration name, supports _dotted_ names. * @return The value `section` denotes or `undefined`. */ get<T>(section: string): T | undefined; /** * Return a value from this configuration. * * @param section Configuration name, supports _dotted_ names. * @param defaultValue A value should be returned when no value could be found, is `undefined`. * @return The value `section` denotes or the default. */ get<T>(section: string, defaultValue: T): T; /** * Check if this configuration has a certain value. * * @param section Configuration name, supports _dotted_ names. * @return `true` if the section doesn't resolve to `undefined`. */ has(section: string): boolean; /** * Retrieve all information about a configuration setting. A configuration value * often consists of a *default* value, a global or installation-wide value, * a workspace-specific value and a folder-specific value. * * The *effective* value (returned by [`get`](#WorkspaceConfiguration.get)) * is computed like this: `defaultValue` overwritten by `globalValue`, * `globalValue` overwritten by `workspaceValue`. `workspaceValue` overwritten by `workspaceFolderValue`. * Refer to [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings) * for more information. * * *Note:* The configuration name must denote a leaf in the configuration tree * (`editor.fontSize` vs `editor`) otherwise no result is returned. * * @param section Configuration name, supports _dotted_ names. * @return Information about a configuration setting or `undefined`. */ inspect<T>(section: string): { key: string; defaultValue?: T; globalValue?: T; workspaceValue?: T, workspaceFolderValue?: T } | undefined; /** * Update a configuration value. The updated configuration values are persisted. * * A value can be changed in * * - [Global configuration](#ConfigurationTarget.Global): Changes the value for all instances of the editor. * - [Workspace configuration](#ConfigurationTarget.Workspace): Changes the value for current workspace, if available. * - [Workspace folder configuration](#ConfigurationTarget.WorkspaceFolder): Changes the value for the * [Workspace folder](#workspace.workspaceFolders) to which the current [configuration](#WorkspaceConfiguration) is scoped to. * * *Note 1:* Setting a global value in the presence of a more specific workspace value * has no observable effect in that workspace, but in others. Setting a workspace value * in the presence of a more specific folder value has no observable effect for the resources * under respective [folder](#workspace.workspaceFolders), but in others. Refer to * [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings) for more information. * * *Note 2:* To remove a configuration value use `undefined`, like so: `config.update('somekey', undefined)` * * Will throw error when * - Writing a configuration which is not registered. * - Writing a configuration to workspace or folder target when no workspace is opened * - Writing a configuration to folder target when there is no folder settings * - Writing to folder target without passing a resource when getting the configuration (`workspace.getConfiguration(section, resource)`) * - Writing a window configuration to folder target * * @param section Configuration name, supports _dotted_ names. * @param value The new value. * @param configurationTarget The [configuration target](#ConfigurationTarget) or a boolean value. * - If `true` configuration target is `ConfigurationTarget.Global`. * - If `false` configuration target is `ConfigurationTarget.Workspace`. * - If `undefined` or `null` configuration target is * `ConfigurationTarget.WorkspaceFolder` when configuration is resource specific * `ConfigurationTarget.Workspace` otherwise. */ update(section: string, value: any, configurationTarget?: ConfigurationTarget | boolean): Thenable<void>; /** * Readable dictionary that backs this configuration. */ readonly [key: string]: any; } export interface ConfigurationChangeEvent { /** * Returns `true` if the given section for the given resource (if provided) is affected. * * @param section Configuration name, supports _dotted_ names. * @param resource A resource Uri. * @return `true` if the given section for the given resource (if provided) is affected. */ affectsConfiguration(section: string, resource?: Uri): boolean; } /** * The configuration target */ export enum ConfigurationTarget { /** * Global configuration */ Global = 1, /** * Workspace configuration */ Workspace = 2, /** * Workspace folder configuration */ WorkspaceFolder = 3, } /** * A workspace folder is one of potentially many roots opened by the editor. All workspace folders * are equal which means there is no notion of an active or master workspace folder. */ export interface WorkspaceFolder { /** * The associated uri for this workspace folder. * * *Note:* The [Uri](#Uri)-type was intentionally chosen such that future releases of the editor can support * workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`. */ readonly uri: Uri; /** * The name of this workspace folder. Defaults to * the basename of its [uri-path](#Uri.path) */ readonly name: string; /** * The ordinal number of this workspace folder. */ readonly index: number; } /** * A uri handler is responsible for handling system-wide [uris](#Uri). * * @see [window.registerUriHandler](#window.registerUriHandler). */ export interface UriHandler { /** * Handle the provided system-wide [uri](#Uri). * * @see [window.registerUriHandler](#window.registerUriHandler). */ handleUri(uri: Uri): ProviderResult<void>; } /** * Content settings for a webview panel. */ export interface WebviewPanelOptions { /** * Controls if the find widget is enabled in the panel. * * Defaults to false. */ readonly enableFindWidget?: boolean; /** * Controls if the webview panel's content (iframe) is kept around even when the panel * is no longer visible. * * Normally the webview panel's html context is created when the panel becomes visible * and destroyed when it is hidden. Extensions that have complex state * or UI can set the `retainContextWhenHidden` to make VS Code keep the webview * context around, even when the webview moves to a background tab. When a webview using * `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended. * When the panel becomes visible again, the context is automatically restored * in the exact same state it was in originally. You cannot send messages to a * hidden webview, even with `retainContextWhenHidden` enabled. * * `retainContextWhenHidden` has a high memory overhead and should only be used if * your panel's context cannot be quickly saved and restored. */ readonly retainContextWhenHidden?: boolean; } /** * Value-object describing what options a terminal should use. */ export interface TerminalOptions { /** * A human-readable string which will be used to represent the terminal in the UI. */ name?: string; /** * A path to a custom shell executable to be used in the terminal. */ shellPath?: string; /** * Args for the custom shell executable. A string can be used on Windows only which allows * specifying shell args in [command-line format](https://msdn.microsoft.com/en-au/08dfcab2-eb6e-49a4-80eb-87d4076c98c6). */ shellArgs?: string[] | string; /** * A path or Uri for the current working directory to be used for the terminal. */ cwd?: string | Uri; /** * Object with environment variables that will be added to the VS Code process. */ env?: { [key: string]: string | null }; /** * Whether the terminal process environment should be exactly as provided in * `TerminalOptions.env`. When this is false (default), the environment will be based on the * window's environment and also apply configured platform settings like * `terminal.integrated.windows.env` on top. When this is true, the complete environment * must be provided as nothing will be inherited from the process or any configuration. */ strictEnv?: boolean; /** * When enabled the terminal will run the process as normal but not be surfaced to the user * until `Terminal.show` is called. The typical usage for this is when you need to run * something that may need interactivity but only want to tell the user about it when * interaction is needed. Note that the terminals will still be exposed to all extensions * as normal. */ hideFromUser?: boolean; /** * Whether an extension is controlling the terminal via a `vscode.Pseudoterminal`. */ isExtensionTerminal?: boolean; /** * A message to write to the terminal on first launch, note that this is not sent to the * process but, rather written directly to the terminal. This supports escape sequences such * a setting text style. */ message?: string; /** * The icon path or {@link ThemeIcon} for the terminal. */ iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; /** * The icon {@link ThemeColor} for the terminal. * The `terminal.ansi*` theme keys are * recommended for the best contrast and consistency across themes. */ color?: ThemeColor; } /** * Provides information on a line in a terminal in order to provide links for it. */ export interface TerminalLinkContext { /** * This is the text from the unwrapped line in the terminal. */ line: string; /** * The terminal the link belongs to. */ terminal: Terminal; } /** * A provider that enables detection and handling of links within terminals. */ export interface TerminalLinkProvider<T extends TerminalLink = TerminalLink> { /** * Provide terminal links for the given context. Note that this can be called multiple times * even before previous calls resolve, make sure to not share global objects (eg. `RegExp`) * that could have problems when asynchronous usage may overlap. * @param context Information about what links are being provided for. * @param token A cancellation token. * @return A list of terminal links for the given line. */ provideTerminalLinks(context: TerminalLinkContext, token: CancellationToken): ProviderResult<T[]>; /** * Handle an activated terminal link. * @param link The link to handle. */ handleTerminalLink(link: T): ProviderResult<void>; } /** * A link on a terminal line. */ export class TerminalLink { /** * The start index of the link on {@link TerminalLinkContext.line}. */ startIndex: number; /** * The length of the link on {@link TerminalLinkContext.line}. */ length: number; /** * The tooltip text when you hover over this link. * * If a tooltip is provided, is will be displayed in a string that includes instructions on * how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary * depending on OS, user settings, and localization. */ tooltip?: string; /** * Creates a new terminal link. * @param startIndex The start index of the link on {@link TerminalLinkContext.line}. * @param length The length of the link on {@link TerminalLinkContext.line}. * @param tooltip The tooltip text when you hover over this link. * * If a tooltip is provided, is will be displayed in a string that includes instructions on * how to trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary * depending on OS, user settings, and localization. */ constructor(startIndex: number, length: number, tooltip?: string); } /** * Provides a terminal profile for the contributed terminal profile when launched via the UI or * command. */ export interface TerminalProfileProvider { /** * Provide the terminal profile. * @param token A cancellation token that indicates the result is no longer needed. * @returns The terminal profile. */ provideTerminalProfile(token: CancellationToken): ProviderResult<TerminalProfile>; } /** * A terminal profile defines how a terminal will be launched. */ export class TerminalProfile { /** * The options that the terminal will launch with. */ options: TerminalOptions | ExtensionTerminalOptions; /** * Creates a new terminal profile. * @param options The options that the terminal will launch with. */ constructor(options: TerminalOptions | ExtensionTerminalOptions); } /** * Class used to execute an extension callback as a task. */ export class CustomExecution { /** * Constructs a CustomExecution task object. The callback will be executed the task is run, at which point the * extension should return the Pseudoterminal it will "run in". The task should wait to do further execution until * [Pseudoterminal.open](#Pseudoterminal.open) is called. Task cancellation should be handled using * [Pseudoterminal.close](#Pseudoterminal.close). When the task is complete fire * [Pseudoterminal.onDidClose](#Pseudoterminal.onDidClose). * @param process The [Pseudoterminal](#Pseudoterminal) to be used by the task to display output. * @param callback The callback that will be called when the task is started by a user. */ constructor(callback: () => Thenable<Pseudoterminal>); } /** * Value-object describing what options a virtual process terminal should use. */ export interface ExtensionTerminalOptions { /** * A human-readable string which will be used to represent the terminal in the UI. */ name: string; /** * An implementation of [Pseudoterminal](#Pseudoterminal) that allows an extension to * control a terminal. */ pty: Pseudoterminal; /** * The icon path or {@link ThemeIcon} for the terminal. */ iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; /** * The icon {@link ThemeColor} for the terminal. * The standard `terminal.ansi*` theme keys are * recommended for the best contrast and consistency across themes. */ color?: ThemeColor; } /** * Defines the interface of a terminal pty, enabling extensions to control a terminal. */ interface Pseudoterminal { /** * An event that when fired will write data to the terminal. Unlike * [Terminal.sendText](#Terminal.sendText) which sends text to the underlying child * pseudo-device (the child), this will write the text to parent pseudo-device (the * _terminal_ itself). * * Note writing `\n` will just move the cursor down 1 row, you need to write `\r` as well * to move the cursor to the left-most cell. * * **Example:** Write red text to the terminal * ```typescript * const writeEmitter = new vscode.EventEmitter<string>(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * open: () => writeEmitter.fire('\x1b[31mHello world\x1b[0m'), * close: () => {} * }; * vscode.window.createTerminal({ name: 'My terminal', pty }); * ``` * * **Example:** Move the cursor to the 10th row and 20th column and write an asterisk * ```typescript * writeEmitter.fire('\x1b[10;20H*'); * ``` */ onDidWrite: Event<string>; /** * An event that when fired allows overriding the [dimensions](#Pseudoterminal.setDimensions) of the * terminal. Note that when set, the overridden dimensions will only take effect when they * are lower than the actual dimensions of the terminal (ie. there will never be a scroll * bar). Set to `undefined` for the terminal to go back to the regular dimensions (fit to * the size of the panel). * * **Example:** Override the dimensions of a terminal to 20 columns and 10 rows * ```typescript * const dimensionsEmitter = new vscode.EventEmitter<vscode.TerminalDimensions>(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * onDidOverrideDimensions: dimensionsEmitter.event, * open: () => { * dimensionsEmitter.fire({ * columns: 20, * rows: 10 * }); * }, * close: () => {} * }; * vscode.window.createTerminal({ name: 'My terminal', pty }); * ``` */ onDidOverrideDimensions?: Event<TerminalDimensions | undefined>; /** * An event that when fired will signal that the pty is closed and dispose of the terminal. * * A number can be used to provide an exit code for the terminal. Exit codes must be * positive and a non-zero exit codes signals failure which shows a notification for a * regular terminal and allows dependent tasks to proceed when used with the * `CustomExecution` API. * * **Example:** Exit the terminal when "y" is pressed, otherwise show a notification. * ```typescript * const writeEmitter = new vscode.EventEmitter<string>(); * const closeEmitter = new vscode.EventEmitter<vscode.TerminalDimensions>(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * onDidClose: closeEmitter.event, * open: () => writeEmitter.fire('Press y to exit successfully'), * close: () => {}, * handleInput: data => { * if (data !== 'y') { * vscode.window.showInformationMessage('Something went wrong'); * } * closeEmitter.fire(); * } * }; * vscode.window.createTerminal({ name: 'Exit example', pty }); * ``` */ onDidClose?: Event<void | number>; /** * An event that when fired allows changing the name of the terminal. * * **Example:** Change the terminal name to "My new terminal". * ```typescript * const writeEmitter = new vscode.EventEmitter<string>(); * const changeNameEmitter = new vscode.EventEmitter<string>(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * onDidChangeName: changeNameEmitter.event, * open: () => changeNameEmitter.fire('My new terminal'), * close: () => {} * }; * vscode.window.createTerminal({ name: 'My terminal', pty }); * ``` */ onDidChangeName?: Event<string>; /** * Implement to handle when the pty is open and ready to start firing events. * * @param initialDimensions The dimensions of the terminal, this will be undefined if the * terminal panel has not been opened before this is called. */ open(initialDimensions: TerminalDimensions | undefined): void; /** * Implement to handle when the terminal is closed by an act of the user. */ close(): void; /** * Implement to handle incoming keystrokes in the terminal or when an extension calls * [Terminal.sendText](#Terminal.sendText). `data` contains the keystrokes/text serialized into * their corresponding VT sequence representation. * * @param data The incoming data. * * **Example:** Echo input in the terminal. The sequence for enter (`\r`) is translated to * CRLF to go to a new line and move the cursor to the start of the line. * ```typescript * const writeEmitter = new vscode.EventEmitter<string>(); * const pty: vscode.Pseudoterminal = { * onDidWrite: writeEmitter.event, * open: () => {}, * close: () => {}, * handleInput: data => writeEmitter.fire(data === '\r' ? '\r\n' : data) * }; * vscode.window.createTerminal({ name: 'Local echo', pty }); * ``` */ handleInput?(data: string): void; /** * Implement to handle when the number of rows and columns that fit into the terminal panel * changes, for example when font size changes or when the panel is resized. The initial * state of a terminal's dimensions should be treated as `undefined` until this is triggered * as the size of a terminal isn't know until it shows up in the user interface. * * When dimensions are overridden by * [onDidOverrideDimensions](#Pseudoterminal.onDidOverrideDimensions), `setDimensions` will * continue to be called with the regular panel dimensions, allowing the extension continue * to react dimension changes. * * @param dimensions The new dimensions. */ setDimensions?(dimensions: TerminalDimensions): void; } /** * The clipboard provides read and write access to the system's clipboard. */ export interface Clipboard { /** * Read the current clipboard contents as text. * @returns A thenable that resolves to a string. */ readText(): Thenable<string>; /** * Writes text into the clipboard. * @returns A thenable that resolves when writing happened. */ writeText(value: string): Thenable<void>; } /** * A selection range represents a part of a selection hierarchy. A selection range * may have a parent selection range that contains it. */ export class SelectionRange { /** * The [range](#Range) of this selection range. */ range: Range; /** * The parent selection range containing this range. */ parent?: SelectionRange; /** * Creates a new selection range. * * @param range The range of the selection range. * @param parent The parent of the selection range. */ constructor(range: Range, parent?: SelectionRange); } /** * A tuple of two characters, like a pair of * opening and closing brackets. */ export type CharacterPair = [string, string]; /** * The workspace symbol provider interface defines the contract between extensions and * the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature. */ export interface WorkspaceSymbolProvider<T extends SymbolInformation = SymbolInformation> { /** * Project-wide search for a symbol matching the given query string. * * The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting * and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the * characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar * strict matching. * * To improve performance implementors can implement `resolveWorkspaceSymbol` and then provide symbols with partial * {@link SymbolInformation.location location}-objects, without a `range` defined. The editor will then call * `resolveWorkspaceSymbol` for selected symbols only, e.g. when opening a workspace symbol. * * @param query A query string, can be the empty string in which case all symbols should be returned. * @param token A cancellation token. * @return An array of document highlights or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined`, `null`, or an empty array. */ provideWorkspaceSymbols(query: string, token: CancellationToken): ProviderResult<T[]>; /** * Given a symbol fill in its {@link SymbolInformation.location location}. This method is called whenever a symbol * is selected in the UI. Providers can implement this method and return incomplete symbols from * {@link WorkspaceSymbolProvider.provideWorkspaceSymbols `provideWorkspaceSymbols`} which often helps to improve * performance. * * @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an * earlier call to `provideWorkspaceSymbols`. * @param token A cancellation token. * @return The resolved symbol or a thenable that resolves to that. When no result is returned, * the given `symbol` is used. */ resolveWorkspaceSymbol?(symbol: T, token: CancellationToken): ProviderResult<T>; } /** * Describes how comments for a language work. */ export interface CommentRule { /** * The line comment token, like `// this is a comment` */ lineComment?: string; /** * The block comment character pair, like `/* block comment *&#47;` */ blockComment?: CharacterPair; } /** * Describes a rule to be evaluated when pressing Enter. */ export interface OnEnterRule { /** * This rule will only execute if the text before the cursor matches this regular expression. */ beforeText: RegExp; /** * This rule will only execute if the text after the cursor matches this regular expression. */ afterText?: RegExp; /** * The action to execute. */ action: EnterAction; previousLineText?: RegExp; } /** * Describes indentation rules for a language. */ export interface IndentationRule { /** * If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches). */ decreaseIndentPattern: RegExp; /** * If a line matches this pattern, then all the lines after it should be indented once (until another rule matches). */ increaseIndentPattern: RegExp; /** * If a line matches this pattern, then **only the next line** after it should be indented once. */ indentNextLinePattern?: RegExp; /** * If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules. */ unIndentedLinePattern?: RegExp; } /** * A workspace folder is one of potentially many roots opened by the editor. All workspace folders * are equal which means there is no notion of an active or master workspace folder. */ export interface WorkspaceFolder { /** * The associated uri for this workspace folder. * * *Note:* The [Uri](#Uri)-type was intentionally chosen such that future releases of the editor can support * workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`. */ readonly uri: Uri; /** * The name of this workspace folder. Defaults to * the basename of its [uri-path](#Uri.path) */ readonly name: string; /** * The ordinal number of this workspace folder. */ readonly index: number; } /** * Represents reasons why a text document is saved. */ export enum TextDocumentSaveReason { /** * Manually triggered, e.g. by the user pressing save, by starting debugging, * or by an API call. */ Manual = 1, /** * Automatic after a delay. */ AfterDelay = 2, /** * When the editor lost focus. */ FocusOut = 3, } /** * Content settings for a webview. */ export interface WebviewOptions { /** * Controls whether scripts are enabled in the webview content or not. * * Defaults to false (scripts-disabled). */ readonly enableScripts?: boolean; /** * Controls whether forms are enabled in the webview content or not. * * Defaults to true if {@link WebviewOptions.enableScripts scripts are enabled}. Otherwise defaults to false. * Explicitly setting this property to either true or false overrides the default. */ readonly enableForms?: boolean; /** * Controls whether command uris are enabled in webview content or not. * * Defaults to false. */ readonly enableCommandUris?: boolean; /** * Root paths from which the webview can load local (filesystem) resources using the `vscode-resource:` scheme. * * Default to the root folders of the current workspace plus the extension's install directory. * * Pass in an empty array to disallow access to any local resources. */ readonly localResourceRoots?: ReadonlyArray<Uri>; /** * Mappings of localhost ports used inside the webview. * * Port mapping allow webviews to transparently define how localhost ports are resolved. This can be used * to allow using a static localhost port inside the webview that is resolved to random port that a service is * running on. * * If a webview accesses localhost content, we recommend that you specify port mappings even if * the `webviewPort` and `extensionHostPort` ports are the same. * * *Note* that port mappings only work for `http` or `https` urls. Websocket urls (e.g. `ws://localhost:3000`) * cannot be mapped to another port. */ readonly portMapping?: ReadonlyArray<WebviewPortMapping>; } /** * A webview displays html content, like an iframe. */ export interface Webview { /** * Content settings for the webview. */ options: WebviewOptions; /** * Contents of the webview. * * Should be a complete html document. */ html: string; /** * Fired when the webview content posts a message. */ readonly onDidReceiveMessage: Event<any>; /** * Post a message to the webview content. * * Messages are only delivered if the webview is visible. * * @param message Body of the message. */ postMessage(message: any): Thenable<boolean>; /** * Convert a uri for the local file system to one that can be used inside webviews. * * Webviews cannot directly load resources from the workspace or local file system using `file:` uris. The * `asWebviewUri` function takes a local `file:` uri and converts it into a uri that can be used inside of * a webview to load the same resource: * * ```ts * webview.html = `<img src="${webview.asWebviewUri(vscode.Uri.file('/Users/codey/workspace/cat.gif'))}">` * ``` */ asWebviewUri(localResource: Uri): Uri; /** * Content security policy source for webview resources. * * This is the origin that should be used in a content security policy rule: * * ``` * img-src https: ${webview.cspSource} ...; * ``` */ readonly cspSource: string; } /** * Represents the state of a window. */ export interface WindowState { /** * Whether the current window is focused. */ readonly focused: boolean; } /** * Represents a parameter of a callable-signature. A parameter can * have a label and a doc-comment. */ export class ParameterInformation { /** * The label of this signature. * * Either a string or inclusive start and exclusive end offsets within its containing * [signature label](#SignatureInformation.label). *Note*: A label of type string must be * a substring of its containing signature information's [label](#SignatureInformation.label). */ label: string | [number, number]; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string | MarkdownString; /** * Creates a new parameter information object. * * @param label A label string or inclusive start and exclusive end offsets within its containing signature label. * @param documentation A doc string. */ constructor(label: string | [number, number], documentation?: string | MarkdownString); } /** * How a [`SignatureHelpProvider`](#SignatureHelpProvider) was triggered. */ export enum SignatureHelpTriggerKind { /** * Signature help was invoked manually by the user or by a command. */ Invoke = 1, /** * Signature help was triggered by a trigger character. */ TriggerCharacter = 2, /** * Signature help was triggered by the cursor moving or by the document content changing. */ ContentChange = 3, } /** * Additional information about the context in which a * [`SignatureHelpProvider`](#SignatureHelpProvider.provideSignatureHelp) was triggered. */ export interface SignatureHelpContext { /** * Action that caused signature help to be triggered. */ readonly triggerKind: SignatureHelpTriggerKind; /** * Character that caused signature help to be triggered. * * This is `undefined` when signature help is not triggered by typing, such as when manually invoking * signature help or when moving the cursor. */ readonly triggerCharacter?: string; /** * `true` if signature help was already showing when it was triggered. * * Retriggers occur when the signature help is already active and can be caused by actions such as * typing a trigger character, a cursor move, or document content changes. */ readonly isRetrigger: boolean; /** * The currently active [`SignatureHelp`](#SignatureHelp). * * The `activeSignatureHelp` has its [`SignatureHelp.activeSignature`] field updated based on * the user arrowing through available signatures. */ readonly activeSignatureHelp?: SignatureHelp; } /** * The signature help provider interface defines the contract between extensions and * the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature. */ export interface SignatureHelpProvider { /** * Provide help for the signature at the given position and document. * * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param token A cancellation token. * @param context Information about how signature help was triggered. * * @return Signature help or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSignatureHelp(document: TextDocument, position: Position, token: CancellationToken, context: SignatureHelpContext): ProviderResult<SignatureHelp>; } /** * Metadata about a registered [`SignatureHelpProvider`](#SignatureHelpProvider). */ export interface SignatureHelpProviderMetadata { /** * List of characters that trigger signature help. */ readonly triggerCharacters: ReadonlyArray<string>; /** * List of characters that re-trigger signature help. * * These trigger characters are only active when signature help is already showing. All trigger characters * are also counted as re-trigger characters. */ readonly retriggerCharacters: ReadonlyArray<string>; } /** * Represents the signature of something callable. A signature * can have a label, like a function-name, a doc-comment, and * a set of parameters. */ export class SignatureInformation { /** * The label of this signature. Will be shown in * the UI. */ label: string; /** * The human-readable doc-comment of this signature. Will be shown * in the UI but can be omitted. */ documentation?: string | MarkdownString; /** * The parameters of this signature. */ parameters: ParameterInformation[]; /** * The index of the active parameter. * * If provided, this is used in place of {@linkcode SignatureHelp.activeSignature}. */ activeParameter?: number; /** * Creates a new signature information object. * * @param label A label string. * @param documentation A doc string. */ constructor(label: string, documentation?: string | MarkdownString); } /** * Signature help represents the signature of something * callable. There can be multiple signatures but only one * active and only one active parameter. */ export class SignatureHelp { /** * One or more signatures. */ signatures: SignatureInformation[]; /** * The active signature. */ activeSignature: number; /** * The active parameter of the active signature. */ activeParameter: number; } /** * Symbol tags are extra annotations that tweak the rendering of a symbol. */ export enum SymbolTag { /** * Render a symbol as obsolete, usually using a strike-out. */ Deprecated = 1, } /** * Represents information about programming constructs like variables, classes, * interfaces etc. */ export class SymbolInformation { /** * The name of this symbol. */ name: string; /** * The name of the symbol containing this symbol. */ containerName: string; /** * The kind of this symbol. */ kind: SymbolKind; /** * Tags for this symbol. */ tags?: ReadonlyArray<SymbolTag>; /** * The location of this symbol. */ location: Location; /** * Creates a new symbol information object. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param containerName The name of the symbol containing the symbol. * @param location The location of the symbol. */ constructor(name: string, kind: SymbolKind, containerName: string, location: Location); /** * ~~Creates a new symbol information object.~~ * * @deprecated Please use the constructor taking a [location](#Location) object. * * @param name The name of the symbol. * @param kind The kind of the symbol. * @param range The range of the location of the symbol. * @param uri The resource of the location of symbol, defaults to the current document. * @param containerName The name of the symbol containing the symbol. */ constructor(name: string, kind: SymbolKind, range: Range, uri?: Uri, containerName?: string); } /** * A symbol kind. */ export enum SymbolKind { File = 0, Module = 1, Namespace = 2, Package = 3, Class = 4, Method = 5, Property = 6, Field = 7, Constructor = 8, Enum = 9, Interface = 10, Function = 11, Variable = 12, Constant = 13, String = 14, Number = 15, Boolean = 16, Array = 17, Object = 18, Key = 19, Null = 20, EnumMember = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, } /** * The version of the editor. */ export const version: string; /** * In a remote window the extension kind describes if an extension * runs where the UI (window) runs or if an extension runs remotely. */ export enum ExtensionKind { /** * Extension runs where the UI runs. */ UI = 1, /** * Extension runs where the remote extension host runs. */ Workspace = 2, } export interface SelectionRangeProvider { /** * Provide selection ranges for the given positions. * * Selection ranges should be computed individually and independend for each position. The editor will merge * and deduplicate ranges but providers must return hierarchies of selection ranges so that a range * is [contained](#Range.contains) by its parent. * * @param document The document in which the command was invoked. * @param positions The positions at which the command was invoked. * @param token A cancellation token. * @return Selection ranges or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideSelectionRanges(document: TextDocument, positions: Position[], token: CancellationToken): ProviderResult<SelectionRange[]>; } /** * Contains additional information about the context in which * [completion provider](#CompletionItemProvider.provideCompletionItems) is triggered. */ export interface CompletionContext { /** * How the completion was triggered. */ readonly triggerKind: CompletionTriggerKind; /** * Character that triggered the completion item provider. * * `undefined` if provider was not triggered by a character. * * The trigger character is already in the document when the completion provider is triggered. */ readonly triggerCharacter?: string; } /** * How a [completion provider](#CompletionItemProvider) was triggered */ export enum CompletionTriggerKind { /** * Completion was triggered normally. */ Invoke = 0, /** * Completion was triggered by a trigger character. */ TriggerCharacter = 1, /** * Completion was re-triggered as current completion list is incomplete */ TriggerForIncompleteCompletions = 2, } /** * Completion item kinds. */ export enum CompletionItemKind { Text = 0, Method = 1, Function = 2, Constructor = 3, Field = 4, Variable = 5, Class = 6, Interface = 7, Module = 8, Property = 9, Unit = 10, Value = 11, Enum = 12, Keyword = 13, Snippet = 14, Color = 15, Reference = 17, File = 16, Folder = 18, EnumMember = 19, Constant = 20, Struct = 21, Event = 22, Operator = 23, TypeParameter = 24, User = 25, Issue = 26, } export enum CompletionItemTag { Deprecated = 1, } /** * Additional data for entries of a workspace edit. Supports to label entries and marks entries * as needing confirmation by the user. The editor groups edits with equal labels into tree nodes, * for instance all edits labelled with "Changes in Strings" would be a tree node. */ export interface WorkspaceEditEntryMetadata { /** * A flag which indicates that user confirmation is needed. */ needsConfirmation: boolean; /** * A human-readable string which is rendered prominent. */ label: string; /** * A human-readable string which is rendered less prominent on the same line. */ description?: string; /** * The icon path or [ThemeIcon](#ThemeIcon) for the edit. */ iconPath?: Uri | { light: Uri; dark: Uri } | ThemeIcon; } /** * A workspace edit is a collection of textual and files changes for * multiple resources and documents. * * Use the [applyEdit](#workspace.applyEdit)-function to apply a workspace edit. */ export class WorkspaceEdit { /** * The number of affected resources of textual or resource changes. */ readonly size: number; /** * Replace the given range with given text for the given resource. * * @param uri A resource identifier. * @param range A range. * @param newText A string. */ replace(uri: Uri, range: Range, newText: string, metadata?: WorkspaceEditEntryMetadata): void; /** * Insert the given text at the given position. * * @param uri A resource identifier. * @param position A position. * @param newText A string. */ insert(uri: Uri, position: Position, newText: string, metadata?: WorkspaceEditEntryMetadata): void; /** * Delete the text at the given range. * * @param uri A resource identifier. * @param range A range. */ delete(uri: Uri, range: Range, metadata?: WorkspaceEditEntryMetadata): void; /** * Check if a text edit for a resource exists. * * @param uri A resource identifier. * @return `true` if the given resource will be touched by this edit. */ has(uri: Uri): boolean; /** * Set (and replace) text edits for a resource. * * @param uri A resource identifier. * @param edits An array of text edits. */ set(uri: Uri, edits: TextEdit[]): void; /** * Get the text edits for a resource. * * @param uri A resource identifier. * @return An array of text edits. */ get(uri: Uri): TextEdit[]; /** * Create a regular file. * * @param uri Uri of the new file.. * @param options Defines if an existing file should be overwritten or be * ignored. When overwrite and ignoreIfExists are both set overwrite wins. */ createFile(uri: Uri, options?: { overwrite?: boolean, ignoreIfExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; /** * Delete a file or folder. * * @param uri The uri of the file that is to be deleted. */ deleteFile(uri: Uri, options?: { recursive?: boolean, ignoreIfNotExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; /** * Rename a file or folder. * * @param oldUri The existing file. * @param newUri The new location. * @param options Defines if existing files should be overwritten or be * ignored. When overwrite and ignoreIfExists are both set overwrite wins. */ renameFile(oldUri: Uri, newUri: Uri, options?: { overwrite?: boolean, ignoreIfExists?: boolean }, metadata?: WorkspaceEditEntryMetadata): void; /** * Get all text edits grouped by resource. * * @return A shallow copy of `[Uri, TextEdit[]]`-tuples. */ entries(): [Uri, TextEdit[]][]; } /** * Options for creating a [TreeView](#TreeView) */ export interface TreeViewOptions<T> { /** * A data provider that provides tree data. */ treeDataProvider: TreeDataProvider<T>; /** * Whether to show collapse all action or not. */ showCollapseAll?: boolean; /** * Whether the tree supports multi-select. When the tree supports multi-select and a command is executed from the tree, * the first argument to the command is the tree item that the command was executed on and the second argument is an * array containing all selected tree items. */ canSelectMany?: boolean; } /** * The event that is fired when an element in the [TreeView](#TreeView) is expanded or collapsed */ export interface TreeViewExpansionEvent<T> { /** * Element that is expanded or collapsed. */ readonly element: T; } /** * The event that is fired when there is a change in [tree view's selection](#TreeView.selection) */ export interface TreeViewSelectionChangeEvent<T> { /** * Selected elements. */ readonly selection: T[]; } /** * The event that is fired when there is a change in [tree view's visibility](#TreeView.visible) */ export interface TreeViewVisibilityChangeEvent { /** * `true` if the [tree view](#TreeView) is visible otherwise `false`. */ readonly visible: boolean; } /** * Represents a Tree view */ export interface TreeView<T> extends Disposable { /** * Event that is fired when an element is expanded */ readonly onDidExpandElement: Event<TreeViewExpansionEvent<T>>; /** * Event that is fired when an element is collapsed */ readonly onDidCollapseElement: Event<TreeViewExpansionEvent<T>>; /** * Currently selected elements. */ readonly selection: T[]; /** * Event that is fired when the [selection](#TreeView.selection) has changed */ readonly onDidChangeSelection: Event<TreeViewSelectionChangeEvent<T>>; /** * `true` if the [tree view](#TreeView) is visible otherwise `false`. */ readonly visible: boolean; /** * Event that is fired when [visibility](#TreeView.visible) has changed */ readonly onDidChangeVisibility: Event<TreeViewVisibilityChangeEvent>; /** * An optional human-readable message that will be rendered in the view. * Setting the message to null, undefined, or empty string will remove the message from the view. */ message?: string; /** * The tree view title is initially taken from the extension package.json * Changes to the title property will be properly reflected in the UI in the title of the view. */ title?: string; /** * An optional human-readable description which is rendered less prominently in the title of the view. * Setting the title description to null, undefined, or empty string will remove the description from the view. */ description?: string; /** * Reveals the given element in the tree view. * If the tree view is not visible then the tree view is shown and element is revealed. * * By default revealed element is selected. * In order to not to select, set the option `select` to `false`. * In order to focus, set the option `focus` to `true`. * In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand. * **NOTE:** You can expand only to 3 levels maximum. * * **NOTE:** The [TreeDataProvider](#TreeDataProvider) that the `TreeView` [is registered with](#window.createTreeView) with must implement [getParent](#TreeDataProvider.getParent) method to access this API. */ reveal(element: T, options?: { select?: boolean, focus?: boolean, expand?: boolean | number }): Thenable<void>; } /** * Collapsible state of the tree item */ export enum TreeItemCollapsibleState { /** * Determines an item can be neither collapsed nor expanded. Implies it has no children. */ None = 0, /** * Determines an item is collapsed */ Collapsed = 1, /** * Determines an item is expanded */ Expanded = 2, } /** * A data provider that provides tree data */ export interface TreeDataProvider<T> { /** * An optional event to signal that an element or root has changed. * This will trigger the view to update the changed element/root and its children recursively (if shown). * To signal that root has changed, do not pass any argument or pass `undefined` or `null`. */ onDidChangeTreeData?: Event<T | undefined | null>; /** * Get [TreeItem](#TreeItem) representation of the `element` * * @param element The element for which [TreeItem](#TreeItem) representation is asked for. * @return [TreeItem](#TreeItem) representation of the element */ getTreeItem(element: T): TreeItem | Thenable<TreeItem>; /** * Get the children of `element` or root if no element is passed. * * @param element The element from which the provider gets children. Can be `undefined`. * @return Children of `element` or root if no element is passed. */ getChildren(element?: T): ProviderResult<T[]>; /** * Optional method to return the parent of `element`. * Return `null` or `undefined` if `element` is a child of root. * * **NOTE:** This method should be implemented in order to access [reveal](#TreeView.reveal) API. * * @param element The element for which the parent has to be returned. * @return Parent of `element`. */ getParent?(element: T): ProviderResult<T>; /** * Called on hover to resolve the {@link TreeItem.tooltip TreeItem} property if it is undefined. * Called on tree item click/open to resolve the {@link TreeItem.command TreeItem} property if it is undefined. * Only properties that were undefined can be resolved in `resolveTreeItem`. * Functionality may be expanded later to include being called to resolve other missing * properties on selection and/or on open. * * Will only ever be called once per TreeItem. * * onDidChangeTreeData should not be triggered from within resolveTreeItem. * * *Note* that this function is called when tree items are already showing in the UI. * Because of that, no property that changes the presentation (label, description, etc.) * can be changed. * * @param item Undefined properties of `item` should be set then `item` should be returned. * @param element The object associated with the TreeItem. * @param token A cancellation token. * @return The resolved tree item or a thenable that resolves to such. It is OK to return the given * `item`. When no result is returned, the given `item` will be used. */ resolveTreeItem?(item: TreeItem, element: T, token: CancellationToken): ProviderResult<TreeItem>; } export class TreeItem { /** * A human-readable string describing this item. When `falsy`, it is derived from {@link TreeItem.resourceUri resourceUri}. */ label?: string | TreeItemLabel; /** * Optional id for the tree item that has to be unique across tree. The id is used to preserve the selection and expansion state of the tree item. * * If not provided, an id is generated using the tree item's label. **Note** that when labels change, ids will change and that selection and expansion state cannot be kept stable anymore. */ id?: string; /** * The icon path or [ThemeIcon](#ThemeIcon) for the tree item. * When `falsy`, [Folder Theme Icon](#ThemeIcon.Folder) is assigned, if item is collapsible otherwise [File Theme Icon](#ThemeIcon.File). * When a [ThemeIcon](#ThemeIcon) is specified, icon is derived from the current file icon theme for the specified theme icon using [resourceUri](#TreeItem.resourceUri) (if provided). */ iconPath?: string | Uri | { light: string | Uri; dark: string | Uri } | ThemeIcon; /** * A human readable string which is rendered less prominent. * When `true`, it is derived from [resourceUri](#TreeItem.resourceUri) and when `falsy`, it is not shown. */ description?: string | boolean; /** * The [uri](#Uri) of the resource representing this item. * * Will be used to derive the [label](#TreeItem.label), when it is not provided. * Will be used to derive the icon from current icon theme, when [iconPath](#TreeItem.iconPath) has [ThemeIcon](#ThemeIcon) value. */ resourceUri?: Uri; /** * The tooltip text when you hover over this item. */ tooltip?: string | undefined; /** * The [command](#Command) that should be executed when the tree item is selected. */ command?: Command; /** * [TreeItemCollapsibleState](#TreeItemCollapsibleState) of the tree item. */ collapsibleState?: TreeItemCollapsibleState; /** * Context value of the tree item. This can be used to contribute item specific actions in the tree. * For example, a tree item is given a context value as `folder`. When contributing actions to `view/item/context` * using `menus` extension point, you can specify context value for key `viewItem` in `when` expression like `viewItem == folder`. * ``` * "contributes": { * "menus": { * "view/item/context": [ * { * "command": "extension.deleteFolder", * "when": "viewItem == folder" * } * ] * } * } * ``` * This will show action `extension.deleteFolder` only for items with `contextValue` is `folder`. */ contextValue?: string; /** * Accessibility information used when screen reader interacts with this tree item. * Generally, a TreeItem has no need to set the `role` of the accessibilityInformation; * however, there are cases where a TreeItem is not displayed in a tree-like way where setting the `role` may make sense. */ accessibilityInformation?: AccessibilityInformation; /** * @param label A human-readable string describing this item * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} */ constructor(label: string | TreeItemLabel, collapsibleState?: TreeItemCollapsibleState); /** * @param resourceUri The {@link Uri} of the resource representing this item. * @param collapsibleState {@link TreeItemCollapsibleState} of the tree item. Default is {@link TreeItemCollapsibleState.None} */ constructor(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState); } /** * Represents a line of text, such as a line of source code. * * TextLine objects are __immutable__. When a [document](#TextDocument) changes, * previously retrieved lines will not represent the latest state. */ export interface TextLine { /** * The zero-based line number. */ readonly lineNumber: number; /** * The text of this line without the line separator characters. */ readonly text: string; /** * The range this line covers without the line separator characters. */ readonly range: Range; /** * The range this line covers with the line separator characters. */ readonly rangeIncludingLineBreak: Range; /** * The offset of the first character which is not a whitespace character as defined * by `/\s/`. **Note** that if a line is all whitespace the length of the line is returned. */ readonly firstNonWhitespaceCharacterIndex: number; /** * Whether this line is whitespace only, shorthand * for [TextLine.firstNonWhitespaceCharacterIndex](#TextLine.firstNonWhitespaceCharacterIndex) === [TextLine.text.length](#TextLine.text). */ readonly isEmptyOrWhitespace: boolean; } /** * Represents a text document, such as a source file. Text documents have * [lines](#TextLine) and knowledge about an underlying resource like a file. */ export interface TextDocument { /** * The associated uri for this document. * * *Note* that most documents use the `file`-scheme, which means they are files on disk. However, **not** all documents are * saved on disk and therefore the `scheme` must be checked before trying to access the underlying file or siblings on disk. * * @see [FileSystemProvider](#FileSystemProvider) * @see [TextDocumentContentProvider](#TextDocumentContentProvider) */ readonly uri: Uri; /** * The file system path of the associated resource. Shorthand * notation for [TextDocument.uri.fsPath](#TextDocument.uri). Independent of the uri scheme. */ readonly fileName: string; /** * Is this document representing an untitled file which has never been saved yet. *Note* that * this does not mean the document will be saved to disk, use [`uri.scheme`](#Uri.scheme) * to figure out where a document will be [saved](#FileSystemProvider), e.g. `file`, `ftp` etc. */ readonly isUntitled: boolean; /** * The identifier of the language associated with this document. */ readonly languageId: string; /** * The version number of this document (it will strictly increase after each * change, including undo/redo). */ readonly version: number; /** * `true` if there are unpersisted changes. */ readonly isDirty: boolean; /** * `true` if the document have been closed. A closed document isn't synchronized anymore * and won't be re-used when the same resource is opened again. */ readonly isClosed: boolean; /** * Save the underlying file. * * @return A promise that will resolve to true when the file * has been saved. If the file was not dirty or the save failed, * will return false. */ save(): Thenable<boolean>; /** * The [end of line](#EndOfLine) sequence that is predominately * used in this document. */ readonly eol: EndOfLine; /** * The number of lines in this document. */ readonly lineCount: number; /** * Returns a text line denoted by the line number. Note * that the returned object is *not* live and changes to the * document are not reflected. * * @param line A line number in [0, lineCount). * @return A [line](#TextLine). */ /* tslint:disable-next-line */ lineAt(line: number): TextLine; /** * Returns a text line denoted by the position. Note * that the returned object is *not* live and changes to the * document are not reflected. * * The position will be [adjusted](#TextDocument.validatePosition). * * @see [TextDocument.lineAt](#TextDocument.lineAt) * @param position A position. * @return A [line](#TextLine). */ /* tslint:disable-next-line */ lineAt(position: Position): TextLine; /** * Converts the position to a zero-based offset. * * The position will be [adjusted](#TextDocument.validatePosition). * * @param position A position. * @return A valid zero-based offset. */ offsetAt(position: Position): number; /** * Converts a zero-based offset to a position. * * @param offset A zero-based offset. * @return A valid [position](#Position). */ positionAt(offset: number): Position; /** * Get the text of this document. A substring can be retrieved by providing * a range. The range will be [adjusted](#TextDocument.validateRange). * * @param range Include only the text included by the range. * @return The text inside the provided range or the entire text. */ getText(range?: Range): string; /** * Get a word-range at the given position. By default words are defined by * common separators, like space, -, _, etc. In addition, per language custom * [word definitions](#LanguageConfiguration.wordPattern) can be defined. It * is also possible to provide a custom regular expression. * * * *Note 1:* A custom regular expression must not match the empty string and * if it does, it will be ignored. * * *Note 2:* A custom regular expression will fail to match multiline strings * and in the name of speed regular expressions should not match words with * spaces. Use [`TextLine.text`](#TextLine.text) for more complex, non-wordy, scenarios. * * The position will be [adjusted](#TextDocument.validatePosition). * * @param position A position. * @param regex Optional regular expression that describes what a word is. * @return A range spanning a word, or `undefined`. */ getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined; /** * Ensure a range is completely contained in this document. * * @param range A range. * @return The given range or a new, adjusted range. */ validateRange(range: Range): Range; /** * Ensure a position is contained in the range of this document. * * @param position A position. * @return The given position or a new, adjusted position. */ validatePosition(position: Position): Position; } /** * Represents a text selection in an editor. */ export class Selection extends Range { /** * The position at which the selection starts. * This position might be before or after [active](#Selection.active). */ anchor: Position; /** * The position of the cursor. * This position might be before or after [anchor](#Selection.anchor). */ active: Position; /** * Create a selection from two positions. * * @param anchor A position. * @param active A position. */ constructor(anchor: Position, active: Position); /** * Create a selection from four coordinates. * * @param anchorLine A zero-based line value. * @param anchorCharacter A zero-based character value. * @param activeLine A zero-based line value. * @param activeCharacter A zero-based character value. */ constructor(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number); /** * A selection is reversed if [active](#Selection.active).isBefore([anchor](#Selection.anchor)). */ isReversed: boolean; } /** * A complex edit that will be applied in one transaction on a TextEditor. * This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, document was not changed in the meantime, etc.) * they can be applied on a [document](#TextDocument) associated with a [text editor](#TextEditor). * */ /** * A universal resource identifier representing either a file on disk * or another resource, like untitled resources. */ export class Uri { /** * Create an URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * *Note* that for a while uris without a `scheme` were accepted. That is not correct * as all uris should have a scheme. To avoid breakage of existing code the optional * `strict`-argument has been added. We *strongly* advise to use it, e.g. `Uri.parse('my:uri', true)` * * @see [Uri.toString](#Uri.toString) * @param value The string value of an Uri. * @param strict Throw an error when `value` is empty or when no `scheme` can be parsed. * @return A new Uri instance. */ static parse(value: string, strict?: boolean): Uri; /** * Create an URI from a file system path. The [scheme](#Uri.scheme) * will be `file`. * * The *difference* between `Uri#parse` and `Uri#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `Uri.file(path)` is *not* the same as * `Uri.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system or UNC path. * @return A new Uri instance. */ static file(path: string): Uri; /** * Create a new uri which path is the result of joining * the path of the base uri with the provided path segments. * * - Note 1: `joinPath` only affects the path component * and all other components (scheme, authority, query, and fragment) are * left as they are. * - Note 2: The base uri must have a path; an error is thrown otherwise. * * The path segments are normalized in the following ways: * - sequences of path separators (`/` or `\`) are replaced with a single separator * - for `file`-uris on windows, the backslash-character (`\`) is considered a path-separator * - the `..`-segment denotes the parent segment, the `.` denotes the current segment * - paths have a root which always remains, for instance on windows drive-letters are roots * so that is true: `joinPath(Uri.file('file:///c:/root'), '../../other').fsPath === 'c:/other'` * * @param base An uri. Must have a path. * @param pathSegments One more more path fragments * @returns A new uri which path is joined with the given fragments */ static joinPath(base: Uri, ...pathSegments: string[]): Uri; /** * Use the `file` and `parse` factory functions to create new `Uri` objects. */ private constructor(scheme: string, authority: string, path: string, query: string, fragment: string); /** * Scheme is the `http` part of `http://www.msft.com/some/path?query#fragment`. * The part before the first colon. */ readonly scheme: string; /** * Authority is the `www.msft.com` part of `http://www.msft.com/some/path?query#fragment`. * The part between the first double slashes and the next slash. */ readonly authority: string; /** * Path is the `/some/path` part of `http://www.msft.com/some/path?query#fragment`. */ readonly path: string; /** * Query is the `query` part of `http://www.msft.com/some/path?query#fragment`. */ readonly query: string; /** * Fragment is the `fragment` part of `http://www.msft.com/some/path?query#fragment`. */ readonly fragment: string; /** * The string representing the corresponding file system path of this Uri. * * Will handle UNC paths and normalize windows drive letters to lower-case. Also * uses the platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this Uri. * * The resulting string shall *not* be used for display purposes but * for disk operations, like `readFile` et al. * * The *difference* to the [`path`](#Uri.path)-property is the use of the platform specific * path separator and the handling of UNC paths. The sample below outlines the difference: * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` */ readonly fsPath: string; /** * Derive a new Uri from this Uri. * * ```ts * let file = Uri.parse('before:some/file/path'); * let other = file.with({ scheme: 'after' }); * assert.ok(other.toString() === 'after:some/file/path'); * ``` * * @param change An object that describes a change to this Uri. To unset components use `null` or * the empty string. * @return A new Uri that reflects the given change. Will return `this` Uri if the change * is not changing anything. */ with(change: { scheme?: string; authority?: string; path?: string; query?: string; fragment?: string }): Uri; /** * Returns a string representation of this Uri. The representation and normalization * of a URI depends on the scheme. * * * The resulting string can be safely used with [Uri.parse](#Uri.parse). * * The resulting string shall *not* be used for display purposes. * * *Note* that the implementation will encode _aggressive_ which often leads to unexpected, * but not incorrect, results. For instance, colons are encoded to `%3A` which might be unexpected * in file-uri. Also `&` and `=` will be encoded which might be unexpected for http-uris. For stability * reasons this cannot be changed anymore. If you suffer from too aggressive encoding you should use * the `skipEncoding`-argument: `uri.toString(true)`. * * @param skipEncoding Do not percentage-encode the result, defaults to `false`. Note that * the `#` and `?` characters occurring in the path will always be encoded. * @returns A string representation of this Uri. */ toString(skipEncoding?: boolean): string; /** * Returns a JSON representation of this Uri. * * @return An object. */ toJSON(): any; } /** * Represents a typed event. * * A function that represents an event to which you subscribe by calling it with * a listener function as argument. * * @sample `item.onDidChange(function(event) { console.log("Event happened: " + event); });` */ export interface Event<T> { /** * A function that represents an event to which you subscribe by calling it with * a listener function as argument. * * @param listener The listener function will be called when the event happens. * @param thisArgs The `this`-argument which will be used when calling the event listener. * @param disposables An array to which a [disposable](#Disposable) will be added. * @return A disposable which unsubscribes the event listener. */ /* tslint:disable-next-line */ (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable; } /** * An event emitter can be used to create and manage an [event](#Event) for others * to subscribe to. One emitter always owns one event. * * Use this class if you want to provide event from within your extension, for instance * inside a [TextDocumentContentProvider](#TextDocumentContentProvider) or when providing * API to other extensions. */ export class EventEmitter<T> { /** * The event listeners can subscribe to. */ event: Event<T>; /** * Notify all subscribers of the [event](#EventEmitter.event). Failure * of one or more listener will not fail this function call. * * @param data The event object. */ fire(data?: T): void; /** * Dispose this object and free resources. */ dispose(): void; } /** * A cancellation token is passed to an asynchronous or long running * operation to request cancellation, like cancelling a request * for completion items because the user continued to type. * * To get an instance of a `CancellationToken` use a * [CancellationTokenSource](#CancellationTokenSource). */ export interface CancellationToken { /** * Is `true` when the token has been cancelled, `false` otherwise. */ isCancellationRequested: boolean; /** * An [event](#Event) which fires upon cancellation. */ onCancellationRequested: Event<any>; } /** * A cancellation source creates and controls a [cancellation token](#CancellationToken). */ export class CancellationTokenSource { /** * The cancellation token of this source. */ token: CancellationToken; /** * Signal cancellation on the token. */ cancel(): void; /** * Dispose object and free resources. */ dispose(): void; } export enum TextDocumentChangeReason { /** The text change is caused by an undo operation. */ Undo = 1, /** The text change is caused by an redo operation. */ Redo = 2, } /** * An event describing a transactional [document](#TextDocument) change. */ export interface TextDocumentChangeEvent { /** * The affected document. */ readonly document: TextDocument; /** * An array of content changes. */ readonly contentChanges: ReadonlyArray<TextDocumentContentChangeEvent>; /** * The reason why the document was changed. * Is `undefined` if the reason is not known. */ readonly reason: TextDocumentChangeReason | undefined; } /** * Represents a related message and source code location for a diagnostic. This should be * used to point to code locations that cause or related to a diagnostics, e.g. when duplicating * a symbol in a scope. */ export class DiagnosticRelatedInformation { /** * The location of this related diagnostic information. */ location: Location; /** * The message of this related diagnostic information. */ message: string; /** * Creates a new related diagnostic information object. * * @param location The location. * @param message The message. */ constructor(location: Location, message: string); } /** * Additional metadata about the type of a diagnostic. */ export enum DiagnosticTag { /** * Unused or unnecessary code. * * Diagnostics with this tag are rendered faded out. The amount of fading * is controlled by the `"editorUnnecessaryCode.opacity"` theme color. For * example, `"editorUnnecessaryCode.opacity": "#000000c0"` will render the * code with 75% opacity. For high contrast themes, use the * `"editorUnnecessaryCode.border"` theme color to underline unnecessary code * instead of fading it out. */ Unnecessary = 1, Deprecated = 2, } /** * Represents the severity of diagnostics. */ export enum DiagnosticSeverity { /** * Something not allowed by the rules of a language or other means. */ Error = 0, /** * Something suspicious but allowed. */ Warning = 1, /** * Something to inform about but not a problem. */ Information = 2, /** * Something to hint to a better way of doing it, like proposing * a refactoring. */ Hint = 3, } /** * Represents a diagnostic, such as a compiler error or warning. Diagnostic objects * are only valid in the scope of a file. */ export class Diagnostic { /** * The range to which this diagnostic applies. */ range: Range; /** * The human-readable message. */ message: string; /** * The severity, default is [error](#DiagnosticSeverity.Error). */ severity: DiagnosticSeverity; /** * A human-readable string describing the source of this * diagnostic, e.g. 'typescript' or 'super lint'. */ source?: string; /** * A code or identifier for this diagnostic. * Should be used for later processing, e.g. when providing [code actions](#CodeActionContext). */ code?: string | number; /** * An array of related diagnostic information, e.g. when symbol-names within * a scope collide all definitions can be marked via this property. */ relatedInformation?: DiagnosticRelatedInformation[]; /** * Additional metadata about the diagnostic. */ tags?: DiagnosticTag[]; /** * Creates a new diagnostic object. * * @param range The range to which this diagnostic applies. * @param message The human-readable message. * @param severity The severity, default is [error](#DiagnosticSeverity.Error). */ constructor(range: Range, message: string, severity?: DiagnosticSeverity); } /** * An error type that should be used to signal cancellation of an operation. * * This type can be used in response to a [cancellation token](#CancellationToken) * being cancelled or when an operation is being cancelled by the * executor of that operation. */ export class CancellationError extends Error { /** * Creates a new cancellation error. */ constructor(); } /** * Represents a type which can release resources, such * as event listening or a timer. */ export class Disposable { /** * Combine many disposable-likes into one. Use this method * when having objects with a dispose function which are not * instances of Disposable. * * @param disposableLikes Objects that have at least a `dispose`-function member. * @return Returns a new disposable which, upon dispose, will * dispose all provided disposables. */ static from(...disposableLikes: { dispose: () => any }[]): Disposable; /** * Creates a new Disposable calling the provided function * on dispose. * @param callOnDispose Function that disposes something. */ constructor(callOnDispose: () => void); /** * Dispose this object. */ dispose(): any; } /** * Represents an extension. * * To get an instance of an `Extension` use [getExtension](#extensions.getExtension). */ export interface Extension<T> { /** * The canonical extension identifier in the form of: `publisher.name`. */ readonly id: string; /** * The uri of the directory containing the extension. */ readonly extensionUri: Uri; /** * The absolute file path of the directory containing this extension. */ readonly extensionPath: string; /** * `true` if the extension has been activated. */ readonly isActive: boolean; /** * The parsed contents of the extension's package.json. */ readonly packageJSON: any; /** * The extension kind describes if an extension runs where the UI runs * or if an extension runs where the remote extension host runs. The extension kind * if defined in the `package.json` file of extensions but can also be refined * via the the `remote.extensionKind`-setting. When no remote extension host exists, * the value is [`ExtensionKind.UI`](#ExtensionKind.UI). */ extensionKind: ExtensionKind; /** * The public API exported by this extension. It is an invalid action * to access this field before this extension has been activated. */ readonly exports: T; /** * Activates this extension and returns its public API. * * @return A promise that will resolve when this extension has been activated. */ activate(): Thenable<T>; } /** * A memento represents a storage utility. It can store and retrieve * values. */ export interface Memento { /** * Return a value. * * @param key A string. * @return The stored value or `undefined`. */ get<T>(key: string): T | undefined; /** * Return a value. * * @param key A string. * @param defaultValue A value that should be returned when there is no * value (`undefined`) with the given key. * @return The stored value or the defaultValue. */ get<T>(key: string, defaultValue: T): T; /** * Store a value. The value must be JSON-stringifyable. * * @param key A string. * @param value A value. MUST not contain cyclic references. */ update(key: string, value: any): Thenable<void>; /** * VS Code proposal API, maybe remove on latest version. * #region https://github.com/microsoft/vscode/issues/87110 * The stored keys. */ readonly keys: readonly string[]; } /** * The event data that is fired when a secret is added or removed. */ export interface SecretStorageChangeEvent { /** * The key of the secret that has changed. */ readonly key: string; } /** * Represents a storage utility for secrets, information that is * sensitive. */ export interface SecretStorage { /** * Retrieve a secret that was stored with key. Returns undefined if there * is no password matching that key. * @param key The key the secret was stored under. * @returns The stored value or `undefined`. */ get(key: string): Thenable<string | undefined>; /** * Store a secret under a given key. * @param key The key to store the secret under. * @param value The secret. */ store(key: string, value: string): Thenable<void>; /** * Remove a secret from storage. * @param key The key the secret was stored under. */ delete(key: string): Thenable<void>; /** * Fires when a secret is stored or deleted. */ onDidChange: Event<SecretStorageChangeEvent>; } /** * Represents how a terminal exited. */ export interface TerminalExitStatus { /** * The exit code that a terminal exited with, it can have the following values: * - Zero: the terminal process or custom execution succeeded. * - Non-zero: the terminal process or custom execution failed. * - `undefined`: the user forcibly closed the terminal or a custom execution exited * without providing an exit code. */ readonly code: number | undefined; } export interface Terminal { /** * The name of the terminal. */ readonly name: string; /** * The process ID of the shell process. */ readonly processId: Thenable<number>; /** * The object used to initialize the terminal, this is useful for example to detecting the * shell type of when the terminal was not launched by this extension or for detecting what * folder the shell was launched in. */ readonly creationOptions: Readonly<TerminalOptions | ExtensionTerminalOptions>; /** * The exit status of the terminal, this will be undefined while the terminal is active. * * **Example:** Show a notification with the exit code when the terminal exits with a * non-zero exit code. * ```typescript * window.onDidCloseTerminal(t => { * if (t.exitStatus && t.exitStatus.code) { * vscode.window.showInformationMessage(`Exit code: ${t.exitStatus.code}`); * } * }); * ``` */ readonly exitStatus: TerminalExitStatus | undefined; /** * Send text to the terminal. The text is written to the stdin of the underlying pty process * (shell) of the terminal. * * @param text The text to send. * @param addNewLine Whether to add a new line to the text being sent, this is normally * required to run a command in the terminal. The character(s) added are \n or \r\n * depending on the platform. This defaults to `true`. */ sendText(text: string, addNewLine?: boolean): void; /** * Show the terminal panel and reveal this terminal in the UI. * * @param preserveFocus When `true` the terminal will not take focus. */ show(preserveFocus?: boolean): void; /** * Hide the terminal panel if this terminal is currently showing. */ hide(): void; /** * Dispose and free associated resources. */ dispose(): void; } /** * Represents the state of a {@link Terminal}. */ export interface TerminalState { /** * Whether the {@link Terminal} has been interacted with. Interaction means that the * terminal has sent data to the process which depending on the terminal's _mode_. By * default input is sent when a key is pressed or when a command or extension sends text, * but based on the terminal's mode it can also happen on: * * - a pointer click event * - a pointer scroll event * - a pointer move event * - terminal focus in/out * * For more information on events that can send data see "DEC Private Mode Set (DECSET)" on * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html */ readonly isInteractedWith: boolean; } //#region EnvironmentVariable /** * A type of mutation that can be applied to an environment variable. */ export enum EnvironmentVariableMutatorType { /** * Replace the variable's existing value. */ Replace = 1, /** * Append to the end of the variable's existing value. */ Append = 2, /** * Prepend to the start of the variable's existing value. */ Prepend = 3, } /** * A type of mutation and its value to be applied to an environment variable. */ export interface EnvironmentVariableMutator { /** * The type of mutation that will occur to the variable. */ readonly type: EnvironmentVariableMutatorType; /** * The value to use for the variable. */ readonly value: string; } /** * A collection of mutations that an extension can apply to a process environment. */ export interface EnvironmentVariableCollection { /** * Whether the collection should be cached for the workspace and applied to the terminal * across window reloads. When true the collection will be active immediately such when the * window reloads. Additionally, this API will return the cached version if it exists. The * collection will be invalidated when the extension is uninstalled or when the collection * is cleared. Defaults to true. */ persistent: boolean; /** * Replace an environment variable with a value. * * Note that an extension can only make a single change to any one variable, so this will * overwrite any previous calls to replace, append or prepend. * * @param variable The variable to replace. * @param value The value to replace the variable with. */ replace(variable: string, value: string): void; /** * Append a value to an environment variable. * * Note that an extension can only make a single change to any one variable, so this will * overwrite any previous calls to replace, append or prepend. * * @param variable The variable to append to. * @param value The value to append to the variable. */ append(variable: string, value: string): void; /** * Prepend a value to an environment variable. * * Note that an extension can only make a single change to any one variable, so this will * overwrite any previous calls to replace, append or prepend. * * @param variable The variable to prepend. * @param value The value to prepend to the variable. */ prepend(variable: string, value: string): void; /** * Gets the mutator that this collection applies to a variable, if any. * * @param variable The variable to get the mutator for. */ get(variable: string): EnvironmentVariableMutator | undefined; /** * Iterate over each mutator in this collection. * * @param callback Function to execute for each entry. * @param thisArg The `this` context used when invoking the handler function. */ forEach(callback: (variable: string, mutator: EnvironmentVariableMutator, collection: EnvironmentVariableCollection) => any, thisArg?: any): void; /** * Deletes this collection's mutator for a variable. * * @param variable The variable to delete the mutator for. */ delete(variable: string): void; /** * Clears all mutators from this collection. */ clear(): void; } //#endregion /** * An extension context is a collection of utilities private to an * extension. * * An instance of an `ExtensionContext` is provided as the first * parameter to the `activate`-call of an extension. */ export interface ExtensionContext { /** * An array to which disposables can be added. When this * extension is deactivated the disposables will be disposed. */ readonly subscriptions: { dispose(): any }[]; /** * A memento object that stores state in the context * of the currently opened [workspace](#workspace.workspaceFolders). */ readonly workspaceState: Memento; /** * A memento object that stores state independent * of the current opened [workspace](#workspace.workspaceFolders). */ readonly globalState: Memento & { /** * Set the keys whose values should be synchronized across devices when synchronizing user-data * like configuration, extensions, and mementos. * * Note that this function defines the whole set of keys whose values are synchronized: * - calling it with an empty array stops synchronization for this memento * - calling it with a non-empty array replaces all keys whose values are synchronized * * For any given set of keys this function needs to be called only once but there is no harm in * repeatedly calling it. * * @param keys The set of keys whose values are synced. */ setKeysForSync(keys: string[]): void; }; /** * The absolute file path of the directory containing the extension. */ readonly extensionPath: string; /** * A storage utility for secrets. Secrets are persisted across reloads and are independent of the * current opened {@link workspace.workspaceFolders workspace}. */ readonly secrets: SecretStorage; /** * The uri of the directory containing the extension. */ readonly extensionUri: Uri; /** * Gets the extension's environment variable collection for this workspace, enabling changes * to be applied to terminal environment variables. */ readonly environmentVariableCollection: EnvironmentVariableCollection; /** * Get the absolute path of a resource contained in the extension. * * @param relativePath A relative path to a resource contained in the extension. * @return The absolute path of the resource. */ asAbsolutePath(relativePath: string): string; /** * An absolute file path of a workspace specific directory in which the extension * can store private state. The directory might not exist on disk and creation is * up to the extension. However, the parent directory is guaranteed to be existent. * * Use [`workspaceState`](#ExtensionContext.workspaceState) or * [`globalState`](#ExtensionContext.globalState) to store key value data. * * @deprecated Use [storagePath](#ExtensionContent.storageUri) instead. */ readonly storagePath: string | undefined; /** * The uri of a workspace specific directory in which the extension * can store private state. The directory might not exist and creation is * up to the extension. However, the parent directory is guaranteed to be existent. * The value is `undefined` when no workspace nor folder has been opened. * * Use [`workspaceState`](#ExtensionContext.workspaceState) or * [`globalState`](#ExtensionContext.globalState) to store key value data. * * @see [`workspace.fs`](#FileSystem) for how to read and write files and folders from * an uri. */ readonly storageUri: Uri | undefined; /** * An absolute file path in which the extension can store global state. * The directory might not exist on disk and creation is * up to the extension. However, the parent directory is guaranteed to be existent. * * Use [`globalState`](#ExtensionContext.globalState) to store key value data. * * @deprecated Use [globalStoragePath](#ExtensionContent.globalStorageUri) instead. */ readonly globalStoragePath: string; /** * The uri of a directory in which the extension can store global state. * The directory might not exist on disk and creation is * up to the extension. However, the parent directory is guaranteed to be existent. * * Use [`globalState`](#ExtensionContext.globalState) to store key value data. * * @see [`workspace.fs`](#FileSystem) for how to read and write files and folders from * an uri. */ readonly globalStorageUri: Uri; /** * An absolute file path of a directory in which the extension can create log files. * The directory might not exist on disk and creation is up to the extension. However, * the parent directory is guaranteed to be existent. * * @deprecated Use [logUri](#ExtensionContext.logUri) instead. */ readonly logPath: string; /** * The uri of a directory in which the extension can create log files. * The directory might not exist on disk and creation is up to the extension. However, * the parent directory is guaranteed to be existent. * * @see [`workspace.fs`](#FileSystem) for how to read and write files and folders from * an uri. */ readonly logUri: Uri; /** * The mode the extension is running in. This is specific to the current * extension. One extension may be in `ExtensionMode.Development` while * other extensions in the host run in `ExtensionMode.Release`. */ readonly extensionMode: ExtensionMode; /** * The current `Extension` instance. */ readonly extension: Extension<any>; } /** * The ExtensionMode is provided on the `ExtensionContext` and indicates the * mode the specific extension is running in. */ export enum ExtensionMode { /** * The extension is installed normally (for example, from the marketplace * or VSIX) in VS Code. */ Production = 1, /** * The extension is running from an `--extensionDevelopmentPath` provided * when launching VS Code. */ Development = 2, /** * The extension is running from an `--extensionTestsPath` and * the extension host is running unit tests. */ Test = 3, } /** * A file system watcher notifies about changes to files and folders * on disk. * * To get an instance of a `FileSystemWatcher` use * [createFileSystemWatcher](#workspace.createFileSystemWatcher). */ export interface FileSystemWatcher extends Disposable { /** * true if this file system watcher has been created such that * it ignores creation file system events. */ ignoreCreateEvents: boolean; /** * true if this file system watcher has been created such that * it ignores change file system events. */ ignoreChangeEvents: boolean; /** * true if this file system watcher has been created such that * it ignores delete file system events. */ ignoreDeleteEvents: boolean; /** * An event which fires on file/folder creation. */ onDidCreate: Event<Uri>; /** * An event which fires on file/folder change. */ onDidChange: Event<Uri>; /** * An event which fires on file/folder deletion. */ onDidDelete: Event<Uri>; } /** * Enumeration of file types. The types `File` and `Directory` can also be * a symbolic links, in that use `FileType.File | FileType.SymbolicLink` and * `FileType.Directory | FileType.SymbolicLink`. */ export enum FileType { /** * The file type is unknown. */ Unknown = 0, /** * A regular file. */ File = 1, /** * A directory. */ Directory = 2, /** * A symbolic link to a file. */ SymbolicLink = 64, } //#region FileSystemProvider stat readonly - https://github.com/microsoft/vscode/issues/73122 export enum FilePermission { /** * The file is readonly. * * *Note:* All `FileStat` from a `FileSystemProvider` that is registered with * the option `isReadonly: true` will be implicitly handled as if `FilePermission.Readonly` * is set. As a consequence, it is not possible to have a readonly file system provider * registered where some `FileStat` are not readonly. */ Readonly = 1 } /** * The `FileStat`-type represents metadata about a file */ export interface FileStat { /** * The type of the file, e.g. is a regular file, a directory, or symbolic link * to a file. */ type: FileType; /** * The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ ctime: number; /** * The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC. */ mtime: number; /** * The size in bytes. */ size: number; /** * The permissions of the file, e.g. whether the file is readonly. * * *Note:* This value might be a bitmask, e.g. `FilePermission.Readonly | FilePermission.Other`. */ permissions?: FilePermission; } /** * A type that filesystem providers should use to signal errors. * * This class has factory methods for common error-cases, like `FileNotFound` when * a file or folder doesn't exist, use them like so: `throw vscode.FileSystemError.FileNotFound(someUri);` */ export class FileSystemError extends Error { /** * Create an error to signal that a file or folder wasn't found. * @param messageOrUri Message or uri. */ static FileNotFound(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file or folder already exists, e.g. when * creating but not overwriting a file. * @param messageOrUri Message or uri. */ static FileExists(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file is not a folder. * @param messageOrUri Message or uri. */ static FileNotADirectory(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that a file is a folder. * @param messageOrUri Message or uri. */ static FileIsADirectory(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that an operation lacks required permissions. * @param messageOrUri Message or uri. */ static NoPermissions(messageOrUri?: string | Uri): FileSystemError; /** * Create an error to signal that the file system is unavailable or too busy to * complete a request. * @param messageOrUri Message or uri. */ static Unavailable(messageOrUri?: string | Uri): FileSystemError; /** * Creates a new filesystem error. * * @param messageOrUri Message or uri. */ constructor(messageOrUri?: string | Uri); /** * A code that identifies this error. * * Possible values are names of errors, like [`FileNotFound`](#FileSystemError.FileNotFound), * or `Unknown` for unspecified errors. */ readonly code: string; } /** * Enumeration of file change types. */ export enum FileChangeType { /** * The contents or metadata of a file have changed. */ Changed = 1, /** * A file has been created. */ Created = 2, /** * A file has been deleted. */ Deleted = 3, } /** * The event filesystem providers must use to signal a file change. */ export interface FileChangeEvent { /** * The type of change. */ readonly type: FileChangeType; /** * The uri of the file that has changed. */ readonly uri: Uri; } /** * The filesystem provider defines what the editor needs to read, write, discover, * and to manage files and folders. It allows extensions to serve files from remote places, * like ftp-servers, and to seamlessly integrate those into the editor. * * * *Note 1:* The filesystem provider API works with [uris](#Uri) and assumes hierarchical * paths, e.g. `foo:/my/path` is a child of `foo:/my/` and a parent of `foo:/my/path/deeper`. * * *Note 2:* There is an activation event `onFileSystem:<scheme>` that fires when a file * or folder is being accessed. * * *Note 3:* The word 'file' is often used to denote all [kinds](#FileType) of files, e.g. * folders, symbolic links, and regular files. */ export interface FileSystemProvider { /** * An event to signal that a resource has been created, changed, or deleted. This * event should fire for resources that are being [watched](#FileSystemProvider.watch) * by clients of this provider. */ readonly onDidChangeFile: Event<FileChangeEvent[]>; /** * Subscribe to events in the file or folder denoted by `uri`. * * The editor will call this function for files and folders. In the latter case, the * options differ from defaults, e.g. what files/folders to exclude from watching * and if subfolders, sub-subfolder, etc. should be watched (`recursive`). * * @param uri The uri of the file to be watched. * @param options Configures the watch. * @returns A disposable that tells the provider to stop watching the `uri`. */ watch(uri: Uri, options: { recursive: boolean; excludes: string[] }): Disposable; /** * Retrieve metadata about a file. * * Note that the metadata for symbolic links should be the metadata of the file they refer to. * Still, the [SymbolicLink](#FileType.SymbolicLink)-type must be used in addition to the actual type, e.g. * `FileType.SymbolicLink | FileType.Directory`. * * @param uri The uri of the file to retrieve metadata about. * @return The file metadata about the file. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ stat(uri: Uri): FileStat | Thenable<FileStat>; /** * Retrieve all entries of a [directory](#FileType.Directory). * * @param uri The uri of the folder. * @return An array of name/type-tuples or a thenable that resolves to such. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ readDirectory(uri: Uri): [string, FileType][] | Thenable<[string, FileType][]>; /** * Create a new directory (Note, that new files are created via `write`-calls). * * @param uri The uri of the new folder. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ createDirectory(uri: Uri): void | Thenable<void>; /** * Read the entire contents of a file. * * @param uri The uri of the file. * @return An array of bytes or a thenable that resolves to such. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. */ readFile(uri: Uri): Uint8Array | Thenable<Uint8Array>; /** * Write data to a file, replacing its entire contents. * * @param uri The uri of the file. * @param content The new content of the file. * @param options Defines if missing files should or must be created. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist and `create` is not set. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist and `create` is set, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists, `create` is set but `overwrite` is not set. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ writeFile(uri: Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }): void | Thenable<void>; /** * Delete a file. * * @param uri The resource that is to be deleted. * @param options Defines if deletion of folders is recursive. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ delete(uri: Uri, options: { recursive: boolean }): void | Thenable<void>; /** * Rename a file or folder. * * @param oldUri The existing file. * @param newUri The new location. * @param options Defines if existing files should be overwritten. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `oldUri` doesn't exist. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `newUri` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `newUri` exists and when the `overwrite` option is not `true`. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ rename(oldUri: Uri, newUri: Uri, options: { overwrite: boolean }): void | Thenable<void>; /** * Copy files or folders. Implementing this function is optional but it will speedup * the copy operation. * * @param source The existing file. * @param destination The destination location. * @param options Defines if existing files should be overwritten. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `source` doesn't exist. * @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `destination` doesn't exist, e.g. no mkdirp-logic required. * @throws [`FileExists`](#FileSystemError.FileExists) when `destination` exists and when the `overwrite` option is not `true`. * @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient. */ copy?(source: Uri, destination: Uri, options: { overwrite: boolean }): void | Thenable<void>; } export interface FileSystem { stat(uri: Uri): Thenable<FileStat>; readDirectory(uri: Uri): Thenable<[string, FileType][]>; createDirectory(uri: Uri): Thenable<void>; readFile(uri: Uri): Thenable<Uint8Array>; writeFile(uri: Uri, content: Uint8Array, options?: { create: boolean, overwrite: boolean }): Thenable<void>; delete(uri: Uri, options?: { recursive: boolean }): Thenable<void>; rename(source: Uri, target: Uri, options?: { overwrite: boolean }): Thenable<void>; copy(source: Uri, target: Uri, options?: { overwrite: boolean }): Thenable<void>; isWritableFileSystem(scheme: string): boolean | undefined; } /** * Represents the configuration. It is a merged view of * * - Default configuration * - Global configuration * - Workspace configuration (if available) * - Workspace folder configuration of the requested resource (if available) * * *Global configuration* comes from User Settings and shadows Defaults. * * *Workspace configuration* comes from Workspace Settings and shadows Global configuration. * * *Workspace Folder configuration* comes from `.vscode` folder under one of the [workspace folders](#workspace.workspaceFolders). * * *Note:* Workspace and Workspace Folder configurations contains `launch` and `tasks` settings. Their basename will be * part of the section identifier. The following snippets shows how to retrieve all configurations * from `launch.json`: * * ```ts * // launch.json configuration * const config = workspace.getConfiguration('launch', vscode.window.activeTextEditor.document.uri); * * // retrieve values * const values = config.get('configurations'); * ``` * * Refer to [Settings](https://code.visualstudio.com/docs/getstarted/settings) for more information. */ /** * An output channel is a container for readonly textual information. * * To get an instance of an `OutputChannel` use * [createOutputChannel](#window.createOutputChannel). */ /** * Defines a generalized way of reporting progress updates. */ export interface Progress<T> { /** * Report a progress update. * @param value A progress item, like a message and/or an * report on how much work finished */ report(value: T): void; } /** * A location in the editor at which progress information can be shown. It depends on the * location how progress is visually represented. */ export enum ProgressLocation { /** * Show progress for the source control viewlet, as overlay for the icon and as progress bar * inside the viewlet (when visible). Neither supports cancellation nor discrete progress. */ SourceControl = 1, /** * Show progress in the status bar of the editor. Neither supports cancellation nor discrete progress. */ Window = 10, /** * Show progress as notification with an optional cancel button. Supports to show infinite and discrete progress. */ Notification = 15, } /** * Value-object describing where and how progress should show. */ export interface ProgressOptions { /** * The location at which progress should show. */ location: ProgressLocation; /** * A human-readable string which will be used to describe the * operation. */ title?: string; /** * Controls if a cancel button should show to allow the user to * cancel the long running operation. Note that currently only * `ProgressLocation.Notification` is supporting to show a cancel * button. */ cancellable?: boolean; } /** * Possible kinds of UI that can use extensions. */ export enum UIKind { /** * Extensions are accessed from a desktop application. */ Desktop = 1, /** * Extensions are accessed from a web browser. */ Web = 2, } //#region Semantic Tokens /** * A semantic tokens legend contains the needed information to decipher * the integer encoded representation of semantic tokens. */ export class SemanticTokensLegend { /** * The possible token types. */ public readonly tokenTypes: string[]; /** * The possible token modifiers. */ public readonly tokenModifiers: string[]; constructor(tokenTypes: string[], tokenModifiers?: string[]); } /** * A semantic tokens builder can help with creating a `SemanticTokens` instance * which contains delta encoded semantic tokens. */ export class SemanticTokensBuilder { constructor(legend?: SemanticTokensLegend); /** * Add another token. * * @param line The token start line number (absolute value). * @param char The token start character (absolute value). * @param length The token length in characters. * @param tokenType The encoded token type. * @param tokenModifiers The encoded token modifiers. */ push(line: number, char: number, length: number, tokenType: number, tokenModifiers?: number): void; /** * Add another token. Use only when providing a legend. * * @param range The range of the token. Must be single-line. * @param tokenType The token type. * @param tokenModifiers The token modifiers. */ push(range: Range, tokenType: string, tokenModifiers?: string[]): void; /** * Finish and create a `SemanticTokens` instance. */ build(resultId?: string): SemanticTokens; } /** * Represents semantic tokens, either in a range or in an entire document. * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens) for an explanation of the format. * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to create an instance. */ export class SemanticTokens { /** * The result id of the tokens. * * This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented). */ readonly resultId?: string; /** * The actual tokens data. * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens) for an explanation of the format. */ readonly data: Uint32Array; constructor(data: Uint32Array, resultId?: string); } /** * Represents edits to semantic tokens. * @see [provideDocumentSemanticTokensEdits](#DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits) for an explanation of the format. */ export class SemanticTokensEdits { /** * The result id of the tokens. * * This is the id that will be passed to `DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits` (if implemented). */ readonly resultId?: string; /** * The edits to the tokens data. * All edits refer to the initial data state. */ readonly edits: SemanticTokensEdit[]; constructor(edits: SemanticTokensEdit[], resultId?: string); } /** * Represents an edit to semantic tokens. * @see [provideDocumentSemanticTokensEdits](#DocumentSemanticTokensProvider.provideDocumentSemanticTokensEdits) for an explanation of the format. */ export class SemanticTokensEdit { /** * The start offset of the edit. */ readonly start: number; /** * The count of elements to remove. */ readonly deleteCount: number; /** * The elements to insert. */ readonly data?: Uint32Array; constructor(start: number, deleteCount: number, data?: Uint32Array); } /** * The document semantic tokens provider interface defines the contract between extensions and * semantic tokens. */ export interface DocumentSemanticTokensProvider { /** * An optional event to signal that the semantic tokens from this provider have changed. */ onDidChangeSemanticTokens?: Event<void>; /** * Tokens in a file are represented as an array of integers. The position of each token is expressed relative to * the token before it, because most tokens remain stable relative to each other when edits are made in a file. * * --- * In short, each token takes 5 integers to represent, so a specific token `i` in the file consists of the following array indices: * - at index `5*i` - `deltaLine`: token line number, relative to the previous token * - at index `5*i+1` - `deltaStart`: token start character, relative to the previous token (relative to 0 or the previous token's start if they are on the same line) * - at index `5*i+2` - `length`: the length of the token. A token cannot be multiline. * - at index `5*i+3` - `tokenType`: will be looked up in `SemanticTokensLegend.tokenTypes`. We currently ask that `tokenType` < 65536. * - at index `5*i+4` - `tokenModifiers`: each set bit will be looked up in `SemanticTokensLegend.tokenModifiers` * * --- * ### How to encode tokens * * Here is an example for encoding a file with 3 tokens in a uint32 array: * ``` * { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] }, * { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] }, * { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] } * ``` * * 1. First of all, a legend must be devised. This legend must be provided up-front and capture all possible token types. * For this example, we will choose the following legend which must be passed in when registering the provider: * ``` * tokenTypes: ['property', 'type', 'class'], * tokenModifiers: ['private', 'static'] * ``` * * 2. The first transformation step is to encode `tokenType` and `tokenModifiers` as integers using the legend. Token types are looked * up by index, so a `tokenType` value of `1` means `tokenTypes[1]`. Multiple token modifiers can be set by using bit flags, * so a `tokenModifier` value of `3` is first viewed as binary `0b00000011`, which means `[tokenModifiers[0], tokenModifiers[1]]` because * bits 0 and 1 are set. Using this legend, the tokens now are: * ``` * { line: 2, startChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, * { line: 2, startChar: 10, length: 4, tokenType: 1, tokenModifiers: 0 }, * { line: 5, startChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } * ``` * * 3. The next step is to represent each token relative to the previous token in the file. In this case, the second token * is on the same line as the first token, so the `startChar` of the second token is made relative to the `startChar` * of the first token, so it will be `10 - 5`. The third token is on a different line than the second token, so the * `startChar` of the third token will not be altered: * ``` * { deltaLine: 2, deltaStartChar: 5, length: 3, tokenType: 0, tokenModifiers: 3 }, * { deltaLine: 0, deltaStartChar: 5, length: 4, tokenType: 1, tokenModifiers: 0 }, * { deltaLine: 3, deltaStartChar: 2, length: 7, tokenType: 2, tokenModifiers: 0 } * ``` * * 4. Finally, the last step is to inline each of the 5 fields for a token in a single array, which is a memory friendly representation: * ``` * // 1st token, 2nd token, 3rd token * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] * ``` * * @see [SemanticTokensBuilder](#SemanticTokensBuilder) for a helper to encode tokens as integers. * *NOTE*: When doing edits, it is possible that multiple edits occur until VS Code decides to invoke the semantic tokens provider. * *NOTE*: If the provider cannot temporarily compute semantic tokens, it can indicate this by throwing an error with the message 'Busy'. */ provideDocumentSemanticTokens(document: TextDocument, token: CancellationToken): ProviderResult<SemanticTokens>; /** * Instead of always returning all the tokens in a file, it is possible for a `DocumentSemanticTokensProvider` to implement * this method (`provideDocumentSemanticTokensEdits`) and then return incremental updates to the previously provided semantic tokens. * * --- * ### How tokens change when the document changes * * Suppose that `provideDocumentSemanticTokens` has previously returned the following semantic tokens: * ``` * // 1st token, 2nd token, 3rd token * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] * ``` * * Also suppose that after some edits, the new semantic tokens in a file are: * ``` * // 1st token, 2nd token, 3rd token * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] * ``` * It is possible to express these new tokens in terms of an edit applied to the previous tokens: * ``` * [ 2,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // old tokens * [ 3,5,3,0,3, 0,5,4,1,0, 3,2,7,2,0 ] // new tokens * * edit: { start: 0, deleteCount: 1, data: [3] } // replace integer at offset 0 with 3 * ``` * * *NOTE*: If the provider cannot compute `SemanticTokensEdits`, it can "give up" and return all the tokens in the document again. * *NOTE*: All edits in `SemanticTokensEdits` contain indices in the old integers array, so they all refer to the previous result state. */ provideDocumentSemanticTokensEdits?(document: TextDocument, previousResultId: string, token: CancellationToken): ProviderResult<SemanticTokens | SemanticTokensEdits>; } /** * The document range semantic tokens provider interface defines the contract between extensions and * semantic tokens. */ export interface DocumentRangeSemanticTokensProvider { /** * @see [provideDocumentSemanticTokens](#DocumentSemanticTokensProvider.provideDocumentSemanticTokens). */ provideDocumentRangeSemanticTokens(document: TextDocument, range: Range, token: CancellationToken): ProviderResult<SemanticTokens>; } //#endregion Semantic Tokens /** * The configuration scope which can be a * a 'resource' or a languageId or both or * a '[TextDocument](#TextDocument)' or * a '[WorkspaceFolder](#WorkspaceFolder)' */ export type ConfigurationScope = Uri | TextDocument | WorkspaceFolder | { uri?: Uri, languageId: string }; //#region EvaluatableExpression /** * An EvaluatableExpression represents an expression in a document that can be evaluated by an active debugger or runtime. * The result of this evaluation is shown in a tooltip-like widget. * If only a range is specified, the expression will be extracted from the underlying document. * An optional expression can be used to override the extracted expression. * In this case the range is still used to highlight the range in the document. */ export class EvaluatableExpression { /* * The range is used to extract the evaluatable expression from the underlying document and to highlight it. */ readonly range: Range; /* * If specified the expression overrides the extracted expression. */ readonly expression?: string; /** * Creates a new evaluatable expression object. * * @param range The range in the underlying document from which the evaluatable expression is extracted. * @param expression If specified overrides the extracted expression. */ constructor(range: Range, expression?: string); } /** * The evaluatable expression provider interface defines the contract between extensions and * the debug hover. In this contract the provider returns an evaluatable expression for a given position * in a document and VS Code evaluates this expression in the active debug session and shows the result in a debug hover. */ export interface EvaluatableExpressionProvider { /** * Provide an evaluatable expression for the given document and position. * VS Code will evaluate this expression in the active debug session and will show the result in the debug hover. * The expression can be implicitly specified by the range in the underlying document or by explicitly returning an expression. * * @param document The document for which the debug hover is about to appear. * @param position The line and character position in the document where the debug hover is about to appear. * @param token A cancellation token. * @return An EvaluatableExpression or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideEvaluatableExpression(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<EvaluatableExpression>; } //#endregion //#region Inline Values /** * Provide inline value as text. */ export class InlineValueText { /** * The document range for which the inline value applies. */ readonly range: Range; /** * The text of the inline value. */ readonly text: string; /** * Creates a new InlineValueText object. * * @param range The document line where to show the inline value. * @param text The value to be shown for the line. */ constructor(range: Range, text: string); } /** * Provide inline value through a variable lookup. * If only a range is specified, the variable name will be extracted from the underlying document. * An optional variable name can be used to override the extracted name. */ export class InlineValueVariableLookup { /** * The document range for which the inline value applies. * The range is used to extract the variable name from the underlying document. */ readonly range: Range; /** * If specified the name of the variable to look up. */ readonly variableName?: string; /** * How to perform the lookup. */ readonly caseSensitiveLookup: boolean; /** * Creates a new InlineValueVariableLookup object. * * @param range The document line where to show the inline value. * @param variableName The name of the variable to look up. * @param caseSensitiveLookup How to perform the lookup. If missing lookup is case sensitive. */ constructor(range: Range, variableName?: string, caseSensitiveLookup?: boolean); } /** * Provide an inline value through an expression evaluation. * If only a range is specified, the expression will be extracted from the underlying document. * An optional expression can be used to override the extracted expression. */ export class InlineValueEvaluatableExpression { /** * The document range for which the inline value applies. * The range is used to extract the evaluatable expression from the underlying document. */ readonly range: Range; /** * If specified the expression overrides the extracted expression. */ readonly expression?: string; /** * Creates a new InlineValueEvaluatableExpression object. * * @param range The range in the underlying document from which the evaluatable expression is extracted. * @param expression If specified overrides the extracted expression. */ constructor(range: Range, expression?: string); } /** * Inline value information can be provided by different means: * - directly as a text value (class InlineValueText). * - as a name to use for a variable lookup (class InlineValueVariableLookup) * - as an evaluatable expression (class InlineValueEvaluatableExpression) * The InlineValue types combines all inline value types into one type. */ export type InlineValue = InlineValueText | InlineValueVariableLookup | InlineValueEvaluatableExpression; /** * A value-object that contains contextual information when requesting inline values from a InlineValuesProvider. */ export interface InlineValueContext { /** * The stack frame (as a DAP Id) where the execution has stopped. */ readonly frameId: number; /** * The document range where execution has stopped. * Typically the end position of the range denotes the line where the inline values are shown. */ readonly stoppedLocation: Range; } /** * The inline values provider interface defines the contract between extensions and the VS Code debugger inline values feature. * In this contract the provider returns inline value information for a given document range * and VS Code shows this information in the editor at the end of lines. */ export interface InlineValuesProvider { /** * An optional event to signal that inline values have changed. * @see [EventEmitter](#EventEmitter) */ onDidChangeInlineValues?: Event<void> | undefined; /** * Provide "inline value" information for a given document and range. * VS Code calls this method whenever debugging stops in the given document. * The returned inline values information is rendered in the editor at the end of lines. * * @param document The document for which the inline values information is needed. * @param viewPort The visible document range for which inline values should be computed. * @param context A bag containing contextual information like the current location. * @param token A cancellation token. * @return An array of InlineValueDescriptors or a thenable that resolves to such. The lack of a result can be * signaled by returning `undefined` or `null`. */ provideInlineValues(document: TextDocument, viewPort: Range, context: InlineValueContext, token: CancellationToken): ProviderResult<InlineValue[]>; } //#endregion Inline Values } /** * Thenable is a common denominator between ES6 promises, Q, jquery.Deferred, WinJS.Promise, * and others. This API makes no assumption about what promise library is being used which * enables reusing existing code without migrating to a specific promise implementation. Still, * we recommend the use of native promises which are available in this editor. */ interface Thenable<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<TResult>(onfulfilled?: (value: T) => TResult | Thenable<TResult>, onrejected?: (reason: any) => TResult | Thenable<TResult>): Thenable<TResult>; /* tslint:disable-next-line */ then<TResult>(onfulfilled?: (value: T) => TResult | Thenable<TResult>, onrejected?: (reason: any) => void): Thenable<TResult>; }
the_stack
import { defineComponent, ref, PropType, computed } from 'vue'; import { TimeFilledIcon, CheckCircleFilledIcon, ErrorCircleFilledIcon, DeleteIcon, BrowseIcon, } from 'tdesign-icons-vue-next'; import TButton from '../button'; import TLoading from '../loading'; import { UploadFile } from './type'; import { FlowRemoveContext } from './interface'; import props from './props'; import { returnFileSize, abridgeName } from './util'; import { useTNodeJSX } from '../hooks/tnode'; import { useFormDisabled } from '../form/hooks'; import { useConfig, usePrefixClass, useCommonClassName } from '../hooks/useConfig'; export default defineComponent({ name: 'TUploadFlowList', props: { showUploadProgress: props.showUploadProgress, placeholder: props.placeholder, autoUpload: props.autoUpload, disabled: props.disabled, theme: props.theme, batchUpload: props.isBatchUpload, // 已上传完成的文件 files: props.files, // 上传队列中的文件(可能存在已经上传过的文件) toUploadFiles: Array as PropType<Array<UploadFile>>, onRemove: Function as PropType<(ctx: FlowRemoveContext) => void>, onUpload: Function as PropType<(files: Array<UploadFile>, e: MouseEvent) => void>, onCancel: Function as PropType<(e: MouseEvent) => void>, onChange: Function as PropType<(files: FileList) => void>, onDragleave: Function as PropType<(e: DragEvent) => void>, onDragenter: Function as PropType<(e: DragEvent) => void>, onImgPreview: Function as PropType<(options: MouseEvent, file: UploadFile) => void>, }, setup(props) { const target = ref(null); const dragActive = ref(false); const renderTNodeJSX = useTNodeJSX(); const disabled = useFormDisabled(); const { classPrefix: prefix, global } = useConfig('upload'); const UPLOAD_NAME = usePrefixClass('upload'); const { SIZE } = useCommonClassName(); const waitingUploadFiles = computed(() => { const list: Array<UploadFile> = []; props.toUploadFiles.forEach((item: UploadFile) => { const r = props.files.filter((t: UploadFile) => t.name === item.name); if (!r.length) { list.push(item); } }); return list; }); const showInitial = computed(() => { const isWaitingEmpty = !waitingUploadFiles.value || !waitingUploadFiles.value.length; return (!props.files || !props.files.length) && isWaitingEmpty; }); const listFiles = computed(() => { if (!props.files || !props.files.length) return props.toUploadFiles; return props.files.concat(waitingUploadFiles.value); }); const failedList = computed(() => { return props.toUploadFiles.filter((file: UploadFile) => file.status === 'fail'); }); const processList = computed(() => props.toUploadFiles.filter((file: UploadFile) => file.status === 'progress')); const isUploading = computed(() => !!processList.value.length); const allowUpload = computed( () => Boolean(waitingUploadFiles.value && waitingUploadFiles.value.length) && !isUploading.value, ); const uploadText = computed(() => { if (isUploading.value) return `${global.value.progress.uploadingText}...`; return failedList.value && failedList.value.length ? global.value.triggerUploadText.reupload : global.value.triggerUploadText.normal; }); const handleDrop = (event: DragEvent) => { event.preventDefault(); props.onChange(event.dataTransfer.files); props.onDragleave(event); dragActive.value = false; }; const handleDragenter = (event: DragEvent) => { target.value = event.target; event.preventDefault(); props.onDragenter(event); dragActive.value = true; }; const handleDragleave = (event: DragEvent) => { if (target.value !== event.target) return; event.preventDefault(); props.onDragleave(event); dragActive.value = false; }; const handleDragover = (event: DragEvent) => { event.preventDefault(); }; const renderDragger = () => { return ( <div class={`${UPLOAD_NAME.value}__flow-empty`} onDrop={handleDrop} onDragenter={handleDragenter} onDragover={handleDragover} onDragleave={handleDragleave} > {dragActive.value ? global.value.dragger.dragDropText : global.value.dragger.clickAndDragText} </div> ); }; const getStatusMap = (file: UploadFile) => { const iconMap = { success: <CheckCircleFilledIcon />, fail: <ErrorCircleFilledIcon />, progress: <TLoading />, waiting: <TimeFilledIcon />, }; const textMap = { success: global.value.progress.successText, fail: global.value.progress.failText, progress: `${global.value.progress.uploadingText} ${Math.min(file.percent, 99)}%`, waiting: global.value.progress.waitingText, }; return { iconMap, textMap, }; }; const renderStatus = (file: UploadFile) => { if (!props.showUploadProgress) return; const { iconMap, textMap } = getStatusMap(file); return ( <div class={`${UPLOAD_NAME.value}__flow-status`}> {iconMap[file.status]} <span>{textMap[file.status]}</span> </div> ); }; const renderNormalActionCol = (file: UploadFile, index: number) => { return ( <td> <span class={`${UPLOAD_NAME.value}__flow-button`} onClick={(e: MouseEvent) => props.onRemove({ e, index, file })} > {global.value.triggerUploadText.delete} </span> </td> ); }; // batchUpload action col const renderBatchActionCol = (index: number) => { // 第一行数据才需要合并单元格 return index === 0 ? ( <td rowspan={listFiles.value.length} class={`${UPLOAD_NAME.value}__flow-table__batch-row`}> <span class={`${UPLOAD_NAME.value}__flow-button`} onClick={(e: MouseEvent) => props.onRemove({ e, index: -1, file: null })} > {global.value.triggerUploadText.delete} </span> </td> ) : ( '' ); }; const renderFileList = () => props.theme === 'file-flow' && ( <table class={`${UPLOAD_NAME.value}__flow-table`}> <tr> <th>{global.value.file.fileNameText}</th> <th>{global.value.file.fileSizeText}</th> <th>{global.value.file.fileStatusText}</th> <th>{global.value.file.fileOperationText}</th> </tr> {showInitial.value && ( <tr> <td colspan={4}>{renderDragger()}</td> </tr> )} {listFiles.value.map((file, index) => { // 合并操作出现条件为:当前为合并上传模式且列表内没有待上传文件 const showBatchUploadAction = props.batchUpload && props.toUploadFiles.length === 0; return ( <tr> <td>{abridgeName(file.name, 7, 10)}</td> <td>{returnFileSize(file.size)}</td> <td>{renderStatus(file)}</td> {showBatchUploadAction ? renderBatchActionCol(index) : renderNormalActionCol(file, index)} </tr> ); })} </table> ); const renderImgItem = (file: UploadFile, index: number) => { const { iconMap, textMap } = getStatusMap(file); return ( <li class={`${UPLOAD_NAME.value}__card-item`}> <div class={[ `${UPLOAD_NAME.value}__card-content`, { [`${prefix.value}-is-bordered`]: file.status !== 'waiting' }, ]} > {['fail', 'progress'].includes(file.status) && ( <div class={`${UPLOAD_NAME.value}__card-status-wrap`}> {iconMap[file.status as 'fail' | 'progress']} <p>{textMap[file.status as 'fail' | 'progress']}</p> </div> )} {(['waiting', 'success'].includes(file.status) || (!file.status && file.url)) && ( <img class={`${UPLOAD_NAME.value}__card-image`} src={file.url || '//tdesign.gtimg.com/tdesign-default-img.png'} /> )} <div class={`${UPLOAD_NAME.value}__card-mask`}> {file.url && ( <span class={`${UPLOAD_NAME.value}__card-mask-item`}> <BrowseIcon onClick={({ e }: { e: MouseEvent }) => props.onImgPreview(e, file)} /> <span class={`${UPLOAD_NAME.value}__card-mask-item-divider`}></span> </span> )} {!disabled.value && ( <span class={`${UPLOAD_NAME.value}__card-mask-item`} onClick={(e: MouseEvent) => props.onRemove({ e, index, file })} > <DeleteIcon /> </span> )} </div> </div> <p class={`${UPLOAD_NAME.value}__card-name`}>{abridgeName(file.name)}</p> </li> ); }; const renderImgList = () => props.theme === 'image-flow' && ( <div class={`${UPLOAD_NAME.value}__flow-card-area`}> {showInitial.value && renderDragger()} {!!listFiles.value.length && ( <ul class={`${UPLOAD_NAME.value}__card clearfix`}> {listFiles.value.map((file, index) => renderImgItem(file, index))} </ul> )} </div> ); const renderFooter = () => !props.autoUpload && ( <div class={`${UPLOAD_NAME.value}__flow-bottom`}> <TButton theme="default" onClick={props.onCancel} disabled={!allowUpload.value}> {global.value.cancelUploadText} </TButton> <TButton disabled={!allowUpload.value} theme="primary" onClick={(e: MouseEvent) => props.onUpload(waitingUploadFiles.value, e)} > {uploadText.value} </TButton> </div> ); return () => ( <div class={[`${UPLOAD_NAME.value}__flow`, `${UPLOAD_NAME.value}__flow-${props.theme}`]}> <div class={`${UPLOAD_NAME.value}__flow-op`}> {renderTNodeJSX('default')} <small class={`${SIZE.value.small} ${UPLOAD_NAME.value}__flow-placeholder`}>{props.placeholder}</small> </div> {renderFileList()} {renderImgList()} {renderFooter()} </div> ); }, });
the_stack
'use strict' import { GraphcoolDefinition } from 'graphcool-json-schema' import { Output } from '../Output/index' import * as _ from 'lodash' import * as replaceall from 'replaceall' import * as BbPromise from 'bluebird' import { Args } from '../types/common' export default class Variables { json: any overwriteSyntax: RegExp = RegExp(/,/g) envRefSyntax: RegExp = RegExp(/^env:/g) selfRefSyntax: RegExp = RegExp(/^self:/g) stringRefSyntax: RegExp = RegExp(/('.*')|(".*")/g) optRefSyntax: RegExp = RegExp(/^opt:/g) variableSyntax: RegExp = RegExp( /* tslint:disable-next-line */ '\\${([ ~:a-zA-Z0-9._\'",\\-\\/\\(\\)]+?)}', 'g', ) out: Output fileName: string options: Args constructor(out: Output, fileName: string, options: Args = {}) { this.out = out this.fileName = fileName this.options = options // this.fileRefSyntax = RegExp(/^file\((~?[a-zA-Z0-9._\-/]+?)\)/g); // this.cfRefSyntax = RegExp(/^cf:/g); // this.s3RefSyntax = RegExp(/^s3:(.+?)\/(.+)$/); // this.ssmRefSyntax = RegExp(/^ssm:([a-zA-Z0-9_.-/]+)[~]?(true|false)?/); } populateJson(json: any): Promise<any> { this.json = json return this.populateObject(this.json).then(() => { return BbPromise.resolve(this.json) }) } public populateObject(objectToPopulate) { const populateAll: any[] = [] const deepMapValues = (object, callback, propertyPath?: string[]) => { const deepMapValuesIteratee = (value, key) => deepMapValues( value, callback, propertyPath ? propertyPath.concat(key) : [key], ) if (_.isArray(object)) { return _.map(object, deepMapValuesIteratee) } else if ( _.isObject(object) && !_.isDate(object) && !_.isRegExp(object) && !_.isFunction(object) ) { return _.extend({}, object, _.mapValues(object, deepMapValuesIteratee)) } return callback(object, propertyPath) } deepMapValues(objectToPopulate, (property, propertyPath) => { if (typeof property === 'string') { const populateSingleProperty = this.populateProperty(property, true) .then(newProperty => _.set(objectToPopulate, propertyPath, newProperty), ) .return() populateAll.push(populateSingleProperty) } }) return BbPromise.all(populateAll).then(() => objectToPopulate) } populateProperty(propertyParam, populateInPlace?: boolean) { let property = populateInPlace ? propertyParam : _.cloneDeep(propertyParam) const allValuesToPopulate: any[] = [] let warned = false if (typeof property === 'string' && property.match(this.variableSyntax)) { property.match(this.variableSyntax)!.forEach(matchedString => { const variableString = matchedString .replace(this.variableSyntax, (match, varName) => varName.trim()) .replace(/\s/g, '') let singleValueToPopulate: Promise<any> | null = null if (variableString.match(this.overwriteSyntax)) { singleValueToPopulate = this.overwrite(variableString) } else { singleValueToPopulate = this.getValueFromSource( variableString, ).then(valueToPopulate => { if (typeof valueToPopulate === 'object') { return this.populateObject(valueToPopulate) } return valueToPopulate }) } singleValueToPopulate = singleValueToPopulate!.then(valueToPopulate => { if (this.warnIfNotFound(variableString, valueToPopulate)) { warned = true } return this.populateVariable( property, matchedString, valueToPopulate, ).then(newProperty => { property = newProperty return BbPromise.resolve(property) }) }) allValuesToPopulate.push(singleValueToPopulate) }) return BbPromise.all(allValuesToPopulate).then(() => { if ((property as any) !== (this.json as any) && !warned) { return this.populateProperty(property) } return BbPromise.resolve(property) }) } // return property; return BbPromise.resolve(property) } populateVariable(propertyParam, matchedString, valueToPopulate) { let property = propertyParam if (typeof valueToPopulate === 'string') { property = replaceall(matchedString, valueToPopulate, property) } else { if (property !== matchedString) { if (typeof valueToPopulate === 'number') { property = replaceall( matchedString, String(valueToPopulate), property, ) } else { const errorMessage = [ 'Trying to populate non string value into', ` a string for variable ${matchedString}.`, ' Please make sure the value of the property is a string.', ].join('') this.out.warn( this.out.getErrorPrefix(this.fileName, 'warning') + errorMessage, ) } return BbPromise.resolve(property) } property = valueToPopulate } return BbPromise.resolve(property) } overwrite(variableStringsString) { let finalValue const variableStringsArray = variableStringsString.split(',') const allValuesFromSource = variableStringsArray.map(variableString => this.getValueFromSource(variableString), ) return BbPromise.all(allValuesFromSource).then(valuesFromSources => { valuesFromSources.find(valueFromSource => { finalValue = valueFromSource return ( finalValue !== null && typeof finalValue !== 'undefined' && !(typeof finalValue === 'object' && _.isEmpty(finalValue)) ) }) return BbPromise.resolve(finalValue) }) } getValueFromSource(variableString) { if (variableString.match(this.envRefSyntax)) { return this.getValueFromEnv(variableString) } else if (variableString.match(this.optRefSyntax)) { return this.getValueFromOptions(variableString) } else if (variableString.match(this.selfRefSyntax)) { return this.getValueFromSelf(variableString) // } else if (variableString.match(this.fileRefSyntax)) { // return this.getValueFromFile(variableString); // } else if (variableString.match(this.cfRefSyntax)) { // return this.getValueFromCf(variableString); // } else if (variableString.match(this.s3RefSyntax)) { // return this.getValueFromS3(variableString); } else if (variableString.match(this.stringRefSyntax)) { return this.getValueFromString(variableString) // } else if (variableString.match(this.ssmRefSyntax)) { // return this.getValueFromSsm(variableString); } const errorMessage = [ `Invalid variable reference syntax for variable ${variableString}.`, ' You can only reference env vars, options, & files.', ' You can check our docs for more info.', ].join('') this.out.warn( this.out.getErrorPrefix(this.fileName, 'warning') + errorMessage, ) } getValueFromEnv(variableString) { const requestedEnvVar = variableString.split(':')[1] const valueToPopulate = requestedEnvVar !== '' || '' in process.env ? process.env[requestedEnvVar] : process.env return BbPromise.resolve(valueToPopulate) } getValueFromString(variableString) { const valueToPopulate = variableString.replace(/^['"]|['"]$/g, '') return BbPromise.resolve(valueToPopulate) } getValueFromOptions(variableString) { const requestedOption = variableString.split(':')[1] const valueToPopulate = requestedOption !== '' || '' in this.options ? this.options[requestedOption] : this.options return BbPromise.resolve(valueToPopulate) } getValueFromSelf(variableString) { const valueToPopulate = this.json const deepProperties = variableString.split(':')[1].split('.') return this.getDeepValue(deepProperties, valueToPopulate) } // getValueFromFile(variableString) { // const matchedFileRefString = variableString.match(this.fileRefSyntax)[0]; // const referencedFileRelativePath = matchedFileRefString // .replace(this.fileRefSyntax, (match, varName) => varName.trim()) // .replace('~', os.homedir()); // // const referencedFileFullPath = (path.isAbsolute(referencedFileRelativePath) ? // referencedFileRelativePath : // path.join(this.graphcool.config.servicePath, referencedFileRelativePath)); // let fileExtension = referencedFileRelativePath.split('.'); // fileExtension = fileExtension[fileExtension.length - 1]; // // Validate file exists // if (!this.graphcool.utils.fileExistsSync(referencedFileFullPath)) { // return BbPromise.resolve(undefined); // } // // let valueToPopulate; // // // Process JS files // if (fileExtension === 'js') { // const jsFile = require(referencedFileFullPath); // eslint-disable-line global-require // const variableArray = variableString.split(':'); // let returnValueFunction; // if (variableArray[1]) { // let jsModule = variableArray[1]; // jsModule = jsModule.split('.')[0]; // returnValueFunction = jsFile[jsModule]; // } else { // returnValueFunction = jsFile; // } // // if (typeof returnValueFunction !== 'function') { // throw new this.graphcool.classes // .Error([ // 'Invalid variable syntax when referencing', // ` file "${referencedFileRelativePath}".`, // ' Check if your javascript is exporting a function that returns a value.', // ].join('')); // } // valueToPopulate = returnValueFunction.call(jsFile); // // return BbPromise.resolve(valueToPopulate).then(valueToPopulateResolved => { // let deepProperties = variableString.replace(matchedFileRefString, ''); // deepProperties = deepProperties.slice(1).split('.'); // deepProperties.splice(0, 1); // return this.getDeepValue(deepProperties, valueToPopulateResolved) // .then(deepValueToPopulateResolved => { // if (typeof deepValueToPopulateResolved === 'undefined') { // const errorMessage = [ // 'Invalid variable syntax when referencing', // ` file "${referencedFileRelativePath}".`, // ' Check if your javascript is returning the correct data.', // ].join(''); // throw new this.graphcool.classes // .Error(errorMessage); // } // return BbPromise.resolve(deepValueToPopulateResolved); // }); // }); // } // // // Process everything except JS // if (fileExtension !== 'js') { // valueToPopulate = this.graphcool.utils.readFileSync(referencedFileFullPath); // if (matchedFileRefString !== variableString) { // let deepProperties = variableString // .replace(matchedFileRefString, ''); // if (deepProperties.substring(0, 1) !== ':') { // const errorMessage = [ // 'Invalid variable syntax when referencing', // ` file "${referencedFileRelativePath}" sub properties`, // ' Please use ":" to reference sub properties.', // ].join(''); // throw new this.graphcool.classes // .Error(errorMessage); // } // deepProperties = deepProperties.slice(1).split('.'); // return this.getDeepValue(deepProperties, valueToPopulate); // } // } // return BbPromise.resolve(valueToPopulate); // } // // getValueFromCf(variableString) { // const variableStringWithoutSource = variableString.split(':')[1].split('.'); // const stackName = variableStringWithoutSource[0]; // const outputLogicalId = variableStringWithoutSource[1]; // return this.graphcool.getProvider('aws') // .request('CloudFormation', // 'describeStacks', // { StackName: stackName }, // this.options.stage, // this.options.region) // .then(result => { // const outputs = result.Stacks[0].Outputs; // const output = outputs.find(x => x.OutputKey === outputLogicalId); // // if (output === undefined) { // const errorMessage = [ // 'Trying to request a non exported variable from CloudFormation.', // ` Stack name: "${stackName}"`, // ` Requested variable: "${outputLogicalId}".`, // ].join(''); // throw new this.graphcool.classes // .Error(errorMessage); // } // // return output.OutputValue; // }); // } // // getValueFromS3(variableString) { // const groups = variableString.match(this.s3RefSyntax); // const bucket = groups[1]; // const key = groups[2]; // return this.graphcool.getProvider('aws') // .request('S3', // 'getObject', // { // Bucket: bucket, // Key: key, // }, // this.options.stage, // this.options.region) // .then( // response => response.Body.toString(), // err => { // const errorMessage = `Error getting value for ${variableString}. ${err.message}`; // throw new this.graphcool.classes.Error(errorMessage); // } // ); // } // // getValueFromSsm(variableString) { // const groups = variableString.match(this.ssmRefSyntax); // const param = groups[1]; // const decrypt = (groups[2] === 'true'); // return this.graphcool.getProvider('aws') // .request('SSM', // 'getParameter', // { // Name: param, // WithDecryption: decrypt, // }, // this.options.stage, // this.options.region) // .then( // response => BbPromise.resolve(response.Parameter.Value), // err => { // const expectedErrorMessage = `Parameter ${param} not found.`; // if (err.message !== expectedErrorMessage) { // throw new this.graphcool.classes.Error(err.message); // } // return BbPromise.resolve(undefined); // } // ); // } getDeepValue(deepProperties, valueToPopulate) { return BbPromise.reduce( deepProperties, (computedValueToPopulateParam, subProperty) => { let computedValueToPopulate = computedValueToPopulateParam if (typeof computedValueToPopulate === 'undefined') { computedValueToPopulate = {} } else if (subProperty !== '' || '' in computedValueToPopulate) { computedValueToPopulate = computedValueToPopulate[subProperty] } if ( typeof computedValueToPopulate === 'string' && computedValueToPopulate.match(this.variableSyntax) ) { return this.populateProperty(computedValueToPopulate) } return BbPromise.resolve(computedValueToPopulate) }, valueToPopulate, ) } warnIfNotFound(variableString, valueToPopulate): boolean { if ( valueToPopulate === null || typeof valueToPopulate === 'undefined' || (typeof valueToPopulate === 'object' && _.isEmpty(valueToPopulate)) ) { let varType if (variableString.match(this.envRefSyntax)) { varType = 'environment variable' } else if (variableString.match(this.optRefSyntax)) { varType = 'option' } else if (variableString.match(this.selfRefSyntax)) { varType = 'self reference' // } else if (variableString.match(this.fileRefSyntax)) { // varType = 'file'; // } else if (variableString.match(this.ssmRefSyntax)) { // varType = 'SSM parameter'; } this.out.warn( this.out.getErrorPrefix(this.fileName, 'warning') + `A valid ${varType} to satisfy the declaration '${variableString}' could not be found.`, ) return true } return false } }
the_stack
import { ABIParameter, ABIReturn, common, ContractEventDescriptorClient, ContractGroup, ContractPermission, ContractPermissionDescriptor, SenderAddressABIDefault, WildcardContainer, } from '@neo-one/client-common'; import { NEO_ONE_METHOD_RESERVED_PARAM } from '@neo-one/client-core'; import { ContractPermissionDescriptorModel } from '@neo-one/client-full-common'; import { tsUtils } from '@neo-one/ts-utils'; import { utils } from '@neo-one/utils'; import _ from 'lodash'; import ts from 'typescript'; import { DEFAULT_DIAGNOSTIC_OPTIONS, DiagnosticOptions } from '../analysis'; import { SmartContractInfoABI, SmartContractInfoManifest, SmartContractInfoMethodDescriptor, } from '../compile/getSmartContractInfo'; import { ContractProperties } from '../constants'; import { Context } from '../Context'; import { DiagnosticCode } from '../DiagnosticCode'; import { DiagnosticMessage } from '../DiagnosticMessage'; import { getSetterName, toABIReturn } from '../utils'; import { ContractInfo, DeployPropInfo } from './ContractInfoProcessor'; const BOOLEAN_RETURN: ABIReturn = { type: 'Boolean' }; const VOID_RETURN: ABIReturn = { type: 'Void' }; export class ManifestSmartContractProcessor { public constructor( private readonly context: Context, private readonly contractInfo: ContractInfo, private readonly properties: ContractProperties, ) {} public process(): SmartContractInfoManifest { return { groups: this.processGroups(), supportedStandards: this.processSupportedStandards(), abi: this.processABI(), permissions: this.processPermissions(), trusts: this.processTrusts(), }; } // TODO: document permissions, trusts, groups // "contract.Manifest" is the manifest of contract to be called = "ManifestCalled" // "currentManifest" is the manifest of the contract that is making the call = "CallingManifest" // "method" is the method being called // currentManifest.CanCall(contract.Manifest, method) // If any Permission.isAllowed(manifest, method) returns true // IsAllowed(manifest, method) // Now "manifest" is the manifest of the contract to be called // IsAllowed is for the Permission object in the manifest of the contract making the call // Permission.Contract = the contract to be invoked (a contract hash or a "group" which is a public key) // Permission.Methods = the methods to be called // If Permission.Contract is a hash, then check if Permission.Contract.Hash === ManifestCalled.Hash // in this case CanCall() will return true as long as the private processGroups(): readonly ContractGroup[] { return this.properties.groups; } private processPermissions(): readonly ContractPermission[] { return this.properties.permissions; } private processTrusts(): WildcardContainer<ContractPermissionDescriptor> { return common.isWildcard(this.properties.trusts) ? '*' : this.properties.trusts.map((trust) => new ContractPermissionDescriptorModel({ hashOrGroup: ContractPermissionDescriptorModel.hashOrGroupFromString(trust), }).serializeJSON(), ); } private processSupportedStandards(): readonly string[] { return [this.isNep17Contract() ? 'NEP-17' : undefined].filter(utils.notNull); } private isNep17Contract(): boolean { const propInfos = this.contractInfo.propInfos.filter((propInfo) => propInfo.isPublic && propInfo.type !== 'deploy'); const hasTransferEvent = this.processEvents().some((event) => event.name === 'Transfer'); const hasTotalSupply = propInfos.some( (info) => info.name === 'totalSupply' && ((info.type === 'function' && info.constant && info.isSafe) || (info.type === 'accessor' && info.getter?.constant && info.getter?.isSafe)), ); const hasBalanceOf = propInfos.some( (info) => info.type === 'function' && info.name === 'balanceOf' && info.constant && info.isSafe, ); const hasTransfer = propInfos.some( (info) => info.type === 'function' && info.name === 'transfer' && !info.constant && !info.isSafe, ); const hasDecimals = propInfos.some( (info) => info.type === 'property' && info.name === 'decimals' && info.isReadonly && info.isSafe, ); const hasSymbol = propInfos.some( (info) => info.type === 'property' && info.name === 'symbol' && info.isReadonly && info.isSafe, ); return hasTotalSupply && hasBalanceOf && hasTransfer && hasDecimals && hasSymbol && hasTransferEvent; } private processABI(): SmartContractInfoABI { return { // TODO: fix this later when changing how smart contracts are called methods: this.modifyProcessedFunctions(this.processFunctions()), events: this.processEvents(), }; } // TODO: remove this later when changing how smart contracts are called private modifyProcessedFunctions( methods: ReadonlyArray<SmartContractInfoMethodDescriptor>, ): ReadonlyArray<SmartContractInfoMethodDescriptor> { return methods.map((method) => method.parameters === undefined ? method : { ...method, parameters: this.addDefaultEntryParams(method.parameters) }, ); } // TODO: remove this later when changing how smart contracts are called private addDefaultEntryParams(params: readonly ABIParameter[]): readonly ABIParameter[] { return [ { type: 'String', name: NEO_ONE_METHOD_RESERVED_PARAM, }, ...params, ]; } // TODO: make sure this matches up with docs and with @safe decorator // These methods are automatically safe: // Marked with @safe or @constant // Properties that are readonly or @safe // Getters marked with @constant or @safe // Not the deploy method private processFunctions(): ReadonlyArray<SmartContractInfoMethodDescriptor> { const deployInfo = this.findDeployInfo(); const propInfos = this.contractInfo.propInfos .filter((propInfo) => propInfo.isPublic && propInfo.type !== 'deploy') .concat([deployInfo].filter(utils.notNull)); return _.flatten<SmartContractInfoMethodDescriptor>( propInfos.map((propInfo): ReadonlyArray<SmartContractInfoMethodDescriptor> => { switch (propInfo.type) { case 'deploy': return [ { name: propInfo.name, parameters: propInfo.isMixinDeploy ? [] : this.getParameters({ callSignature: propInfo.callSignature }), returnType: BOOLEAN_RETURN, safe: propInfo.isSafe, }, ]; case 'upgrade': return [ { name: propInfo.name, parameters: [ { name: 'script', type: 'Buffer' }, { name: 'manifest', type: 'Buffer' }, ], returnType: VOID_RETURN, safe: propInfo.isSafe, }, ]; case 'function': return [ { name: propInfo.name, parameters: this.getParameters({ callSignature: propInfo.callSignature, }), returnType: this.toABIReturn(propInfo.decl, propInfo.returnType), constant: propInfo.constant, safe: propInfo.isSafe, }, ]; case 'property': return [ { name: propInfo.name, parameters: [], returnType: this.toABIReturn(propInfo.decl, propInfo.propertyType), constant: true, safe: propInfo.isSafe, }, propInfo.isReadonly ? undefined : { name: getSetterName(propInfo.name), parameters: [ this.toABIParameter(propInfo.name, propInfo.decl, propInfo.propertyType, false, { error: false, }), ].filter(utils.notNull), returnType: VOID_RETURN, safe: propInfo.isSafe, }, ].filter(utils.notNull); case 'accessor': return [ propInfo.getter === undefined ? undefined : { name: propInfo.getter.name, parameters: [], constant: propInfo.getter.constant, returnType: this.toABIReturn(propInfo.getter.decl, propInfo.propertyType), safe: propInfo.getter.isSafe, }, propInfo.setter === undefined ? undefined : { name: propInfo.setter.name, parameters: [ this.toABIParameter( propInfo.name, propInfo.getter === undefined ? propInfo.setter.decl : propInfo.getter.decl, propInfo.propertyType, false, propInfo.getter === undefined ? { error: true } : undefined, ), ].filter(utils.notNull), returnType: VOID_RETURN, safe: propInfo.setter.isSafe, }, ].filter(utils.notNull); default: utils.assertNever(propInfo); throw new Error('For TS'); } }), ); } private findDeployInfo(contractInfo: ContractInfo = this.contractInfo): DeployPropInfo | undefined { const deployInfo = contractInfo.propInfos.find( (propInfo): propInfo is DeployPropInfo => propInfo.type === 'deploy', ); const superSmartContract = contractInfo.superSmartContract; if (deployInfo !== undefined) { if (deployInfo.decl === undefined && superSmartContract !== undefined) { const superDeployInfo = this.findDeployInfo(superSmartContract); return superDeployInfo === undefined ? deployInfo : superDeployInfo; } return deployInfo; } return superSmartContract === undefined ? undefined : this.findDeployInfo(superSmartContract); } private getParameters({ callSignature, }: { readonly callSignature: ts.Signature | undefined; readonly send?: boolean; }): ReadonlyArray<ABIParameter> { if (callSignature === undefined) { return []; } const parameters = callSignature.getParameters(); return parameters.map((parameter) => this.paramToABIParameter(parameter)).filter(utils.notNull); } private processEvents(): ReadonlyArray<ContractEventDescriptorClient> { const createEventNotifierDecl = tsUtils.symbol.getDeclarations( this.context.builtins.getValueSymbol('createEventNotifier'), )[0]; const declareEventDecl = tsUtils.symbol.getDeclarations(this.context.builtins.getValueSymbol('declareEvent'))[0]; const calls = this.context.analysis .findReferencesAsNodes(createEventNotifierDecl) .concat(this.context.analysis.findReferencesAsNodes(declareEventDecl)) .map((node) => { if (ts.isIdentifier(node)) { const parent = tsUtils.node.getParent(node); if (ts.isCallExpression(parent)) { return parent; } } return undefined; }) .filter(utils.notNull); return calls.reduce<ReadonlyArray<ContractEventDescriptorClient>>((events, call) => { const event = this.toContractEventDescriptorClient(call, events); return event === undefined ? events : [...events, event]; }, []); } private toContractEventDescriptorClient( call: ts.CallExpression, events: ReadonlyArray<ContractEventDescriptorClient>, ): ContractEventDescriptorClient | undefined { const callArguments = tsUtils.argumented.getArguments(call); const parent = tsUtils.node.getParent(call); let typeArguments = tsUtils.argumented .getTypeArgumentsArray(call) .map((typeNode) => this.context.analysis.getType(typeNode)); if (ts.isPropertyDeclaration(parent)) { const propertyName = tsUtils.node.getName(parent); const smartContractType = this.context.analysis.getType(this.contractInfo.smartContract); if (smartContractType !== undefined) { const member = tsUtils.type_.getProperty(smartContractType, propertyName); if (member !== undefined) { const type = this.context.analysis.getTypeOfSymbol(member, this.contractInfo.smartContract); const signatureTypes = this.context.analysis.extractSignatureForType(call, type); if (signatureTypes !== undefined) { typeArguments = signatureTypes.paramDecls.map((paramDecl) => signatureTypes.paramTypes.get(paramDecl)); } } } } const nameArg = callArguments[0] as ts.Node | undefined; if (nameArg === undefined) { return undefined; } if (!ts.isStringLiteral(nameArg)) { this.context.reportError( nameArg, DiagnosticCode.InvalidContractEvent, DiagnosticMessage.InvalidContractEventNameStringLiteral, ); return undefined; } const name = tsUtils.literal.getLiteralValue(nameArg); const parameters = _.zip(callArguments.slice(1), typeArguments) .map(([paramNameArg, paramType]) => { if (paramNameArg === undefined || paramType === undefined) { return undefined; } if (!ts.isStringLiteral(paramNameArg)) { this.context.reportError( paramNameArg, DiagnosticCode.InvalidContractEvent, DiagnosticMessage.InvalidContractEventArgStringLiteral, ); return undefined; } const paramName = tsUtils.literal.getLiteralValue(paramNameArg); const param = this.toABIParameter(paramName, paramNameArg, paramType); if (param !== undefined && param.type === 'ForwardValue') { this.context.reportError( paramNameArg, DiagnosticCode.InvalidContractType, DiagnosticMessage.InvalidContractType, ); return undefined; } return param; }) .filter(utils.notNull); const event = { name, parameters }; const dupeEvent = events.find((otherEvent) => otherEvent.name === event.name && !_.isEqual(event, otherEvent)); if (dupeEvent === undefined) { return event; } this.context.reportError( nameArg, DiagnosticCode.InvalidContractEvent, DiagnosticMessage.InvalidContractEventDuplicate, ); return undefined; } private paramToABIParameter(param: ts.Symbol): ABIParameter | undefined { const decls = tsUtils.symbol.getDeclarations(param); const decl = utils.nullthrows(decls[0]); const initializer = tsUtils.initializer.getInitializer(decl); const parameter = this.toABIParameter( tsUtils.symbol.getName(param), decl, this.getParamSymbolType(param), initializer !== undefined, ); if ( parameter === undefined || initializer === undefined || (!ts.isPropertyAccessExpression(initializer) && !ts.isCallExpression(initializer)) ) { return parameter; } if (ts.isPropertyAccessExpression(initializer)) { const symbol = this.context.analysis.getSymbol(initializer); const senderAddress = this.context.builtins.getOnlyMemberSymbol('DeployConstructor', 'senderAddress'); if (symbol === senderAddress) { const sender: SenderAddressABIDefault = { type: 'sender' }; return { ...parameter, default: sender }; } } return parameter; } private checkLastParam(parameters: ReadonlyArray<ts.Symbol>, value: string): boolean { return this.checkLastParamBase(parameters, (decl, type) => this.context.builtins.isInterface(decl, type, value)); } private checkLastParamBase( parameters: ReadonlyArray<ts.Symbol>, checkParamType: (decl: ts.Node, type: ts.Type) => boolean, ): boolean { if (parameters.length === 0) { return false; } const lastParam = parameters[parameters.length - 1]; const lastParamType = this.getParamSymbolType(lastParam); return lastParamType !== undefined && checkParamType(tsUtils.symbol.getDeclarations(lastParam)[0], lastParamType); } private getParamSymbolType(param: ts.Symbol): ts.Type | undefined { const decls = tsUtils.symbol.getDeclarations(param); const decl = utils.nullthrows(decls[0]); return this.context.analysis.getTypeOfSymbol(param, decl); } private toABIParameter( nameIn: string, node: ts.Node, resolvedTypeIn: ts.Type | undefined, optional = false, options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS, ): ABIParameter | undefined { const name = nameIn.startsWith('_') ? nameIn.slice(1) : nameIn; let resolvedType = resolvedTypeIn; if (ts.isParameter(node) && tsUtils.parameter.isRestParameter(node) && resolvedType !== undefined) { resolvedType = tsUtils.type_.getTypeArgumentsArray(resolvedType)[0]; } const type = toABIReturn(this.context, node, resolvedType, optional, options); if (type === undefined) { return undefined; } if (ts.isParameter(node) && tsUtils.parameter.isRestParameter(node)) { return { ...type, name, rest: true }; } return { ...type, name }; } private toABIReturn( node: ts.Node, resolvedType: ts.Type | undefined, optional = false, options: DiagnosticOptions = DEFAULT_DIAGNOSTIC_OPTIONS, ): ABIReturn { const type = toABIReturn(this.context, node, resolvedType, optional, options); return type === undefined ? VOID_RETURN : type; } }
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ActivatedRoute } from '@angular/router'; import { IIncome, ComponentLayoutStyleEnum, IOrganization, IEmployee, IOrganizationContact, ITag, IEmployeeProposalTemplate } from '@gauzy/contracts'; import { Subject } from 'rxjs'; import { combineLatest } from 'rxjs'; import { distinctUntilChange } from '@gauzy/common-angular'; import { NbDialogService } from '@nebular/theme'; import { TranslateService } from '@ngx-translate/core'; import { Ng2SmartTableComponent } from 'ng2-smart-table'; import { debounceTime, filter, tap } from 'rxjs/operators'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import * as moment from 'moment'; import { IncomeMutationComponent } from '../../@shared/income/income-mutation/income-mutation.component'; import { DateViewComponent, IncomeExpenseAmountComponent, NotesWithTagsComponent } from '../../@shared/table-components'; import { DeleteConfirmationComponent } from '../../@shared/user/forms'; import { PaginationFilterBaseComponent } from '../../@shared/pagination/pagination-filter-base.component'; import { API_PREFIX, ComponentEnum } from '../../@core/constants'; import { ServerDataSource } from '../../@core/utils/smart-table/server.data-source'; import { ErrorHandlingService, IncomeService, Store, ToastrService } from '../../@core/services'; import { ALL_EMPLOYEES_SELECTED } from '../../@theme/components/header/selectors/employee'; import { OrganizationContactFilterComponent, TagsColorFilterComponent } from '../../@shared/table-filters'; import { AvatarComponent } from '../../@shared/components/avatar/avatar.component'; @UntilDestroy({ checkProperties: true }) @Component({ templateUrl: './income.component.html', styleUrls: ['./income.component.scss'] }) export class IncomeComponent extends PaginationFilterBaseComponent implements AfterViewInit, OnInit, OnDestroy { smartTableSettings: object; selectedEmployeeId: string; selectedDate: Date; smartTableSource: ServerDataSource; disableButton = true; loading: boolean; viewComponentName: ComponentEnum; incomes: IIncome[]; dataLayoutStyle = ComponentLayoutStyleEnum.TABLE; componentLayoutStyleEnum = ComponentLayoutStyleEnum; selectedIncome: IIncome; public organization: IOrganization; subject$: Subject<any> = new Subject(); incomeTable: Ng2SmartTableComponent; @ViewChild('incomeTable') set content(content: Ng2SmartTableComponent) { if (content) { this.incomeTable = content; this.onChangedSource(); } } /* * Actions Buttons directive */ @ViewChild('actionButtons', { static : true }) actionButtons : TemplateRef<any>; constructor( private readonly store: Store, private readonly incomeService: IncomeService, private readonly dialogService: NbDialogService, private readonly toastrService: ToastrService, private readonly route: ActivatedRoute, private readonly errorHandler: ErrorHandlingService, public readonly translateService: TranslateService, private readonly httpClient: HttpClient, private readonly cdr: ChangeDetectorRef ) { super(translateService); this.setView(); } ngOnInit() { this._applyTranslationOnSmartTable(); this._loadSmartTableSettings(); this.subject$ .pipe( debounceTime(300), tap(() => this.loading = true), tap(() => this.getIncomes()), tap(() => this.clearItem()), untilDestroyed(this) ) .subscribe(); const storeOrganization$ = this.store.selectedOrganization$; const storeEmployee$ = this.store.selectedEmployee$; const selectedDate$ = this.store.selectedDate$; combineLatest([storeOrganization$, storeEmployee$, selectedDate$]) .pipe( debounceTime(300), filter(([organization]) => !!organization), tap(([organization]) => (this.organization = organization)), distinctUntilChange(), tap(([organization, employee, date]) => { if (organization) { this.selectedDate = date; this.selectedEmployeeId = employee ? employee.id : null; this.refreshPagination(); this.subject$.next(true); } }), untilDestroyed(this) ) .subscribe(); this.route.queryParamMap .pipe( filter((params) => !!params && params.get('openAddDialog') === 'true'), debounceTime(1000), tap(() => this.addIncome()), untilDestroyed(this) ) .subscribe(); this.cdr.detectChanges(); } ngAfterViewInit() { const { employeeId } = this.store.user; if (employeeId) { delete this.smartTableSettings['columns']['employeeName']; this.smartTableSettings = Object.assign({}, this.smartTableSettings); } } setView() { this.viewComponentName = ComponentEnum.INCOME; this.store .componentLayout$(this.viewComponentName) .pipe( distinctUntilChange(), tap((componentLayout) => this.dataLayoutStyle = componentLayout), filter((componentLayout) => componentLayout === ComponentLayoutStyleEnum.CARDS_GRID), tap(() => this.refreshPagination()), tap(() => this.subject$.next(true)), untilDestroyed(this) ) .subscribe(); } /* * Table on changed source event */ onChangedSource() { this.incomeTable.source.onChangedSource .pipe( untilDestroyed(this), tap(() => this.clearItem()) ) .subscribe(); } private _loadSmartTableSettings() { this.smartTableSettings = { actions: false, mode: 'external', editable: true, noDataMessage: this.getTranslation('SM_TABLE.NO_DATA'), columns: { valueDate: { title: this.getTranslation('SM_TABLE.DATE'), type: 'custom', width: '20%', renderComponent: DateViewComponent, filter: false }, clientName: { title: this.getTranslation('SM_TABLE.CONTACT_NAME'), type: 'string', filter: { type: 'custom', component: OrganizationContactFilterComponent }, filterFunction: (value: IOrganizationContact| null) => { this.setFilter({ field: 'clientId', search: (value)?.id || null }); } }, employeeName: { title: this.getTranslation('SM_TABLE.EMPLOYEE'), filter: false, type: 'custom', sort: false, renderComponent: AvatarComponent, valuePrepareFunction: ( cell, row: IEmployeeProposalTemplate ) => { return { name: row.employee && row.employee.user ? row.employee.fullName : null, id: row.employee ? row.employee.id : null }; } }, amount: { title: this.getTranslation('SM_TABLE.VALUE'), type: 'custom', width: '15%', filter: false, renderComponent: IncomeExpenseAmountComponent }, notes: { title: this.getTranslation('SM_TABLE.NOTES'), type: 'text', class: 'align-row' }, tags: { title: this.getTranslation('SM_TABLE.TAGS'), type: 'custom', class: 'align-row', renderComponent: NotesWithTagsComponent, filter: { type: 'custom', component: TagsColorFilterComponent }, filterFunction: (tags: ITag[]) => { const tagIds = []; for (const tag of tags) { tagIds.push(tag.id); } this.setFilter({ field: 'tags', search: tagIds }); }, sort: false } }, pager: { display: true, perPage: this.pagination.itemsPerPage } }; } private _applyTranslationOnSmartTable() { this.translateService.onLangChange .pipe( tap(() => this._loadSmartTableSettings()), untilDestroyed(this) ) .subscribe(); } async addIncome() { if (!this.store.selectedDate) { this.store.selectedDate = this.store.getDateFromOrganizationSettings(); } this.dialogService .open(IncomeMutationComponent) .onClose .pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const { amount, organizationContact, valueDate, employee, notes, currency, isBonus, tags } = result; await this.incomeService.create({ amount, clientId: organizationContact.id, valueDate, employeeId: employee ? employee.id : null, organizationId, tenantId, notes, currency, isBonus, tags }) .then(() => { this.toastrService.success('NOTES.INCOME.ADD_INCOME', { name: this.employeeName(employee) }); }) .finally(() => { this.subject$.next(true); }); } catch (error) { this.toastrService.danger(error); } } }); } selectIncome({ isSelected, data }) { this.disableButton = !isSelected; this.selectedIncome = isSelected ? data : null; } async editIncome(selectedItem?: IIncome) { if (selectedItem) { this.selectIncome({ isSelected: true, data: selectedItem }); } this.dialogService .open(IncomeMutationComponent, { context: { income: this.selectedIncome } }) .onClose.pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { const { amount, organizationContact, valueDate, notes, currency, isBonus, tags } = result; const { employee } = this.selectedIncome; await this.incomeService.update(this.selectedIncome.id, { amount, clientId: organizationContact.id, valueDate, notes, currency, isBonus, tags, employeeId: employee ? employee.id : null }).then(() => { this.toastrService.success('NOTES.INCOME.EDIT_INCOME', { name: this.employeeName(employee) }); }) .finally(() => { this.subject$.next(true); }); } catch (error) { this.errorHandler.handleError(error); } } }); } async deleteIncome(selectedItem?: IIncome) { if (selectedItem) { this.selectIncome({ isSelected: true, data: selectedItem }); } this.dialogService .open(DeleteConfirmationComponent, { context: { recordType: this.getTranslation('INCOME_PAGE.INCOME') } }) .onClose.pipe(untilDestroyed(this)) .subscribe(async (result) => { if (result) { try { const { id, employee } = this.selectedIncome; await this.incomeService.delete( id, employee ? employee.id : null ) .then(() => { this.toastrService.success('NOTES.INCOME.DELETE_INCOME', { name: this.employeeName(employee) }); }) .finally(() => { this.subject$.next(true); }); } catch (error) { this.errorHandler.handleError(error); } } }); } /* * Register Smart Table Source Config */ setSmartTableSource() { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const request = {}; if (this.selectedEmployeeId) { request['employeeId'] = this.selectedEmployeeId; } if (moment(this.selectedDate).isValid()) { request['valueDate'] = moment(this.selectedDate).format('YYYY-MM-DD HH:mm:ss'); } this.smartTableSource = new ServerDataSource(this.httpClient, { endPoint: `${API_PREFIX}/income/pagination`, relations: [ 'employee', 'employee.user', 'tags', 'organization', 'client' ], join: { alias: 'income', leftJoin: { tags: 'income.tags' } }, where: { ...{ organizationId, tenantId }, ...request, ...this.filters.where }, resultMap: (income: IIncome) => { return Object.assign({}, income, { employeeName: income.employee ? income.employee.fullName : null, clientName: income.client ? income.client.name : income.clientName, }); }, finalize: () => { this.loading = false; } }); } private async getIncomes() { try { this.setSmartTableSource(); if (this.dataLayoutStyle === ComponentLayoutStyleEnum.CARDS_GRID) { // Initiate GRID view pagination const { activePage, itemsPerPage } = this.pagination; this.smartTableSource.setPaging(activePage, itemsPerPage, false); await this.smartTableSource.getElements(); this.incomes = this.smartTableSource.getData(); this.pagination['totalItems'] = this.smartTableSource.count(); } } catch (error) { this.toastrService.danger(error); } } /* * Clear selected item */ clearItem() { this.selectIncome({ isSelected: false, data: null }); this.deselectAll(); } /* * Deselect all table rows */ deselectAll() { if (this.incomeTable && this.incomeTable.grid) { this.incomeTable.grid.dataSet['willSelect'] = 'false'; this.incomeTable.grid.dataSet.deselectAll(); } } employeeName(employee: IEmployee) { return ( employee && employee.id ) ? (employee.fullName).trim() : ALL_EMPLOYEES_SELECTED.firstName; } ngOnDestroy() { } }
the_stack
import assert from 'assert'; import AsyncTestUtil from 'async-test-util'; import BroadcastChannel from 'broadcast-channel'; import convertHrtime from 'convert-hrtime'; import * as schemas from './helper/schemas'; import * as schemaObjects from './helper/schema-objects'; import { mergeMap } from 'rxjs/operators'; // we do a custom build without dev-plugins, // like you would use in production import { createRxDatabase, addRxPlugin, randomCouchString, dbCount, RxDatabase } from '../plugins/core'; import { addPouchPlugin, getRxStoragePouch } from '../plugins/pouchdb'; addPouchPlugin(require('pouchdb-adapter-memory')); import { RxDBNoValidatePlugin } from '../plugins/no-validate'; addRxPlugin(RxDBNoValidatePlugin); import { RxDBKeyCompressionPlugin } from '../plugins/key-compression'; addRxPlugin(RxDBKeyCompressionPlugin); import { RxDBMigrationPlugin } from '../plugins/migration'; addRxPlugin(RxDBMigrationPlugin); const elapsedTime = (before: any) => { try { return convertHrtime(process.hrtime(before)).milliseconds; } catch (err) { return performance.now() - before; } }; const nowTime = () => { try { return process.hrtime(); } catch (err) { return performance.now(); } }; async function afterTest() { await AsyncTestUtil.wait(waitTimeBetween / 2); // ensure databases cleaned up const count = dbCount(); assert.strictEqual(count, 0); await global.gc(); await AsyncTestUtil.wait(waitTimeBetween / 2); } // each test can take about 10seconds const benchmark: any = { spawnDatabases: { amount: 1000, collections: 5, total: 0, perInstance: 0 }, insertDocuments: { blocks: 2000, blockSize: 5, total: 0, perBlock: 0 }, findDocuments: { amount: 10000, total: 0, perDocument: 0 }, migrateDocuments: { amount: 1000, total: 0 }, writeWhileSubscribe: { amount: 1000, total: 0 } }; const ormMethods = { foo() { return 'bar'; }, foobar() { return 'barbar'; }, foobar2() { return 'barbar'; } }; // increase this to measure minimal optimisations const runs = 1; const waitTimeBetween = 1000; for (let r = 0; r < runs; r++) { describe('performance.test.js', function () { this.timeout(90 * 1000); it('clear broadcast-channel tmp-folder', async () => { await BroadcastChannel.clearNodeFolder(); }); it('wait a bit for jit', async () => { await AsyncTestUtil.wait(2000); }); it('spawnDatabases', async () => { // create databases with some collections each const dbs: RxDatabase[] = []; const startTime = nowTime(); for (let i = 0; i < benchmark.spawnDatabases.amount; i++) { const db = await createRxDatabase({ name: randomCouchString(10), eventReduce: true, storage: getRxStoragePouch('memory') }); dbs.push(db); const collectionData: any = {}; new Array(benchmark.spawnDatabases.collections) .fill(0) .forEach(() => { const name = 'human' + randomCouchString(10); collectionData[name] = { schema: schemas.averageSchema(), statics: ormMethods }; }); await db.addCollections(collectionData); } const elapsed = elapsedTime(startTime); benchmark.spawnDatabases.total = benchmark.spawnDatabases.total + elapsed; benchmark.spawnDatabases.perInstance = elapsed / benchmark.spawnDatabases.amount; await Promise.all(dbs.map(db => db.destroy())); await afterTest(); }); it('insertDocuments', async () => { const db = await createRxDatabase({ name: randomCouchString(10), eventReduce: true, storage: getRxStoragePouch('memory') }); const cols = await db.addCollections({ human: { schema: schemas.averageSchema(), methods: ormMethods } }); const col = cols.human; let lastDoc; const docsData = new Array(benchmark.insertDocuments.blocks * benchmark.insertDocuments.blockSize) .fill(0) .map(() => schemaObjects.averageSchema()); const startTime = nowTime(); for (let i = 0; i < benchmark.insertDocuments.blocks; i++) { await Promise.all( new Array(benchmark.insertDocuments.blockSize) .fill(0) .map(async () => { const doc = await col.insert(docsData.pop()); lastDoc = doc; }) ); } const elapsed = elapsedTime(startTime); assert.ok(lastDoc); benchmark.insertDocuments.total = benchmark.insertDocuments.total + elapsed; benchmark.insertDocuments.perBlock = elapsed / benchmark.insertDocuments.blocks; await db.destroy(); await afterTest(); }); it('findDocuments', async () => { const dbName = randomCouchString(10); const schema = schemas.averageSchema(); const db = await createRxDatabase({ name: dbName, eventReduce: true, storage: getRxStoragePouch('memory') }); const cols = await db.addCollections({ human: { schema, methods: ormMethods } }); const col = cols.human; await Promise.all( new Array(benchmark.findDocuments.amount) .fill(0) .map(() => schemaObjects.averageSchema()) .map(data => col.insert(data)) ); await db.destroy(); const db2 = await createRxDatabase({ name: dbName, storage: getRxStoragePouch('memory'), eventReduce: true, ignoreDuplicate: true }); const cols2 = await db2.addCollections({ human: { schema, methods: ormMethods } }); const col2 = cols2.human; const startTime = nowTime(); const allDocs = await col2.find().exec(); const elapsed = elapsedTime(startTime); assert.strictEqual(allDocs.length, benchmark.findDocuments.amount); benchmark.findDocuments.total = benchmark.findDocuments.total + elapsed; benchmark.findDocuments.perDocument = elapsed / benchmark.findDocuments.amount; await db2.destroy(); await afterTest(); }); it('migrateDocuments', async () => { const name = randomCouchString(10); const db = await createRxDatabase({ name, eventReduce: true, storage: getRxStoragePouch('memory') }); const cols = await db.addCollections({ human: { schema: schemas.averageSchema() } }); const col = cols.human; // insert into old collection await Promise.all( new Array(benchmark.migrateDocuments.amount) .fill(0) .map(() => schemaObjects.averageSchema()) .map(docData => col.insert(docData)) ); const db2 = await createRxDatabase({ name, eventReduce: true, storage: getRxStoragePouch('memory'), ignoreDuplicate: true }); const newSchema = schemas.averageSchema(); newSchema.version = 1; newSchema.properties.var2.type = 'string'; const cols2 = await db2.addCollections({ human: { schema: newSchema, migrationStrategies: { 1: (oldDoc: any) => { oldDoc.var2 = oldDoc.var2 + ''; return oldDoc; } }, autoMigrate: false } }); const col2 = cols2.human; const startTime = nowTime(); await col2.migratePromise(); const elapsed = elapsedTime(startTime); benchmark.migrateDocuments.total = benchmark.migrateDocuments.total + elapsed; await db.destroy(); await db2.destroy(); await afterTest(); }); it('writeWhileSubscribe', async () => { const name = randomCouchString(10); const db = await createRxDatabase({ name, eventReduce: true, storage: getRxStoragePouch('memory') }); const cols = await db.addCollections({ human: { schema: schemas.averageSchema() } }); const col = cols.human; const query = col.find({ selector: { var2: { $gt: 1 } }, sort: [ { var1: 'asc' } ] }); let t = 0; let lastResult: any[] = []; const startTime = nowTime(); await new Promise(res => { const obs$ = query.$.pipe( mergeMap(async (result) => { if (t <= benchmark.writeWhileSubscribe.amount) { t++; await col.insert(schemaObjects.averageSchema()); } else { sub.unsubscribe(); res(null); } return result; }) ); const sub = obs$.subscribe(result => { lastResult = result; }); }); const elapsed = elapsedTime(startTime); benchmark.writeWhileSubscribe.total = benchmark.writeWhileSubscribe.total + elapsed; assert.strictEqual(lastResult.length, benchmark.writeWhileSubscribe.amount); await db.destroy(); await afterTest(); }); it('show results:', async () => { await afterTest(); console.log(JSON.stringify(benchmark, null, 2)); }); }); }
the_stack
import { HttpMethods } from './../../shared/models/constants'; import { FunctionAppService } from 'app/shared/services/function-app.service'; import { Headers } from '@angular/http'; import { UUID } from 'angular2-uuid'; import { Observable } from 'rxjs/Observable'; import { BindingComponent } from '../../binding/binding.component'; import { FunctionNewComponent } from '../../function/function-new/function-new.component'; import { CacheService } from '../../shared/services/cache.service'; import { AiService } from '../../shared/services/ai.service'; import { ArmObj } from '../../shared/models/arm/arm-obj'; import { MSGraphConstants, AADPermissions, AADRegistrationInfo } from '../../shared/models/microsoft-graph'; import { FunctionAppContext } from 'app/shared/function-app-context'; declare const Buffer: any; declare var require: any; export class MicrosoftGraphHelper { public binding?: BindingComponent; public function?: FunctionNewComponent; private _token: string; private _jwt: any; private setClientSecret = false; constructor( private context: FunctionAppContext, private _functionAppService: FunctionAppService, private _cacheService: CacheService, private _aiService?: AiService ) {} getADDAppRegistrationInfo(necessaryAADPermisisons: AADPermissions[], graphToken: string): Observable<AADRegistrationInfo> { const cloneNecessaryAADPermisisons = JSON.parse(JSON.stringify(necessaryAADPermisisons)); const rootUri = this.getRootUri(graphToken); const result: AADRegistrationInfo = { isPermissionConfigured: false, isAADAppCreated: false, permissions: cloneNecessaryAADPermisisons, }; return this.checkForExistingAAD(rootUri).flatMap(applicationInformation => { // If it already exists, check to see if it has necessary client secret & resources let existingApplication: any; if (applicationInformation) { existingApplication = applicationInformation.json().value[0]; } if (existingApplication) { result.isAADAppCreated = true; result.isPermissionConfigured = true; // Check if app has all required resource permissions if (!existingApplication.requiredResourceAccess) { existingApplication.requiredResourceAccess = []; } let appPerm = null; result.permissions.forEach(requiredPerm => { const findPerm = existingApplication.requiredResourceAccess.find(p => { if (p.resourceAppId.toLocaleLowerCase() === requiredPerm.resourceAppId.toLocaleLowerCase()) { appPerm = p; return true; } else { return false; } }); if (findPerm) { requiredPerm.resourceAccess.forEach(requiredAccess => { const findAccess = appPerm.resourceAccess.find(appAccess => { return requiredAccess.id.toLocaleLowerCase() === appAccess.id.toLocaleLowerCase(); }); requiredAccess.configured = !!findAccess; }); } }); result.permissions.forEach(p => { p.resourceAccess.forEach(ra => { if (!ra.configured) { result.isPermissionConfigured = false; } }); }); return Observable.of(result); } else { return Observable.of(result); } }); } configureAAD(necessaryAADPermisisons: AADPermissions[], graphToken: string): Observable<any> { const rootUri = this.getRootUri(graphToken); // If it does not exist, create it & set necessary resources const appUri = this.context.mainSiteUrl; const name = this.context.site.name; const app = { displayName: name, homepage: appUri, identifierUris: [appUri], oauth2AllowImplicitFlow: true, replyUrls: [trimTrailingSlash(appUri) + MSGraphConstants.General.AADReplyUrl], passwordCredentials: [GeneratePasswordCredentials()], requiredResourceAccess: necessaryAADPermisisons, }; const pwCreds = app.passwordCredentials[0]; const application = JSON.stringify(app); return this.sendRequest(rootUri, '/applications', 'POST', application) .do(null, err => { if (this._aiService) { this._aiService.trackException(err, 'Error while creating new AAD application'); } }) .flatMap(response => { const newApplication = JSON.parse(response._body); return this.setAuthSettings(newApplication.appId, this._jwt, pwCreds.value, app.replyUrls); }); } addPermissions(necessaryAADPermisisons: AADPermissions[], graphToken: string): Observable<any> { this._token = graphToken; const jwt = parseToken(this._token); if (!jwt) { throw Error('Unable to parse MS Graph JWT; cannot retrieve audience or tenant ID'); } const rootUri = jwt.aud + jwt.tid; // audience + tenantId return this.checkForExistingAAD(rootUri).flatMap(applicationInformation => { // If it already exists, check to see if it has necessary client secret & resources let existingApplication: any = {}; if (applicationInformation) { existingApplication = applicationInformation.json().value[0]; } if (existingApplication) { // Legacy reasons: check for client secret (Easy Auth used to not set Client Secret automatically) if (this.setClientSecret) { this.createClientSecret(rootUri, existingApplication.objectId).subscribe( () => { this.setClientSecret = false; }, error => { if (this._aiService) { this._aiService.trackException(error, "Could not update AAD manifest's client secret"); } } ); } const patch: any = {}; patch.value = CompareResources(existingApplication.requiredResourceAccess, necessaryAADPermisisons); return this.sendRequest( rootUri, '/applications/' + existingApplication.objectId + '/requiredResourceAccess', 'PATCH', JSON.stringify(patch) ); } else { return Observable.of(null); } }); } // Set long list of auth settings needed by Easy Auth private setAuthSettings(applicationId: string, jwt, clientSecret, replyUrls) { const authSettings = new Map<string, any>(); authSettings.set('enabled', true); authSettings.set('unauthenticatedClientAction', 'AllowAnonymous'); authSettings.set('tokenStoreEnabled', true); authSettings.set('allowedExternalRedirectUrls', window.location.hostname); authSettings.set('defaultProvider', 'AzureActiveDirectory'); authSettings.set('clientId', applicationId); authSettings.set('clientSecret', clientSecret); authSettings.set('issuer', jwt.iss); authSettings.set('allowedAudiences', replyUrls); authSettings.set('isAadAutoProvisioned', true); return this._functionAppService.createAuthSettings(this.context, authSettings).do(null, error => { if (this._aiService) { this._aiService.trackException(error, 'Error occurred while setting necessary authsettings'); } }); } private checkForExistingAAD(rootUri: string): Observable<any> { return this._cacheService.postArm(`${this.context.site.id}/config/authsettings/list`, true).flatMap(r => { const authSettings: ArmObj<any> = r.json(); const clientId = authSettings.properties['clientId']; this.setClientSecret = !authSettings.properties['clientSecret']; if (clientId) { return this.sendRequest(rootUri, '/applications', 'GET', null, "appId eq '" + clientId + "'", true); } else { return Observable.of(null); } }); } // Update client secret of AAD + auth settings of existing registration private createClientSecret(rootUri: string, objectId: string): Observable<any> { const pwCreds = GeneratePasswordCredentials(); const authSettings = new Map<string, any>(); authSettings.set('clientSecret', pwCreds.keyId); return this._functionAppService.createAuthSettings(this.context, authSettings).do( () => { return this.sendRequest(rootUri, '/applications/' + objectId + '/passwordCredentials', 'PATCH', JSON.stringify(pwCreds)); }, error => { if (this._aiService) { this._aiService.trackException(error, 'Error while updating authsetting with new client secret'); } } ); } private sendRequest( baseUrl: string, extension: string, method: string, jsonPayload?, queryParameters?: string, force?: boolean ): Observable<any> { let url = trimTrailingSlash(baseUrl) + extension + '?api-version=' + MSGraphConstants.General.ApiVersion; if (queryParameters) { url += '&$filter=' + encodeURIComponent(queryParameters); } const headers = new Headers(); headers.append('Authorization', `Bearer ${this._token}`); if (method.toLowerCase() === HttpMethods.POST) { headers.append('Content-Type', 'application/json'); return this._cacheService.post(url, force, headers, jsonPayload); } else if (method.toLowerCase() === HttpMethods.PUT) { headers.append('Content-Type', 'application/json'); return this._cacheService.put(url, headers, jsonPayload); } else if (method.toLowerCase() === HttpMethods.PATCH) { headers.append('Content-Type', 'application/json; charset=utf-8'); return this._cacheService.patch(url, headers, jsonPayload); } return this._cacheService.get(url, force, headers); } private getRootUri(graphToken: string): string { this._token = graphToken; this._jwt = parseToken(this._token); if (!this._jwt) { throw Error('Unable to parse MS Graph JWT; cannot retrieve audience or tenant ID'); } return this._jwt.aud + this._jwt.tid; // audience + tenantId } } function base64urlUnescape(str: string) { str += new Array(5 - (str.length % 4)).join('='); return str.replace(/\-/g, '+').replace(/_/g, '/'); } function trimTrailingSlash(url): string { return url.replace(/\/$/, ''); } export function parseToken(token: string) { const segments = token.split('.'); if (segments.length >= 2) { try { const payload = JSON.parse(base64urlDecode(segments[1])); return payload; } catch (e) { return null; } } } function base64urlDecode(payloadSegment: string) { return new Buffer(base64urlUnescape(payloadSegment), 'base64').toString(); } function GeneratePasswordCredentials() { return { endDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000), keyId: UUID.UUID(), startDate: new Date(), value: GeneratePassword(), }; } function GeneratePassword(): string { const crypto = require('crypto-browserify'); return crypto.randomBytes(32).toString('base64'); } // Given a set of resources a binding/tempalte needs and the app's current resources, determine the union of the two sets // Retain current resources and add additional ones if necessary export function CompareResources(current, necessary) { // Resources associated with MS Graph that application manifest currently contains const existingMSGraph = current.find(obj => { return obj.resourceAppId === MSGraphConstants.RequiredResources.MicrosoftGraph; }); // Resources associated with MS Graph that application needs for this specific binding/template const necessaryMSGraph = necessary.find(obj => { return obj.resourceAppId === MSGraphConstants.RequiredResources.MicrosoftGraph; }); const unionMSGraph: any = {}; if (existingMSGraph) { // Union two arrays by removing intersection from existing resources then concatenating remaining unionMSGraph.resourceAccess = necessaryMSGraph.resourceAccess.concat( existingMSGraph.resourceAccess.filter(item => { return ( necessaryMSGraph.resourceAccess.findIndex(necessary => { return necessary.type === item.type && necessary.id === item.id; }) < 0 ); }) ); } else { // If no MS Graph resources are currently required, the new ones are just the ones this binding/template needs unionMSGraph.resourceAccess = necessaryMSGraph.resourceAccess; } // Set up the object that will be used in the request payload unionMSGraph.resourceAppId = MSGraphConstants.RequiredResources.MicrosoftGraph; const unionAAD: any = {}; // Same as MS Graph, only this time comparing AAD resources const existingAAD = current.find(obj => { return obj.resourceAppId === MSGraphConstants.RequiredResources.WindowsAzureActiveDirectory; }); const necessaryAAD = necessary.find(obj => { return obj.resourceAppId === MSGraphConstants.RequiredResources.WindowsAzureActiveDirectory; }); if (existingAAD) { // Union two arrays by removing intersection from existing resources then concatenating remaining unionAAD.resourceAccess = necessaryAAD.resourceAccess.concat( existingAAD.resourceAccess.filter(item => { return ( necessaryAAD.resourceAccess.findIndex(necessary => { return necessary.type === item.type && necessary.id === item.id; }) < 0 ); }) ); } else { unionAAD.resourceAccess = necessaryAAD.resourceAccess; } unionAAD.resourceAppId = MSGraphConstants.RequiredResources.WindowsAzureActiveDirectory; return [unionMSGraph, unionAAD]; }
the_stack
import { DI, ILifecycleHooks, ILogger, IRouteViewModel, lifecycleHooks, NavigationInstruction, Params, RouteNode, } from 'aurelia'; import { Article, ArticleListResponse, ArticleResponse, Comment, ErrorRecordResponse, IApiService, IJwtService, ArticleQueryParams, User, UserLogin, UserRegistration, UserResponse, UserUpdate, ArticleListQueryParams, Profile, ProfileResponse, ErrorList, } from './api'; /** * Singleton `User` state that represents the currently logged-in user. */ export const IUserState = DI.createInterface<IUserState>('IUserState', (x) => x.singleton(UserState) ); export interface IUserState extends UserState {} export class UserState { errors: ErrorList = []; current = User.NONE; isAuth = false; constructor( @IJwtService private readonly jwt: IJwtService, @IApiService private readonly api: IApiService ) {} loadPending = false; async load(): Promise<void> { if (this.jwt.isTokenValid()) { this.loadPending = true; const resp = await this.api.getCurrentUser(); this.loadPending = false; this.setAuth(resp.user); } else { this.clearAuth(); } } loginPending = false; async login(login: UserLogin): Promise<boolean> { this.errors = []; this.loginPending = true; const resp = await this.api.loginUser(login); this.loginPending = false; if (resp instanceof ErrorRecordResponse) { this.clearAuth(); this.errors = resp.toErrorList(); return false; } this.setAuth(resp.user); return true; } logout(): void { this.clearAuth(); } registerPending = false; async register(registration: UserRegistration): Promise<boolean> { this.errors = []; this.registerPending = true; const resp = await this.api.registerUser(registration); this.registerPending = false; if (resp instanceof ErrorRecordResponse) { this.clearAuth(); this.errors = resp.toErrorList(); return false; } this.setAuth(resp.user); return true; } updatePending = false; async update(user: UserUpdate): Promise<void> { this.updatePending = true; const resp = await this.api.updateUser(user); this.updatePending = false; if (resp instanceof UserResponse) { this.current = resp.user; } } private setAuth(user: User): void { this.jwt.saveToken(user.token); this.current = user; this.isAuth = true; } private clearAuth(): void { this.jwt.destroyToken(); this.current = User.NONE; this.isAuth = false; } } /** * Singleton `Profile` state that represents the profile currently routed to. */ export const IProfileState = DI.createInterface<IProfileState>( 'IProfileState', (x) => x.singleton(ProfileState) ); export interface IProfileState extends ProfileState {} export class ProfileState { current = Profile.NONE; constructor(@IApiService private readonly api: IApiService) {} toggleFollowPending = false; async toggleFollow(): Promise<void> { const profile = this.current; const username = profile.username; let resp: ProfileResponse; this.toggleFollowPending = true; if (profile.following) { resp = await this.api.unfollowUser(username); } else { resp = await this.api.followUser(username); } this.toggleFollowPending = false; this.current = resp.profile; } // Stuff for request deduplication. // Not super necessary in this app, but still good form when arbitrary components may request data from the state object. // This guarantees only the first request results in an api call, and subsequent requests will wait for the same initial promise. private nextUsername = ''; private loadPromise: Promise<void> | null = null; loadPending = false; async load(username: string): Promise<void> { if (username === this.nextUsername) { return this.loadPromise ?? undefined; } this.nextUsername = username; return (this.loadPromise = (async () => { this.loadPending = true; const resp = await this.api.getProfile(username); this.loadPending = false; this.loadPromise = null; this.current = resp.profile; })()); } } /** * Singleton `Article` state that represents the article currently routed to. */ export const IArticleState = DI.createInterface<IArticleState>( 'IArticleState', (x) => x.singleton(ArticleState) ); export interface IArticleState extends ArticleState {} export class ArticleState { errors: ErrorList = []; current: Article = Article.NONE; comments: Comment[] = []; constructor(@IApiService private readonly api: IApiService) {} toggleFollowPending = false; async toggleFollow(): Promise<void> { const author = this.current.author; const username = author.username; let resp: ProfileResponse; this.toggleFollowPending = true; if (author.following) { resp = await this.api.unfollowUser(username); } else { resp = await this.api.followUser(username); } this.toggleFollowPending = false; this.current.author = resp.profile; } toggleFavoritePending = false; async toggleFavorite(): Promise<void> { const article = this.current; let resp: ArticleResponse; this.toggleFavoritePending = true; if (article.favorited) { resp = await this.api.unfavoriteArticle(article.slug); } else { resp = await this.api.favoriteArticle(article.slug); } this.toggleFavoritePending = false; this.current = resp.article; } private nextSlug = ''; private loadPromise: Promise<void> | null = null; loadPending = false; async load(slug = ''): Promise<void> { if (slug === this.nextSlug) { return this.loadPromise ?? undefined; } this.nextSlug = slug; this.current = Article.NONE; this.comments = []; if (slug) { return (this.loadPromise = (async () => { this.loadPending = true; // TODO: handle 404 and other errors gracefully const resp = await this.api.getArticle(slug); if (slug === this.nextSlug) { this.loadPending = false; this.loadPromise = null; this.current = resp.article; } })()); } } private nextCommentsSlug = ''; private loadCommentsPromise: Promise<void> | null = null; loadCommentsPending = false; async loadComments(slug: string): Promise<void> { if (slug === this.nextCommentsSlug) { return this.loadCommentsPromise ?? undefined; } this.nextCommentsSlug = slug; return (this.loadCommentsPromise = (async () => { this.loadCommentsPending = true; // TODO: handle 404 and other errors gracefully const resp = await this.api.getCommentsFromArticle(slug); if (slug === this.nextCommentsSlug) { this.loadCommentsPending = false; this.loadCommentsPromise = null; this.comments = resp.comments; } })()); } savePending = false; async save(article: Article): Promise<boolean> { this.errors = []; let resp: ErrorRecordResponse | ArticleResponse; this.savePending = true; if (article.slug) { resp = await this.api.updateArticle(article.slug, article); } else { resp = await this.api.createArticle(article); } this.savePending = false; if (resp instanceof ErrorRecordResponse) { this.errors = resp.toErrorList(); return false; } this.current = resp.article; return true; } deletePending = false; async delete(): Promise<void> { this.errors = []; this.deletePending = true; await this.api.deleteArticle(this.current.slug); this.deletePending = false; this.current = Article.NONE; } addCommentPending = false; async addComment(body: string): Promise<boolean> { this.errors = []; const article = this.current; this.addCommentPending = true; const resp = await this.api.addCommentToArticle(article.slug, { body }); this.addCommentPending = false; if (resp instanceof ErrorRecordResponse) { this.errors = resp.toErrorList(); return false; } this.comments.push(resp.comment); return true; } deleteCommentPending = false; async deleteComment(commentId: number): Promise<void> { if (this.deleteCommentPending) { return; } this.errors = []; const article = this.current; this.deleteCommentPending = true; await this.api.deleteCommentFromArticle(article.slug, commentId); this.deleteCommentPending = false; const idx = this.comments.findIndex((x) => x.id === commentId); this.comments.splice(idx, 1); } } /** * Singleton `Article` list state that represents the list of articles (and the query params that narrow them down) currently being viewed. */ export const IArticleListState = DI.createInterface<IArticleListState>( 'IArticleListState', (x) => x.singleton(ArticleListState) ); export interface IArticleListState extends ArticleListState {} export class ArticleListState { items: Article[] = []; itemsCount = 0; currentPage = 0; pages: number[] = []; params: ArticleQueryParams = ArticleListQueryParams.create({ limit: 20, offset: 0, }); constructor(@IApiService private readonly api: IApiService) {} toggleFavoritePending = {} as Record<string, boolean>; async toggleFavorite(slug: string): Promise<void> { const idx = this.items.findIndex((x) => x.slug === slug); const article = this.items[idx]; let resp: ArticleResponse; this.toggleFavoritePending[slug] = true; if (article.favorited) { resp = await this.api.unfavoriteArticle(slug); } else { resp = await this.api.favoriteArticle(slug); } this.toggleFavoritePending[slug] = false; this.items.splice(idx, 1, resp.article); } loadPending = false; async load(params: ArticleQueryParams = this.params): Promise<void> { this.params = params; let resp: ArticleListResponse; this.loadPending = true; if (params.type === 'all') { resp = await this.api.getArticles(params); } else { resp = await this.api.getFeedArticles(params); } this.loadPending = false; this.items = resp.articles; this.itemsCount = resp.articlesCount; this.currentPage = (params.offset + this.items.length) / params.limit; this.pages = Array.from( Array(Math.ceil(resp.articlesCount / params.limit)), (_, i) => i + 1 ); } } /** * Singleton tags state that represents all global tags. */ export const ITagsState = DI.createInterface<ITagsState>('ITagsState', (x) => x.singleton(TagsState) ); export interface ITagsState extends TagsState {} export class TagsState { items: string[] = []; constructor(@IApiService private readonly api: IApiService) {} loadPending = false; async load(): Promise<void> { this.loadPending = true; const resp = await this.api.getTags(); this.loadPending = false; this.items = resp.tags; } } @lifecycleHooks() export class AuthHandler implements ILifecycleHooks<IRouteViewModel, 'canLoad'> { constructor( @IUserState readonly auth: IUserState, @ILogger readonly logger: ILogger ) { this.logger = logger.scopeTo('AuthHandler'); } canLoad( vm: IRouteViewModel, params: Params, next: RouteNode ): boolean | NavigationInstruction { if (!this.auth.isAuth) { this.logger.trace( `canLoad() - redirecting to login page`, next, this.auth ); return 'login'; } this.logger.trace(`canLoad() - proceeding`, next, this.auth); return true; } }
the_stack
/// <reference types="angular" /> import * as angular from 'angular'; declare const moduleName: 'ui.bootstrap'; export = moduleName; declare module 'angular' { export namespace ui.bootstrap { interface IAccordionConfig { /** * Controls whether expanding an item will cause the other items to close. * * @default true */ closeOthers?: boolean | undefined; } interface IButtonConfig { /** * @default: 'active' */ activeClass?: string | undefined; /** * @default: 'Click' */ toggleEvent?: string | undefined; } interface IDropdownConfigNgOptions extends angular.INgModelOptions { allowInvalid?: boolean | undefined; timezone?: string | undefined; } type DatepickerCallback<T> = (args: IDatepickerCellArgs) => T; type DatepickerMode = "day" | "month" | "year"; interface IDatepickerCellArgs { date: Date; mode: DatepickerMode; } interface IDatepickerConfig { /** * Format of day in month. * * @default 'dd' */ formatDay?: string | undefined; /** * Format of month in year. * * @default 'MMM' */ formatMonth?: string | undefined; /** * Format of year in year range. * * @default 'yyyy' */ formatYear?: string | undefined; /** * Format of day in week header. * * @default 'EEE' */ formatDayHeader?: string | undefined; /** * Format of title when selecting day. * * @default 'MMM yyyy' */ formatDayTitle?: string | undefined; /** * Format of title when selecting month. * * @default 'yyyy' */ formatMonthTitle?: string | undefined; /** * Current mode of the datepicker (day|month|year). Can be used to initialize datepicker to specific mode. * * @default 'day' */ datepickerMode?: DatepickerMode | undefined; /** * Set a lower limit for mode. * * @default 'day' */ minMode?: string | undefined; /** * Set an upper limit for mode. * * @default 'year' */ maxMode?: string | undefined; /** * Whether to display week numbers. * * @default true */ showWeeks?: boolean | undefined; /** * Starting day of the week from 0-6 where 0=Sunday and 6=Saturday. * * @default 0 */ startingDay?: number | undefined; /** * Number of years displayed in year selection. * * @default 20 */ yearRange?: number | undefined; /** * Defines the minimum available date. * * @default null */ minDate?: any; /** * Defines the maximum available date. * * @default null */ maxDate?: any; /** * Defines the initial date, when no model value is specified. * * @default null */ initDate?: any; /** * An option to disable or enable shortcut's event propagation * * @default false */ shortcutPropagation?: boolean | undefined; /** * The number of columns displayed in month selection. * * @default 3 */ monthColumns?: number | undefined; /** * The number of columns displayed in year selection. * * @default 5 */ yearColumns?: number | undefined; /** * The number of rows displayed in year selection * * @default 4 */ yearRows?: number | undefined; /** * All supported angular ngModelOptions plus some * * @default {} */ ngModelOptions?: IDropdownConfigNgOptions | undefined; /** * Defines an optional expression to disable visible options based on passing an object with date and current mode properties. * * @default null */ dateDisabled?: DatepickerCallback<boolean> | undefined; /** * Defines an optional expression to add classes based on passing an object with date and current mode properties. * * @default null */ customClass?: DatepickerCallback<string> | undefined; } interface IDatepickerPopupConfig extends IDatepickerConfig { /** * A list of alternate formats acceptable for manual entry. * * @default [] */ altInputFormats?: string[] | undefined; /** * The format for displayed dates. * * @default 'yyyy-MM-dd' */ datepickerPopup?: string | undefined; /** * Allows overriding of default template of the popup. * * @default 'template/datepicker/popup.html' */ datepickerPopupTemplateUrl?: string | undefined; /** * Allows overriding of default template of the datepicker used in popup. * * @default 'template/datepicker/popup.html' */ datepickerTemplateUrl?: string | undefined; /** * Allows overriding of the default format for html5 date inputs. */ html5Types?: { date?: string | undefined; 'datetime-local'?: string | undefined; month?: string | undefined; } | undefined; /** * The text to display for the current day button. * * @default 'Today' */ currentText?: string | undefined; /** * The text to display for the clear button. * * @default 'Clear' */ clearText?: string | undefined; /** * The text to display for the close button. * * @default 'Done' */ closeText?: string | undefined; /** * Whether to close calendar when a date is chosen. * * @default true */ closeOnDateSelection?: boolean | undefined; /** * Append the datepicker popup element to `body`, rather than inserting after `datepicker-popup`. * * @default false */ appendToBody?: boolean | undefined; /** * Whether to display a button bar underneath the datepicker. * * @default true */ showButtonBar?: boolean | undefined; /** * Whether to focus the datepicker popup upon opening. * * @default true */ onOpenFocus?: boolean | undefined; /** * Passing in 'auto' separated by a space before the placement will enable auto positioning, e.g: "auto bottom-left". The popup will attempt to position where it fits in the closest scrollable ancestor. * * @default 'auto bottom-left' */ placement?: string | undefined; } interface IDropdownConfig { /** * @default: 'uib-dropdown-open' */ appendToOpenClass?: string | undefined; /** * @default: 'open' */ openClass?: string | undefined; } interface IModalProvider extends angular.IServiceProvider { /** * Default options all modals will use. */ options: IModalSettings; } interface IModalService { /** * @returns {IPromise} */ getPromiseChain(): IPromise<any>; /** * @param {IModalSettings} options * @returns {IModalInstanceService} */ open(options: IModalSettings): IModalInstanceService; } interface IModalInstanceService { /** * A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. */ close(result?: any): void; /** * A method that can be used to dismiss a modal, passing a reason. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. */ dismiss(reason?: any): void; /** * A promise that is resolved when a modal is closed and rejected when a modal is dismissed. */ result: angular.IPromise<any>; /** * A promise that is resolved when a modal gets opened after downloading content's template and resolving all variables. */ opened: angular.IPromise<any>; /** * A promise that is resolved when a modal is rendered. */ rendered: angular.IPromise<any>; /** * A promise that is resolved when a modal is closed and the animation completes. */ closed: angular.IPromise<any>; } /** * @deprecated use IModalInstanceService instead. */ interface IModalServiceInstance extends IModalInstanceService { } interface IModalScope extends angular.IScope { /** * Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. * * @returns true if the modal was closed; otherwise false */ $dismiss(reason?: any): boolean; /** * Close the dialog resolving the promise to the given value. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. * * @returns true if the modal was closed; otherwise false */ $close(result?: any): boolean; } interface IModalSettings { /** * a path to a template representing modal's content */ templateUrl?: string | (() => string) | undefined; /** * inline template representing the modal's content */ template?: string | (() => string) | undefined; /** * a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope). * Defaults to `$rootScope`. */ scope?: angular.IScope | IModalScope | undefined; /** * a controller for a modal instance - it can initialize scope used by modal. * A controller can be injected with `$modalInstance` * If value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) */ controller?: string | Function | Array<string | Function> | undefined; /** * an alternative to the controller-as syntax, matching the API of directive definitions. * Requires the controller option to be provided as well */ controllerAs?: string | undefined; /** * When used with controllerAs and set to true, it will bind the controller properties onto the $scope directly. * * @default false */ bindToController?: boolean | undefined; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes * If property value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) */ resolve?: { [key: string]: string | Function | Array<string | Function> | Object } | undefined; /** * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. * * @default true */ animation?: boolean | undefined; /** * controls the presence of a backdrop * Allowed values: * - true (default) * - false (no backdrop) * - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window * * @default true */ backdrop?: boolean | string | undefined; /** * indicates whether the dialog should be closable by hitting the ESC key * * @default true */ keyboard?: boolean | undefined; /** * additional CSS class(es) to be added to a modal backdrop template */ backdropClass?: string | undefined; /** * additional CSS class(es) to be added to a modal window template */ windowClass?: string | undefined; /** * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. */ size?: string | undefined; /** * a path to a template overriding modal's window template */ windowTemplateUrl?: string | undefined; /** * The class added to the body element when the modal is opened. * * @default 'model-open' */ openedClass?: string | undefined; /** * CSS class(es) to be added to the top modal window. */ windowTopClass?: string | undefined; /** * Appends the modal to a specific element. * * @default 'body' */ appendTo?: angular.IAugmentedJQuery | undefined; /** * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set. * * It supports these bindings: * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}` * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}` * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`. * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details. */ component?: string | undefined; /** * Sets the `aria-describedby` property on the modal. * The string should be an id (without the leading '#') pointing to the element that describes your modal. * @type {string} * @memberOf IModalSettings */ ariaDescribedBy?: string | undefined; /** * Sets the `aria-labelledby` property on the modal. * The string should be an id (without the leading '#') pointing to the element that labels your modal. * @type {string} * @memberOf IModalSettings */ ariaLabelledBy?: string | undefined; } interface IModalStackService { /** * Opens a new modal instance. */ open(modalInstance: IModalInstanceService, modal: any): void; /** * Closes a modal instance with an optional result. */ close(modalInstance: IModalInstanceService, result?: any): void; /** * Dismisses a modal instance with an optional reason. */ dismiss(modalInstance: IModalInstanceService, reason?: any): void; /** * Dismiss all open modal instances with an optional reason that will be passed to each instance. */ dismissAll(reason?: any): void; /** * Gets the topmost modal instance that is open. */ getTop(): IModalStackedMapKeyValuePair; } interface IModalStackedMapKeyValuePair { key: IModalInstanceService; value: any; } interface IPaginationConfig { /** * Total number of items in all pages. */ totalItems?: number | undefined; /** * Maximum number of items per page. A value less than one indicates all items on one page. * * @default 10 */ itemsPerPage?: number | undefined; /** * Limit number for pagination size. * * @default: null */ maxSize?: number | undefined; /** * An optional expression assigned the total number of pages to display. * * @default angular.noop */ numPages?: number | undefined; /** * Whether to keep current page in the middle of the visible ones. * * @default true */ rotate?: boolean | undefined; /** * Whether to display Previous / Next buttons. * * @default true */ directionLinks?: boolean | undefined; /** * Text for Previous button. * * @default 'Previous' */ previousText?: string | undefined; /** * Text for Next button. * * @default 'Next' */ nextText?: string | undefined; /** * Whether to display First / Last buttons. * * @default false */ boundaryLinks?: boolean | undefined; /** * Whether to always display the first and last page numbers. If max-size is smaller than the number of pages, then the first and last page numbers are still shown with ellipses in-between as necessary. NOTE: max-size refers to the center of the range. This option may add up to 2 more numbers on each side of the displayed range for the end value and what would be an ellipsis but is replaced by a number because it is sequential. * * @default false */ boundaryLinkNumbers?: boolean | undefined; /** * Text for First button. * * @default 'First' */ firstText?: string | undefined; /** * Text for Last button. * * @default 'Last' */ lastText?: string | undefined; /** * Override the template for the component with a custom provided template. * * @default 'template/pagination/pagination.html' */ templateUrl?: string | undefined; /** * Also displays ellipses when rotate is true and max-size is smaller than the number of pages. * * @default false */ forceEllipses?: boolean | undefined; } interface IPagerConfig { /** * Whether to align each link to the sides. * * @default true */ align?: boolean | undefined; /** * Maximum number of items per page. A value less than one indicates all items on one page. * * @default 10 */ itemsPerPage?: number | undefined; /** * Text for Previous button. * * @default '« Previous' */ previousText?: string | undefined; /** * Text for Next button. * * @default 'Next »' */ nextText?: string | undefined; } interface IPositionCoordinates { width?: number | undefined; height?: number | undefined; top?: number | undefined; left?: number | undefined; } interface IPositionService { /** * Provides a read-only equivalent of jQuery's position function. */ position(element: JQuery): IPositionCoordinates; /** * Provides a read-only equivalent of jQuery's offset function. */ offset(element: JQuery): IPositionCoordinates; } interface IProgressConfig { /** * Whether bars use transitions to achieve the width change. * * @default: true */ animate?: boolean | undefined; /** * A number that specifies the total value of bars that is required. * * @default: 100 */ max?: number | undefined; } interface IRatingConfig { /** * Changes the number of icons. * * @default: 5 */ max?: number | undefined; /** * A variable used in the template to specify the state for selected icons. * * @default: null */ stateOn?: string | undefined; /** * A variable used in the template to specify the state for unselected icons. * * @default: null */ stateOff?: string | undefined; /** * An array of strings defining titles for all icons. * * @default: ["one", "two", "three", "four", "five"] */ titles?: Array<string> | undefined; } interface ITimepickerConfig { /** * Number of hours to increase or decrease when using a button. * * @default 1 */ hourStep?: number | undefined; /** * Number of minutes to increase or decrease when using a button. * * @default 1 */ minuteStep?: number | undefined; /** * Number of seconds to increase or decrease when using a button. * * @default 1 */ secondStep?: number | undefined; /** * Whether to display 12H or 24H mode. * * @default true */ showMeridian?: boolean | undefined; /** * Meridian labels based on locale. To override you must supply an array like ['AM', 'PM']. * * @default null */ meridians?: Array<string> | undefined; /** * Whether the user can type inside the hours & minutes input. * * @default false */ readonlyInput?: boolean | undefined; /** * Whether the user can scroll inside the hours & minutes input to increase or decrease it's values. * * @default true */ mousewheel?: boolean | undefined; /** * Whether the user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values. * * @default true */ arrowkeys?: boolean | undefined; /** * Shows spinner arrows above and below the inputs. * * @default true */ showSpinners?: boolean | undefined; /** * Show seconds input. * * @default false */ showSeconds?: boolean | undefined; /** * Add the ability to override the template used on the component. * * @default 'uib/template/timepicker/timepicker.html' */ templateUrl?: string | undefined; } interface ITooltipOptions { /** * Where to place it? Defaults to 'top', but also accepts 'right', 'bottom', or 'left'. * * @default 'top' */ placement?: string | undefined; /** * Should the modal fade in and out? * * @default true */ animation?: boolean | undefined; /** * Popup delay in milliseconds until it opens. * * @default 0 */ popupDelay?: number | undefined; /** * For how long should the tooltip remain open after the close trigger event? * * @default 0 */ popupCloseDelay?: number | undefined; /** * Should the tooltip be appended to `$body` instead of the parent element? * * @default false */ appendToBody?: boolean | undefined; /** * What should trigger a show of the tooltip? Supports a space separated list of event names. * * @default 'mouseenter' for tooltip, 'click' for popover */ trigger?: string | undefined; /** * Should an expression on the scope be used to load the content? * * @default false */ useContentExp?: boolean | undefined; } interface ITooltipProvider extends angular.IServiceProvider { /** * Provide a set of defaults for certain tooltip and popover attributes. */ options(value: ITooltipOptions): void; /** * Extends the default trigger mappings with mappings of your own. E.g. `{ 'openTrigger': 'closeTrigger' }`. */ setTriggers(triggers: Object): void; } /** * WARNING: $transition is now deprecated. Use $animate from ngAnimate instead. */ interface ITransitionService { /** * The browser specific animation event name. */ animationEndEventName: string; /** * The browser specific transition event name. */ transitionEndEventName: string; /** * Provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. * * @param element The DOMElement that will be animated * @param trigger The thing that will cause the transition to start: * - As a string, it represents the css class to be added to the element. * - As an object, it represents a hash of style attributes to be applied to the element. * - As a function, it represents a function to be called that will cause the transition to occur. * @param options Optional settings for the transition. * * @return A promise that is resolved when the transition finishes. */ (element: angular.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): angular.IPromise<angular.IAugmentedJQuery>; } interface ITransitionServiceOptions { animation?: boolean | undefined; } } }
the_stack
* @module Utilities */ // cSpell:ignore configurableui clientservices import { Store } from "redux"; import { GuidString, Logger, ProcessDetector } from "@itwin/core-bentley"; import { Localization, RpcActivity } from "@itwin/core-common"; import { IModelApp, IModelConnection, SnapMode, ViewState } from "@itwin/core-frontend"; import { Presentation } from "@itwin/presentation-frontend"; import { TelemetryEvent } from "@itwin/core-telemetry"; import { getClassName, UiAdmin, UiError, UiEvent } from "@itwin/appui-abstract"; import { LocalStateStorage, SettingsManager, UiStateStorage } from "@itwin/core-react"; import { UiIModelComponents } from "@itwin/imodel-components-react"; import { BackstageManager } from "./backstage/BackstageManager"; import { ChildWindowManager } from "./childwindow/ChildWindowManager"; import { ConfigurableUiManager } from "./configurableui/ConfigurableUiManager"; import { ConfigurableUiActionId } from "./configurableui/state"; import { FrameworkState } from "./redux/FrameworkState"; import { CursorMenuData, PresentationSelectionScope, SessionStateActionId } from "./redux/SessionState"; import { StateManager } from "./redux/StateManager"; import { HideIsolateEmphasizeActionHandler, HideIsolateEmphasizeManager } from "./selection/HideIsolateEmphasizeManager"; import { SyncUiEventDispatcher, SyncUiEventId } from "./syncui/SyncUiEventDispatcher"; import { SYSTEM_PREFERRED_COLOR_THEME, WIDGET_OPACITY_DEFAULT } from "./theme/ThemeManager"; import * as keyinPaletteTools from "./tools/KeyinPaletteTools"; import * as openSettingTools from "./tools/OpenSettingsTool"; import * as restoreLayoutTools from "./tools/RestoreLayoutTool"; import * as toolSettingTools from "./tools/ToolSettingsTools"; import { UiShowHideManager, UiShowHideSettingsProvider } from "./utils/UiShowHideManager"; import { WidgetManager } from "./widgets/WidgetManager"; import { FrontstageManager } from "./frontstage/FrontstageManager"; // cSpell:ignore Mobi /** Defined that available UI Versions. It is recommended to always use the latest version available. * @public */ export type FrameworkVersionId = "1" | "2"; /** Interface to be implemented but any classes that wants to load their user settings when the UiStateEntry storage class is set. * @public */ export interface UserSettingsProvider { /** Unique provider Id */ providerId: string; /** Function to load settings from settings storage */ loadUserSettings(storage: UiStateStorage): Promise<void>; } /** UiVisibility Event Args interface. * @public */ export interface UiVisibilityEventArgs { visible: boolean; } /** UiVisibility Event class. * @public */ export class UiVisibilityChangedEvent extends UiEvent<UiVisibilityEventArgs> { } /** FrameworkVersion Changed Event Args interface. * @internal */ export interface FrameworkVersionChangedEventArgs { oldVersion: FrameworkVersionId; version: FrameworkVersionId; } /** FrameworkVersion Changed Event class. * @internal */ export class FrameworkVersionChangedEvent extends UiEvent<FrameworkVersionChangedEventArgs> { } /** TrackingTime time argument used by our feature tracking manager as an option argument to the TelemetryClient * @internal */ export interface TrackingTime { startTime: Date; endTime: Date; } /** * Manages the Redux store, localization service and iModel, Project and Login services for the ui-framework package. * @public */ export class UiFramework { private static _initialized = false; private static _store?: Store<any>; private static _complaint = "UiFramework not initialized"; private static _frameworkStateKeyInStore: string = "frameworkState"; // default name private static _backstageManager?: BackstageManager; private static _widgetManager?: WidgetManager; private static _uiVersion: FrameworkVersionId = "2"; private static _hideIsolateEmphasizeActionHandler?: HideIsolateEmphasizeActionHandler; /** this provides a default state storage handler */ private static _uiStateStorage: UiStateStorage = new LocalStateStorage(); private static _settingsManager?: SettingsManager; private static _uiSettingsProviderRegistry: Map<string, UserSettingsProvider> = new Map<string, UserSettingsProvider>(); private static _PopupWindowManager = new ChildWindowManager(); public static useDefaultPopoutUrl = false; /** @public */ public static get childWindowManager(): ChildWindowManager { return UiFramework._PopupWindowManager; } /** Registers class that will be informed when the UserSettingsStorage location has been set or changed. This allows * classes to load any previously saved settings from the new storage location. Common storage locations are the browser's * local storage, or the iTwin Product Settings cloud storage available via the SettingsAdmin see `IModelApp.settingsAdmin`. * @beta */ public static registerUserSettingsProvider(entry: UserSettingsProvider) { if (this._uiSettingsProviderRegistry.has(entry.providerId)) return false; this._uiSettingsProviderRegistry.set(entry.providerId, entry); return true; } /** Get Show Ui event. * @public */ public static readonly onUiVisibilityChanged = new UiVisibilityChangedEvent(); /** * Called by the application to initialize the UiFramework. Also initializes UIIModelComponents, UiComponents, UiCore. * @param store The single Redux store created by the host application. If this is `undefined` then it is assumed that the [[StateManager]] is being used to provide the Redux store. * @param frameworkStateKey The name of the key used by the app when adding the UiFramework state into the Redux store. If not defined "frameworkState" is assumed. This value is ignored if [[StateManager]] is being used. The StateManager use "frameworkState". * @param startInUi1Mode Used for legacy applications to start up in the deprecated UI 1 mode. This should not set by newer applications. */ public static async initialize(store: Store<any> | undefined, frameworkStateKey?: string, startInUi1Mode?: boolean): Promise<void> { return this.initializeEx(store, frameworkStateKey, startInUi1Mode); } /** * Called by the application to initialize the UiFramework. Also initializes UIIModelComponents, UiComponents, UiCore. * @param store The single Redux store created by the host application. If this is `undefined` then it is assumed that the [[StateManager]] is being used to provide the Redux store. * @param frameworkStateKey The name of the key used by the app when adding the UiFramework state into the Redux store. If not defined "frameworkState" is assumed. This value is ignored if [[StateManager]] is being used. The StateManager use "frameworkState". * @param startInUi1Mode Used for legacy applications to start up in the deprecated UI 1 mode. This should not set by newer applications. * * @internal */ public static async initializeEx(store: Store<any> | undefined, frameworkStateKey?: string, startInUi1Mode?: boolean): Promise<void> { if (UiFramework._initialized) { Logger.logInfo(UiFramework.loggerCategory(UiFramework), `UiFramework.initialize already called`); return; } /* if store is undefined then the StateManager class should have been initialized by parent app and the apps default set of reducers registered with it. If the app has no reducers to add and does not initialize a StateManager then just initialize the StateManager with the default framework reducer now */ if (undefined === store && !StateManager.isInitialized(true)) new StateManager(); UiFramework._store = store; // ignore setting _frameworkStateKeyInStore if not using store if (frameworkStateKey && store) UiFramework._frameworkStateKeyInStore = frameworkStateKey; if (startInUi1Mode) UiFramework.store.dispatch({ type: ConfigurableUiActionId.SetFrameworkVersion, payload: "1" }); // set up namespace and register all tools from package const frameworkNamespace = IModelApp.localization?.registerNamespace(UiFramework.localizationNamespace); [ restoreLayoutTools, keyinPaletteTools, openSettingTools, toolSettingTools, ].forEach((tool) => IModelApp.tools.registerModule(tool, this.localizationNamespace)); UiFramework._backstageManager = new BackstageManager(); UiFramework._hideIsolateEmphasizeActionHandler = new HideIsolateEmphasizeManager(); // this allows user to override the default HideIsolateEmphasizeManager implementation. UiFramework._widgetManager = new WidgetManager(); // Initialize ui-imodel-components, ui-components, ui-core & ui-abstract await UiIModelComponents.initialize(); UiFramework.settingsManager.onSettingsProvidersChanged.addListener(() => { SyncUiEventDispatcher.dispatchSyncUiEvent(SyncUiEventId.SettingsProvidersChanged); }); // Initialize the MessagePresenter interface in UiAdmin for Editor notifications UiAdmin.messagePresenter = IModelApp.notifications; UiFramework._initialized = true; // initialize any standalone settings providers that don't need to have defaults set by iModelApp UiShowHideSettingsProvider.initialize(); ConfigurableUiManager.initialize(); return frameworkNamespace; } /** Un-registers the UiFramework internationalization service namespace */ public static terminate() { UiFramework._store = undefined; UiFramework._frameworkStateKeyInStore = "frameworkState"; if (StateManager.isInitialized(true)) StateManager.clearStore(); // istanbul ignore next IModelApp.localization?.unregisterNamespace(UiFramework.localizationNamespace); UiFramework._backstageManager = undefined; UiFramework._widgetManager = undefined; UiFramework._hideIsolateEmphasizeActionHandler = undefined; UiFramework._settingsManager = undefined; UiIModelComponents.terminate(); UiShowHideManager.terminate(); UiFramework._initialized = false; } /** Determines if UiFramework has been initialized */ public static get initialized(): boolean { return UiFramework._initialized; } /** Property that returns the SettingManager used by AppUI-based applications. * @public */ public static get settingsManager() { if (undefined === UiFramework._settingsManager) UiFramework._settingsManager = new SettingsManager(); return UiFramework._settingsManager; } /** @public */ public static get frameworkStateKey(): string { return UiFramework._frameworkStateKeyInStore; } /** The UiFramework state maintained by Redux * @public */ public static get frameworkState(): FrameworkState | undefined { try { // eslint-disable-next-line dot-notation return UiFramework.store.getState()[UiFramework.frameworkStateKey]; } catch (_e) { return undefined; } } /** The Redux store */ public static get store(): Store<any> { if (UiFramework._store) return UiFramework._store; // istanbul ignore else if (!StateManager.isInitialized(true)) throw new UiError(UiFramework.loggerCategory(this), `Error trying to access redux store before either store or StateManager has been initialized.`); // istanbul ignore next return StateManager.store; } /** The internationalization service created by the app. * @internal */ public static get localization(): Localization { // istanbul ignore next if (!IModelApp.localization) throw new UiError(UiFramework.loggerCategory(this), `IModelApp.localization has not been defined.`); return IModelApp.localization; } /** The internationalization service namespace. */ public static get localizationNamespace(): string { return "UiFramework"; } /** @public */ public static get backstageManager(): BackstageManager { // istanbul ignore next if (!UiFramework._backstageManager) throw new UiError(UiFramework.loggerCategory(this), UiFramework._complaint); return UiFramework._backstageManager; } /** @alpha */ public static get hideIsolateEmphasizeActionHandler(): HideIsolateEmphasizeActionHandler { // istanbul ignore next if (!UiFramework._hideIsolateEmphasizeActionHandler) throw new UiError(UiFramework.loggerCategory(this), UiFramework._complaint); return UiFramework._hideIsolateEmphasizeActionHandler; } /** @alpha */ public static setHideIsolateEmphasizeActionHandler(handler: HideIsolateEmphasizeActionHandler | undefined) { // istanbul ignore else if (handler) UiFramework._hideIsolateEmphasizeActionHandler = handler; else UiFramework._hideIsolateEmphasizeActionHandler = new HideIsolateEmphasizeManager(); } /** @alpha */ public static get widgetManager(): WidgetManager { // istanbul ignore next if (!UiFramework._widgetManager) throw new UiError(UiFramework.loggerCategory(this), UiFramework._complaint); return UiFramework._widgetManager; } /** Calls localization.getLocalizedStringWithNamespace with the "UiFramework" namespace. Do NOT include the namespace in the key. * @internal */ public static translate(key: string | string[]): string { return IModelApp.localization.getLocalizedStringWithNamespace(UiFramework.localizationNamespace, key); } /** @internal */ public static get packageName(): string { return "appui-react"; } /** @internal */ public static loggerCategory(obj: any): string { const className = getClassName(obj); const category = UiFramework.packageName + (className ? `.${className}` : ""); return category; } public static dispatchActionToStore(type: string, payload: any, immediateSync = false) { UiFramework.store.dispatch({ type, payload }); if (immediateSync) SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(type); else SyncUiEventDispatcher.dispatchSyncUiEvent(type); } public static setAccudrawSnapMode(snapMode: SnapMode) { UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetSnapMode, snapMode, true); } public static getAccudrawSnapMode(): SnapMode { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.snapMode : /* istanbul ignore next */ SnapMode.NearestKeypoint; } public static getActiveSelectionScope(): string { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.activeSelectionScope : /* istanbul ignore next */ "element"; } public static setActiveSelectionScope(selectionScopeId: string): void { // istanbul ignore else if (UiFramework.frameworkState) { const foundIndex = UiFramework.frameworkState.sessionState.availableSelectionScopes.findIndex((selectionScope: PresentationSelectionScope) => selectionScope.id === selectionScopeId); if (-1 !== foundIndex) { const scope = UiFramework.frameworkState.sessionState.availableSelectionScopes[foundIndex]; UiFramework.dispatchActionToStore(SessionStateActionId.SetSelectionScope, scope.id); Presentation.selection.scopes.activeScope = scope.id; } } } /** @public */ public static openCursorMenu(menuData: CursorMenuData | undefined): void { UiFramework.dispatchActionToStore(SessionStateActionId.UpdateCursorMenu, menuData); } /** @public */ public static closeCursorMenu(): void { UiFramework.dispatchActionToStore(SessionStateActionId.UpdateCursorMenu, undefined); } /** @public */ public static getCursorMenuData(): CursorMenuData | undefined { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.cursorMenuData : /* istanbul ignore next */ undefined; } public static getActiveIModelId(): string { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.iModelId : /* istanbul ignore next */ ""; } public static setActiveIModelId(iModelId: string): void { UiFramework.dispatchActionToStore(SessionStateActionId.SetActiveIModelId, iModelId); } public static setIModelConnection(iModelConnection: IModelConnection | undefined, immediateSync = false) { const oldConnection = UiFramework.getIModelConnection(); if (oldConnection !== iModelConnection) { if (oldConnection?.iModelId) FrontstageManager.clearFrontstageDefsForIModelId(oldConnection.iModelId); oldConnection && undefined === iModelConnection && SyncUiEventDispatcher.clearConnectionEvents(oldConnection); iModelConnection && SyncUiEventDispatcher.initializeConnectionEvents(iModelConnection); UiFramework.dispatchActionToStore(SessionStateActionId.SetIModelConnection, iModelConnection, immediateSync); } UiFramework.setActiveIModelId(iModelConnection?.iModelId ?? ""); } public static getIModelConnection(): IModelConnection | undefined { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.iModelConnection : /* istanbul ignore next */ undefined; } /** Called by iModelApp to initialize saved UI state from registered UseSettingsProviders * @public */ public static async initializeStateFromUserSettingsProviders(immediateSync = false) { // let any registered providers to load values from the new storage location const providerKeys = [...this._uiSettingsProviderRegistry.keys()]; for await (const key of providerKeys) { await this._uiSettingsProviderRegistry.get(key)!.loadUserSettings(UiFramework._uiStateStorage); } // istanbul ignore next if (immediateSync) SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(SyncUiEventId.UiStateStorageChanged); else SyncUiEventDispatcher.dispatchSyncUiEvent(SyncUiEventId.UiStateStorageChanged); } /** @public */ public static async setUiStateStorage(storage: UiStateStorage, immediateSync = false) { if (UiFramework._uiStateStorage === storage) return; UiFramework._uiStateStorage = storage; await this.initializeStateFromUserSettingsProviders(immediateSync); } /** The UI Settings Storage is a convenient wrapper around Local Storage to assist in caching state information across user sessions. * It was previously used to conflate both the state information across session and the information driven directly from user explicit action, * which are now handled with user preferences. * @public */ public static getUiStateStorage(): UiStateStorage { return UiFramework._uiStateStorage; } public static setDefaultIModelViewportControlId(iModelViewportControlId: string, immediateSync = false) { UiFramework.dispatchActionToStore(SessionStateActionId.SetDefaultIModelViewportControlId, iModelViewportControlId, immediateSync); } public static getDefaultIModelViewportControlId(): string | undefined { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.defaultIModelViewportControlId : /* istanbul ignore next */ undefined; } public static setDefaultViewId(viewId: string, immediateSync = false) { UiFramework.dispatchActionToStore(SessionStateActionId.SetDefaultViewId, viewId, immediateSync); } public static getDefaultViewId(): string | undefined { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.defaultViewId : /* istanbul ignore next */ undefined; } public static setDefaultViewState(viewState: ViewState, immediateSync = false) { UiFramework.dispatchActionToStore(SessionStateActionId.SetDefaultViewState, viewState, immediateSync); } public static getDefaultViewState(): ViewState | undefined { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.defaultViewState : /* istanbul ignore next */ undefined; } /** @public */ public static getAvailableSelectionScopes(): PresentationSelectionScope[] { return UiFramework.frameworkState ? UiFramework.frameworkState.sessionState.availableSelectionScopes : /* istanbul ignore next */ [{ id: "element", label: "Element" } as PresentationSelectionScope]; } public static getIsUiVisible() { return UiShowHideManager.isUiVisible; } public static setIsUiVisible(visible: boolean) { if (UiShowHideManager.isUiVisible !== visible) { UiShowHideManager.isUiVisible = visible; UiFramework.onUiVisibilityChanged.emit({ visible }); } } public static setColorTheme(theme: string) { if (UiFramework.getColorTheme() === theme) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetTheme, theme, true); } public static getColorTheme(): string { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.theme : /* istanbul ignore next */ SYSTEM_PREFERRED_COLOR_THEME; } public static setWidgetOpacity(opacity: number) { if (UiFramework.getWidgetOpacity() === opacity) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetWidgetOpacity, opacity, true); } public static getWidgetOpacity(): number { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.widgetOpacity : /* istanbul ignore next */ WIDGET_OPACITY_DEFAULT; } public static isMobile() { // eslint-disable-line @itwin/prefer-get return ProcessDetector.isMobileBrowser; } /** Returns the Ui Version. * @public */ public static get uiVersion(): FrameworkVersionId { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.frameworkVersion : this._uiVersion; } public static setUiVersion(version: FrameworkVersionId) { if (UiFramework.uiVersion === version) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetFrameworkVersion, version === "1" ? "1" : "2", true); } public static get showWidgetIcon(): boolean { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.showWidgetIcon : /* istanbul ignore next */ false; } public static setShowWidgetIcon(value: boolean) { if (UiFramework.showWidgetIcon === value) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetShowWidgetIcon, value, true); } /** Animate Tool Settings on appear */ public static get animateToolSettings(): boolean { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.animateToolSettings : /* istanbul ignore next */ false; } public static setAnimateToolSettings(value: boolean) { if (UiFramework.animateToolSettings === value) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.AnimateToolSettings, value, true); } /** @alpha */ public static get autoCollapseUnpinnedPanels(): boolean { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.autoCollapseUnpinnedPanels : /* istanbul ignore next */ false; } /** Method used to enable the automatic closing of an unpinned widget panel as soon as the * mouse leaves the widget panel. The default behavior is to require a mouse click outside * the panel before it is closed. * @alpha */ public static setAutoCollapseUnpinnedPanels(value: boolean) { if (UiFramework.autoCollapseUnpinnedPanels === value) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.AutoCollapseUnpinnedPanels, value, true); } public static get useDragInteraction(): boolean { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.useDragInteraction : false; } public static setUseDragInteraction(useDragInteraction: boolean) { UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetDragInteraction, useDragInteraction, true); } /** Returns the variable controlling whether the overlay is displayed in a Viewport * @public */ public static get viewOverlayDisplay() { return UiFramework.frameworkState ? UiFramework.frameworkState.configurableUiState.viewOverlayDisplay : /* istanbul ignore next */ true; } /** Set the variable that controls display of the view overlay. Applies to all viewports in the app * @public */ public static setViewOverlayDisplay(display: boolean) { if (UiFramework.viewOverlayDisplay === display) return; UiFramework.dispatchActionToStore(ConfigurableUiActionId.SetViewOverlayDisplay, display); } /** Send logging message to the telemetry system * @internal */ // istanbul ignore next public static async postTelemetry(eventName: string, eventId?: GuidString, iTwinId?: GuidString, iModeId?: GuidString, changeSetId?: string, time?: TrackingTime, additionalProperties?: { [key: string]: any }): Promise<void> { if (!IModelApp.authorizationClient) return; try { const activity: RpcActivity = { sessionId: IModelApp.sessionId, activityId: "", applicationId: IModelApp.applicationId, applicationVersion: IModelApp.applicationVersion, accessToken: (await IModelApp.authorizationClient.getAccessToken()) ?? "", }; const telemetryEvent = new TelemetryEvent(eventName, eventId, iTwinId, iModeId, changeSetId, time, additionalProperties); await IModelApp.telemetry.postTelemetry(activity, telemetryEvent); } catch { } } /** Determines whether a ContextMenu is open * @alpha * */ public static get isContextMenuOpen(): boolean { const contextMenu = document.querySelector("div.core-context-menu-opened"); return contextMenu !== null && contextMenu !== undefined; } }
the_stack
import { AVRInterruptConfig, CPU } from '../cpu/cpu'; import { u8 } from '../types'; export interface AVRExternalInterrupt { EICRA: u8; EICRB: u8; EIMSK: u8; EIFR: u8; index: u8; // 0..7 interrupt: u8; } export interface AVRPinChangeInterrupt { PCIE: u8; // bit index in PCICR/PCIFR PCICR: u8; PCIFR: u8; PCMSK: u8; pinChangeInterrupt: u8; mask: u8; offset: u8; } export interface AVRPortConfig { // Register addresses PIN: u8; DDR: u8; PORT: u8; // Interrupt settings pinChange?: AVRPinChangeInterrupt; externalInterrupts: (AVRExternalInterrupt | null)[]; } export const INT0: AVRExternalInterrupt = { EICRA: 0x69, EICRB: 0, EIMSK: 0x3d, EIFR: 0x3c, index: 0, interrupt: 2, }; export const INT1: AVRExternalInterrupt = { EICRA: 0x69, EICRB: 0, EIMSK: 0x3d, EIFR: 0x3c, index: 1, interrupt: 4, }; export const PCINT0 = { PCIE: 0, PCICR: 0x68, PCIFR: 0x3b, PCMSK: 0x6b, pinChangeInterrupt: 6, mask: 0xff, offset: 0, }; export const PCINT1 = { PCIE: 1, PCICR: 0x68, PCIFR: 0x3b, PCMSK: 0x6c, pinChangeInterrupt: 8, mask: 0xff, offset: 0, }; export const PCINT2 = { PCIE: 2, PCICR: 0x68, PCIFR: 0x3b, PCMSK: 0x6d, pinChangeInterrupt: 10, mask: 0xff, offset: 0, }; export type GPIOListener = (value: u8, oldValue: u8) => void; export type ExternalClockListener = (pinValue: boolean) => void; export const portAConfig: AVRPortConfig = { PIN: 0x20, DDR: 0x21, PORT: 0x22, externalInterrupts: [], }; export const portBConfig: AVRPortConfig = { PIN: 0x23, DDR: 0x24, PORT: 0x25, // Interrupt settings pinChange: PCINT0, externalInterrupts: [], }; export const portCConfig: AVRPortConfig = { PIN: 0x26, DDR: 0x27, PORT: 0x28, // Interrupt settings pinChange: PCINT1, externalInterrupts: [], }; export const portDConfig: AVRPortConfig = { PIN: 0x29, DDR: 0x2a, PORT: 0x2b, // Interrupt settings pinChange: PCINT2, externalInterrupts: [null, null, INT0, INT1], }; export const portEConfig: AVRPortConfig = { PIN: 0x2c, DDR: 0x2d, PORT: 0x2e, externalInterrupts: [], }; export const portFConfig: AVRPortConfig = { PIN: 0x2f, DDR: 0x30, PORT: 0x31, externalInterrupts: [], }; export const portGConfig: AVRPortConfig = { PIN: 0x32, DDR: 0x33, PORT: 0x34, externalInterrupts: [], }; export const portHConfig: AVRPortConfig = { PIN: 0x100, DDR: 0x101, PORT: 0x102, externalInterrupts: [], }; export const portJConfig: AVRPortConfig = { PIN: 0x103, DDR: 0x104, PORT: 0x105, externalInterrupts: [], }; export const portKConfig: AVRPortConfig = { PIN: 0x106, DDR: 0x107, PORT: 0x108, externalInterrupts: [], }; export const portLConfig: AVRPortConfig = { PIN: 0x109, DDR: 0x10a, PORT: 0x10b, externalInterrupts: [], }; export enum PinState { Low, High, Input, InputPullUp, } /* This mechanism allows timers to override specific GPIO pins */ export enum PinOverrideMode { None, Enable, Set, Clear, Toggle, } enum InterruptMode { LowLevel, Change, FallingEdge, RisingEdge, } export class AVRIOPort { readonly externalClockListeners: (ExternalClockListener | null)[] = []; private readonly externalInts: (AVRInterruptConfig | null)[]; private readonly PCINT: AVRInterruptConfig | null; private listeners: GPIOListener[] = []; private pinValue: u8 = 0; private overrideMask: u8 = 0xff; private overrideValue: u8 = 0; private lastValue: u8 = 0; private lastDdr: u8 = 0; private lastPin: u8 = 0; constructor(private cpu: CPU, readonly portConfig: Readonly<AVRPortConfig>) { cpu.gpioPorts.add(this); cpu.gpioByPort[portConfig.PORT] = this; cpu.writeHooks[portConfig.DDR] = (value: u8) => { const portValue = cpu.data[portConfig.PORT]; cpu.data[portConfig.DDR] = value; this.writeGpio(portValue, value); this.updatePinRegister(value); return true; }; cpu.writeHooks[portConfig.PORT] = (value: u8) => { const ddrMask = cpu.data[portConfig.DDR]; cpu.data[portConfig.PORT] = value; this.writeGpio(value, ddrMask); this.updatePinRegister(ddrMask); return true; }; cpu.writeHooks[portConfig.PIN] = (value: u8, oldValue, addr, mask) => { // Writing to 1 PIN toggles PORT bits const oldPortValue = cpu.data[portConfig.PORT]; const ddrMask = cpu.data[portConfig.DDR]; const portValue = oldPortValue ^ (value & mask); cpu.data[portConfig.PORT] = portValue; this.writeGpio(portValue, ddrMask); this.updatePinRegister(ddrMask); return true; }; // External interrupts const { externalInterrupts } = portConfig; this.externalInts = externalInterrupts.map((externalConfig) => externalConfig ? { address: externalConfig.interrupt, flagRegister: externalConfig.EIFR, flagMask: 1 << externalConfig.index, enableRegister: externalConfig.EIMSK, enableMask: 1 << externalConfig.index, } : null ); const EICRA = externalInterrupts.find((item) => item && item.EICRA)?.EICRA ?? 0; this.attachInterruptHook(EICRA); const EICRB = externalInterrupts.find((item) => item && item.EICRB)?.EICRB ?? 0; this.attachInterruptHook(EICRB); const EIMSK = externalInterrupts.find((item) => item && item.EIMSK)?.EIMSK ?? 0; this.attachInterruptHook(EIMSK, 'mask'); const EIFR = externalInterrupts.find((item) => item && item.EIFR)?.EIFR ?? 0; this.attachInterruptHook(EIFR, 'flag'); // Pin change interrupts const { pinChange } = portConfig; this.PCINT = pinChange ? { address: pinChange.pinChangeInterrupt, flagRegister: pinChange.PCIFR, flagMask: 1 << pinChange.PCIE, enableRegister: pinChange.PCICR, enableMask: 1 << pinChange.PCIE, } : null; if (pinChange) { const { PCIFR, PCMSK } = pinChange; cpu.writeHooks[PCIFR] = (value) => { for (const gpio of this.cpu.gpioPorts) { const { PCINT } = gpio; if (PCINT) { cpu.clearInterruptByFlag(PCINT, value); } } return true; }; cpu.writeHooks[PCMSK] = (value) => { cpu.data[PCMSK] = value; for (const gpio of this.cpu.gpioPorts) { const { PCINT } = gpio; if (PCINT) { cpu.updateInterruptEnable(PCINT, value); } } return true; }; } } addListener(listener: GPIOListener) { this.listeners.push(listener); } removeListener(listener: GPIOListener) { this.listeners = this.listeners.filter((l) => l !== listener); } /** * Get the state of a given GPIO pin * * @param index Pin index to return from 0 to 7 * @returns PinState.Low or PinState.High if the pin is set to output, PinState.Input if the pin is set * to input, and PinState.InputPullUp if the pin is set to input and the internal pull-up resistor has * been enabled. */ pinState(index: number) { const ddr = this.cpu.data[this.portConfig.DDR]; const port = this.cpu.data[this.portConfig.PORT]; const bitMask = 1 << index; if (ddr & bitMask) { return this.lastValue & bitMask ? PinState.High : PinState.Low; } else { return port & bitMask ? PinState.InputPullUp : PinState.Input; } } /** * Sets the input value for the given pin. This is the value that * will be returned when reading from the PIN register. */ setPin(index: number, value: boolean) { const bitMask = 1 << index; this.pinValue &= ~bitMask; if (value) { this.pinValue |= bitMask; } this.updatePinRegister(this.cpu.data[this.portConfig.DDR]); } /** * Internal method - do not call this directly! * Used by the timer compare output units to override GPIO pins. */ timerOverridePin(pin: u8, mode: PinOverrideMode) { const { cpu, portConfig } = this; const pinMask = 1 << pin; if (mode === PinOverrideMode.None) { this.overrideMask |= pinMask; this.overrideValue &= ~pinMask; } else { this.overrideMask &= ~pinMask; switch (mode) { case PinOverrideMode.Enable: this.overrideValue &= ~pinMask; this.overrideValue |= cpu.data[portConfig.PORT] & pinMask; break; case PinOverrideMode.Set: this.overrideValue |= pinMask; break; case PinOverrideMode.Clear: this.overrideValue &= ~pinMask; break; case PinOverrideMode.Toggle: this.overrideValue ^= pinMask; break; } } const ddrMask = cpu.data[portConfig.DDR]; this.writeGpio(cpu.data[portConfig.PORT], ddrMask); this.updatePinRegister(ddrMask); } private updatePinRegister(ddr: u8) { const newPin = (this.pinValue & ~ddr) | (this.lastValue & ddr); this.cpu.data[this.portConfig.PIN] = newPin; if (this.lastPin !== newPin) { for (let index = 0; index < 8; index++) { if ((newPin & (1 << index)) !== (this.lastPin & (1 << index))) { const value = !!(newPin & (1 << index)); this.toggleInterrupt(index, value); this.externalClockListeners[index]?.(value); } } this.lastPin = newPin; } } private toggleInterrupt(pin: u8, risingEdge: boolean) { const { cpu, portConfig, externalInts, PCINT } = this; const { externalInterrupts, pinChange } = portConfig; const externalConfig = externalInterrupts[pin]; const external = externalInts[pin]; if (external && externalConfig) { const { index, EICRA, EICRB, EIMSK } = externalConfig; if (cpu.data[EIMSK] & (1 << index)) { const configRegister = index >= 4 ? EICRB : EICRA; const configShift = (index % 4) * 2; const configuration = (cpu.data[configRegister] >> configShift) & 0x3; let generateInterrupt = false; external.constant = false; switch (configuration) { case InterruptMode.LowLevel: generateInterrupt = !risingEdge; external.constant = true; break; case InterruptMode.Change: generateInterrupt = true; break; case InterruptMode.FallingEdge: generateInterrupt = !risingEdge; break; case InterruptMode.RisingEdge: generateInterrupt = risingEdge; break; } if (generateInterrupt) { cpu.setInterruptFlag(external); } else if (external.constant) { cpu.clearInterrupt(external, true); } } } if (pinChange && PCINT && pinChange.mask & (1 << pin)) { const { PCMSK } = pinChange; if (cpu.data[PCMSK] & (1 << (pin + pinChange.offset))) { cpu.setInterruptFlag(PCINT); } } } private attachInterruptHook(register: number, registerType: 'flag' | 'mask' | 'other' = 'other') { if (!register) { return; } const { cpu } = this; cpu.writeHooks[register] = (value: u8) => { if (registerType !== 'flag') { cpu.data[register] = value; } for (const gpio of cpu.gpioPorts) { for (const external of gpio.externalInts) { if (external && registerType === 'mask') { cpu.updateInterruptEnable(external, value); } if (external && !external.constant && registerType === 'flag') { cpu.clearInterruptByFlag(external, value); } } gpio.checkExternalInterrupts(); } return true; }; } private checkExternalInterrupts() { const { cpu } = this; const { externalInterrupts } = this.portConfig; for (let pin = 0; pin < 8; pin++) { const external = externalInterrupts[pin]; if (!external) { continue; } const pinValue = !!(this.lastPin & (1 << pin)); const { index, EICRA, EICRB, EIMSK, EIFR, interrupt } = external; if (!(cpu.data[EIMSK] & (1 << index)) || pinValue) { continue; } const configRegister = index >= 4 ? EICRB : EICRA; const configShift = (index % 4) * 2; const configuration = (cpu.data[configRegister] >> configShift) & 0x3; if (configuration === InterruptMode.LowLevel) { cpu.queueInterrupt({ address: interrupt, flagRegister: EIFR, flagMask: 1 << index, enableRegister: EIMSK, enableMask: 1 << index, constant: true, }); } } } private writeGpio(value: u8, ddr: u8) { const newValue = (((value & this.overrideMask) | this.overrideValue) & ddr) | (value & ~ddr); const prevValue = this.lastValue; if (newValue !== prevValue || ddr !== this.lastDdr) { this.lastValue = newValue; this.lastDdr = ddr; for (const listener of this.listeners) { listener(newValue, prevValue); } } } }
the_stack
import { createHmac } from 'crypto' import { encode } from 'querystring' import { Context, camelize, Random, sanitize, Logger, Session, Dict } from 'koishi' import { CommonPayload, addListeners, defaultEvents, EventConfig } from './events' import { Config, GitHub, ReplyHandler, ReplySession, ReplyPayloads } from './server' import axios, { Method } from 'axios' export * from './server' declare module 'koishi' { interface Modules { github: typeof import('.') } } export const name = 'GitHub' export const using = ['database'] as const const logger = new Logger('github') export function apply(ctx: Context, config: Config) { config.path = sanitize(config.path) const { app, database } = ctx const { appId, redirect } = config const subscriptions: Dict<Dict<EventConfig>> = {} ctx.plugin(GitHub, config) ctx.command('github', 'GitHub 相关功能').alias('gh') .action(({ session }) => session.execute('help github', true)) const tokens: Dict<string> = {} ctx.router.get(config.path + '/authorize', async (ctx) => { const token = ctx.query.state if (!token || Array.isArray(token)) return ctx.status = 400 const id = tokens[token] if (!id) return ctx.status = 403 delete tokens[token] const { code, state } = ctx.query const data = await ctx.github.getTokens({ code, state, redirect_uri: redirect }) await database.setUser('id', id, { ghAccessToken: data.access_token, ghRefreshToken: data.refresh_token, }) return ctx.status = 200 }) ctx.command('github.authorize <user>', 'GitHub 授权') .alias('github.auth') .userFields(['id']) .action(async ({ session }, user) => { if (!user) return '请输入用户名。' const token = Random.id() tokens[token] = session.user.id const url = 'https://github.com/login/oauth/authorize?' + encode({ client_id: appId, state: token, redirect_uri: redirect, scope: 'admin:repo_hook,repo', login: user, }) return '请点击下面的链接继续操作:\n' + url }) const repoRegExp = /^[\w.-]+\/[\w.-]+$/ ctx.command('github.repos [name]', '管理监听的仓库') .userFields(['ghAccessToken', 'ghRefreshToken']) .option('add', '-a 监听一个新的仓库') .option('delete', '-d 移除已监听的仓库') .option('subscribe', '-s 添加完成后更新到订阅') .action(async ({ session, options }, name) => { if (options.add || options.delete) { if (!name) return '请输入仓库名。' if (!repoRegExp.test(name)) return '请输入正确的仓库名。' if (!session.user.ghAccessToken) { return ctx.github.authorize(session, '要使用此功能,请对机器人进行授权。输入你的 GitHub 用户名。') } name = name.toLowerCase() const url = `https://api.github.com/repos/${name}/hooks` const [repo] = await ctx.database.get('github', [name]) if (options.add) { if (repo) return `已经添加过仓库 ${name}。` const secret = Random.id() let data: any try { data = await ctx.github.request('POST', url, session, { events: ['*'], config: { secret, url: app.options.selfUrl + config.path + '/webhook', }, }) } catch (err) { if (!axios.isAxiosError(err)) throw err if (err.response?.status === 404) { return '仓库不存在或您无权访问。' } else if (err.response?.status === 403) { return '第三方访问受限,请尝试授权此应用。\nhttps://docs.github.com/articles/restricting-access-to-your-organization-s-data/' } else { logger.warn(err) return '由于未知原因添加仓库失败。' } } await ctx.database.create('github', { name, id: data.id, secret }) if (!options.subscribe) return '添加仓库成功!' return session.execute({ name: 'github', args: [name], options: { add: true }, }, true) } else { if (!repo) return `尚未添加过仓库 ${name}。` try { await ctx.github.request('DELETE', `${url}/${repo.id}`, session) } catch (err) { if (!axios.isAxiosError(err)) throw err logger.warn(err) return '移除仓库失败。' } await ctx.database.remove('github', [name]) return '移除仓库成功!' } } const repos = await ctx.database.get('github', {}) if (!repos.length) return '当前没有监听的仓库。' return repos.map(repo => repo.name).join('\n') }) function subscribe(repo: string, id: string, meta: EventConfig) { (subscriptions[repo] ||= {})[id] = meta } function unsubscribe(repo: string, id: string) { delete subscriptions[repo][id] if (!Object.keys(subscriptions[repo]).length) { delete subscriptions[repo] } } const hidden = (sess: Session) => sess.subtype !== 'group' ctx.command('github [name]') .channelFields(['githubWebhooks']) .option('list', '-l 查看当前频道订阅的仓库列表', { hidden }) .option('add', '-a 为当前频道添加仓库订阅', { hidden, authority: 2 }) .option('delete', '-d 从当前频道移除仓库订阅', { hidden, authority: 2 }) .action(async ({ session, options }, name) => { if (options.list) { if (!session.channel) return '当前不是群聊上下文。' const names = Object.keys(session.channel.githubWebhooks) if (!names.length) return '当前没有订阅的仓库。' return names.join('\n') } if (options.add || options.delete) { if (!session.channel) return '当前不是群聊上下文。' if (!name) return '请输入仓库名。' if (!repoRegExp.test(name)) return '请输入正确的仓库名。' name = name.toLowerCase() const webhooks = session.channel.githubWebhooks if (options.add) { if (webhooks[name]) return `已经在当前频道订阅过仓库 ${name}。` const [repo] = await ctx.database.get('github', [name]) if (!repo) { const dispose = session.middleware(({ content }, next) => { dispose() content = content.trim() if (content && content !== '.' && content !== '。') return next() return session.execute({ name: 'github.repos', args: [name], options: { add: true, subscribe: true }, }) }) return `尚未添加过仓库 ${name}。发送空行或句号以立即添加并订阅该仓库。` } webhooks[name] = {} await session.channel.$update() subscribe(name, session.cid, {}) return '添加订阅成功!' } else if (options.delete) { if (!webhooks[name]) return `尚未在当前频道订阅过仓库 ${name}。` delete webhooks[name] await session.channel.$update() unsubscribe(name, session.cid) return '移除订阅成功!' } } }) async function request(method: Method, url: string, session: ReplySession, body: any, message: string) { return ctx.github.request(method, 'https://api.github.com' + url, session, body) .then(() => message + '成功!') .catch((err) => { logger.warn(err) return message + '失败。' }) } ctx.command('github.issue [title] [body:text]', '创建和查看 issue') .userFields(['ghAccessToken', 'ghRefreshToken']) .option('repo', '-r [repo:string] 仓库名') .action(async ({ session, options }, title, body) => { if (!options.repo) return '请输入仓库名。' if (!repoRegExp.test(options.repo)) return '请输入正确的仓库名。' if (!session.user.ghAccessToken) { return ctx.github.authorize(session, '要使用此功能,请对机器人进行授权。输入你的 GitHub 用户名。') } return request('POST', `/repos/${options.repo}/issues`, session, { title, body, }, '创建') }) ctx.command('github.star [repo]', '给仓库点个 star') .userFields(['ghAccessToken', 'ghRefreshToken']) .option('repo', '-r [repo:string] 仓库名') .action(async ({ session, options }) => { if (!options.repo) return '请输入仓库名。' if (!repoRegExp.test(options.repo)) return '请输入正确的仓库名。' if (!session.user.ghAccessToken) { return ctx.github.authorize(session, '要使用此功能,请对机器人进行授权。输入你的 GitHub 用户名。') } return request('PUT', `/user/starred/${options.repo}`, session, null, '创建') }) ctx.on('ready', async () => { const channels = await ctx.database.getAssignedChannels(['id', 'githubWebhooks']) for (const { id, githubWebhooks } of channels) { for (const repo in githubWebhooks) { subscribe(repo, id, githubWebhooks[repo]) } } }) const reactions = ['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes'] const history: Dict<ReplyPayloads> = {} function safeParse(source: string) { try { return JSON.parse(source) } catch {} } ctx.router.post(config.path + '/webhook', async (ctx) => { const event = ctx.headers['x-github-event'] const signature = ctx.headers['x-hub-signature-256'] const id = ctx.headers['x-github-delivery'] const payload = safeParse(ctx.request.body.payload) if (!payload) return ctx.status = 400 const fullEvent = payload.action ? `${event}/${payload.action}` : event logger.debug('received %s (%s)', fullEvent, id) const [data] = await database.get('github', [payload.repository.full_name.toLowerCase()]) // 202:服务器已接受请求,但尚未处理 // 在 github.repos -a 时确保获得一个 2xx 的状态码 if (!data) return ctx.status = 202 if (signature !== `sha256=${createHmac('sha256', data.secret).update(ctx.request.rawBody).digest('hex')}`) { return ctx.status = 403 } ctx.status = 200 if (payload.action) { app.emit(`github/${fullEvent}` as any, payload) } app.emit(`github/${event}` as any, payload) }) ctx.before('attach-user', (session, fields) => { if (!session.quote) return if (history[session.quote.messageId]) { fields.add('ghAccessToken') fields.add('ghRefreshToken') } }) ctx.middleware((session: ReplySession, next) => { if (!session.quote) return next() const body = session.parsed.content.trim() const payloads = history[session.quote.messageId] if (!body || !payloads) return next() let name: string, message: string if (session.parsed.prefix !== null) { name = body.split(' ', 1)[0] message = body.slice(name.length).trim() } else { name = reactions.includes(body) ? 'react' : 'reply' message = body } const payload = payloads[name] if (!payload) return next() const handler = new ReplyHandler(ctx.github, session, message) return handler[name](...payload) }) addListeners((event, handler) => { const base = camelize(event.split('/', 1)[0]) ctx.on(`github/${event}` as any, async (payload: CommonPayload) => { // step 1: filter event const repoConfig = subscriptions[payload.repository.full_name.toLowerCase()] || {} const targets = Object.keys(repoConfig).filter((id) => { const baseConfig = repoConfig[id][base] || {} if (baseConfig === false) return const action = camelize(payload.action) if (action && baseConfig !== true) { const actionConfig = baseConfig[action] if (actionConfig === false) return if (actionConfig !== true && !(defaultEvents[base] || {})[action]) return } return true }) if (!targets.length) return // step 2: handle event const result = handler(payload as any) if (!result) return // step 3: broadcast message logger.debug('broadcast', result[0].split('\n', 1)[0]) const messageIds = await ctx.broadcast(targets, config.messagePrefix + result[0]) // step 4: save message ids for interactions for (const id of messageIds) { history[id] = result[1] } setTimeout(() => { for (const id of messageIds) { delete history[id] } }, config.replyTimeout) }) }) }
the_stack
// These types are derived in large part from the Microsoft-supplied types for // ES2015 Promises. They have been tweaked to support RSVP's extensions to the // Promises A+ spec and the additional helper functions it supplies. declare namespace RSVP { // All the Promise methods essentially flatten existing promises, so that // you don't end up with `Promise<Promise<Promise<string>>>` if you happen // to return another `Promise` from a `.then()` invocation, etc. So all of // them can take a type or a promise-like/then-able type. type Arg<T> = T | PromiseLike<T>; // RSVP supplies status for promises in certain places. enum State { fulfilled = 'fulfilled', rejected = 'rejected', pending = 'pending', } type Resolved<T> = { state: State.fulfilled; value: T; }; type Rejected<T = any> = { state: State.rejected; reason: T; }; type Pending = { state: State.pending; }; type PromiseState<T> = Resolved<T> | Rejected | Pending; type Deferred<T> = { promise: Promise<T>; resolve: (value?: RSVP.Arg<T>) => void; reject: (reason?: any) => void; }; interface InstrumentEvent { guid: string; // guid of promise. Must be globally unique, not just within the implementation childGuid: string; // child of child promise (for chained via `then`) eventName: string; // one of ['created', 'chained', 'fulfilled', 'rejected'] detail: any; // fulfillment value or rejection reason, if applicable label: string; // label passed to promise's constructor timeStamp: number; // milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now } interface ObjectWithEventMixins { on( eventName: 'created' | 'chained' | 'fulfilled' | 'rejected', listener: (event: InstrumentEvent) => void ): void; on(eventName: 'error', errorHandler: (reason: any) => void): void; on(eventName: string, callback: (value: any) => void): void; off(eventName: string, callback?: (value: any) => void): void; trigger(eventName: string, options?: any, label?: string): void; } class EventTarget { /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. */ static mixin(object: object): ObjectWithEventMixins; /** Registers a callback to be executed when `eventName` is triggered */ static on( eventName: 'created' | 'chained' | 'fulfilled' | 'rejected', listener: (event: InstrumentEvent) => void ): void; static on(eventName: 'error', errorHandler: (reason: any) => void): void; static on(eventName: string, callback: (value: any) => void): void; /** * You can use `off` to stop firing a particular callback for an event. * * If you don't pass a `callback` argument to `off`, ALL callbacks for the * event will not be executed when the event fires. */ static off(eventName: string, callback?: (value: any) => void): void; /** * Use `trigger` to fire custom events. * * You can also pass a value as a second argument to `trigger` that will be * passed as an argument to all event listeners for the event */ static trigger(eventName: string, options?: any, label?: string): void; } class Promise<T> implements PromiseLike<T> { constructor( executor: (resolve: (value?: RSVP.Arg<T>) => void, reject: (reason?: any) => void) => void, label?: string ); new<T>( executor: (resolve: (value?: RSVP.Arg<T>) => void, reject: (reason?: any) => void) => void ): RSVP.Promise<T>; then<TResult1 = T, TResult2 = never>( onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null, label?: string ): RSVP.Promise<TResult1 | TResult2>; catch<TResult = never>( onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null, label?: string ): RSVP.Promise<T | TResult>; finally<U>(onFinally?: U | PromiseLike<U>): RSVP.Promise<T>; readonly [Symbol.toStringTag]: 'Promise'; static all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>, Arg<T10>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; static all<T1, T2, T3, T4, T5, T6, T7, T8, T9>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; static all<T1, T2, T3, T4, T5, T6, T7, T8>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; static all<T1, T2, T3, T4, T5, T6, T7>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5, T6, T7]>; static all<T1, T2, T3, T4, T5, T6>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5, T6]>; static all<T1, T2, T3, T4, T5>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>], label?: string ): RSVP.Promise<[T1, T2, T3, T4, T5]>; static all<T1, T2, T3, T4>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>], label?: string ): RSVP.Promise<[T1, T2, T3, T4]>; static all<T1, T2, T3>(values: [Arg<T1>, Arg<T2>, Arg<T3>], label?: string): RSVP.Promise<[T1, T2, T3]>; static all<T1, T2>(values: [Arg<T1>, Arg<T2>], label?: string): Promise<[T1, T2]>; static all<T>(values: (Arg<T>)[], label?: string): RSVP.Promise<T[]>; static race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( values: [ Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>, T10 | PromiseLike<T10> ], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>; static race<T1, T2, T3, T4, T5, T6, T7, T8, T9>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>; static race<T1, T2, T3, T4, T5, T6, T7, T8>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>; static race<T1, T2, T3, T4, T5, T6, T7>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7>; static race<T1, T2, T3, T4, T5, T6>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5 | T6>; static race<T1, T2, T3, T4, T5>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4 | T5>; static race<T1, T2, T3, T4>( values: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>], label?: string ): RSVP.Promise<T1 | T2 | T3 | T4>; static race<T1, T2, T3>(values: [Arg<T1>, Arg<T2>, Arg<T3>], label?: string): RSVP.Promise<T1 | T2 | T3>; static race<T1, T2>(values: [Arg<T1>, Arg<T2>], label?: string): RSVP.Promise<T1 | T2>; static race<T>(values: (Arg<T>)[], label?: string): RSVP.Promise<T>; static reject(reason?: any, label?: string): RSVP.Promise<never>; static resolve<T>(value?: Arg<T>, label?: string): RSVP.Promise<T>; static resolve(): RSVP.Promise<void>; /** * @deprecated */ static cast: typeof RSVP.Promise.resolve; } const all: typeof Promise.all; const race: typeof Promise.race; const reject: typeof Promise.reject; const resolve: typeof Promise.resolve; function rethrow(reason: any): void; const cast: typeof Promise.cast; const on: typeof EventTarget.on; const off: typeof EventTarget.off; // ----- denodeify ----- // // Here be absurd things because we don't have variadic types. All of // this will go away if we can ever write this: // // denodeify<...T, ...A>( // nodeFunc: (...args: ...A, callback: (err: any, ...cbArgs: ...T) => any) => void, // options?: false // ): (...args: ...A) => RSVP.Promise<...T> // // That day, however, may never come. So, in the meantime, we do this. function denodeify<T1, T2, T3, A>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2, data3: T3) => void) => void, options?: false ): (arg1: A) => RSVP.Promise<T1>; function denodeify<T1, T2, A>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2) => void) => void, options?: false ): (arg1: A) => RSVP.Promise<T1>; function denodeify<T, A>( nodeFunc: (arg1: A, callback: (err: any, data: T) => void) => void, options?: false ): (arg1: A) => RSVP.Promise<T>; function denodeify<T1, T2, T3, A>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2, data3: T3) => void) => void, options: true ): (arg1: A) => RSVP.Promise<[T1, T2, T3]>; function denodeify<T1, T2, A>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2) => void) => void, options: true ): (arg1: A) => RSVP.Promise<[T1, T2]>; function denodeify<T, A>( nodeFunc: (arg1: A, callback: (err: any, data: T) => void) => void, options: true ): (arg1: A) => RSVP.Promise<[T]>; function denodeify<T1, T2, T3, A, K1 extends string, K2 extends string, K3 extends string>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2, data3: T3) => void) => void, options: [K1, K2, K3] ): (arg1: A) => RSVP.Promise<{ [K in K1]: T1 } & { [K in K2]: T2 } & { [K in K3]: T3 }>; function denodeify<T1, T2, A, K1 extends string, K2 extends string>( nodeFunc: (arg1: A, callback: (err: any, data1: T1, data2: T2) => void) => void, options: [K1, K2] ): (arg1: A) => RSVP.Promise<{ [K in K1]: T1 } & { [K in K2]: T2 }>; function denodeify<T, A, K1 extends string>( nodeFunc: (arg1: A, callback: (err: any, data: T) => void) => void, options: [K1] ): (arg1: A) => RSVP.Promise<{ [K in K1]: T }>; // ----- hash and hashSettled ----- // function hash<T>(object: { [P in keyof T]: Arg<T[P]> }, label?: string): RSVP.Promise<T>; function hashSettled<T>( object: { [P in keyof T]: Arg<T[P]> }, label?: string ): RSVP.Promise<{ [P in keyof T]: PromiseState<T[P]> }>; function allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>, Arg<T10>], label?: string ): RSVP.Promise< [ PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>, PromiseState<T6>, PromiseState<T7>, PromiseState<T8>, PromiseState<T9> ] >; function allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>], label?: string ): RSVP.Promise< [ PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>, PromiseState<T6>, PromiseState<T7>, PromiseState<T8>, PromiseState<T9> ] >; function allSettled<T1, T2, T3, T4, T5, T6, T7, T8>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>], label?: string ): RSVP.Promise< [ PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>, PromiseState<T6>, PromiseState<T7>, PromiseState<T8> ] >; function allSettled<T1, T2, T3, T4, T5, T6, T7>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>], label?: string ): RSVP.Promise< [ PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>, PromiseState<T6>, PromiseState<T7> ] >; function allSettled<T1, T2, T3, T4, T5, T6>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>], label?: string ): RSVP.Promise< [PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>, PromiseState<T6>] >; function allSettled<T1, T2, T3, T4, T5>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>], label?: string ): RSVP.Promise<[PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>, PromiseState<T5>]>; function allSettled<T1, T2, T3, T4>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>], label?: string ): RSVP.Promise<[PromiseState<T1>, PromiseState<T2>, PromiseState<T3>, PromiseState<T4>]>; function allSettled<T1, T2, T3>( entries: [Arg<T1>, Arg<T2>, Arg<T3>], label?: string ): RSVP.Promise<[PromiseState<T1>, PromiseState<T2>, PromiseState<T3>]>; function allSettled<T1, T2>( entries: [Arg<T1>, Arg<T2>], label?: string ): RSVP.Promise<[PromiseState<T1>, PromiseState<T2>]>; function allSettled<T>(entries: Arg<T>[], label?: string): RSVP.Promise<[PromiseState<T>]>; function map<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>, Arg<T10>], mapFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10) => U, label?: string ): RSVP.Promise<Array<U> & { length: 10 }>; function map<T1, T2, T3, T4, T5, T6, T7, T8, T9, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>], mapFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9) => U, label?: string ): RSVP.Promise<Array<U> & { length: 9 }>; function map<T1, T2, T3, T4, T5, T6, T7, T8, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>], mapFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8) => U, label?: string ): RSVP.Promise<Array<U> & { length: 8 }>; function map<T1, T2, T3, T4, T5, T6, T7, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>], mapFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7) => U, label?: string ): RSVP.Promise<Array<U> & { length: 7 }>; function map<T1, T2, T3, T4, T5, T6, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>], mapFn: (item: T1 | T2 | T3 | T4 | T5 | T6) => U, label?: string ): RSVP.Promise<Array<U> & { length: 6 }>; function map<T1, T2, T3, T4, T5, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>], mapFn: (item: T1 | T2 | T3 | T4 | T5) => U, label?: string ): RSVP.Promise<Array<U> & { length: 5 }>; function map<T1, T2, T3, T4, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>], mapFn: (item: T1 | T2 | T3 | T4) => U, label?: string ): RSVP.Promise<Array<U> & { length: 4 }>; function map<T1, T2, T3, U>( entries: [Arg<T1>, Arg<T2>, Arg<T3>], mapFn: (item: T1 | T2 | T3) => U, label?: string ): RSVP.Promise<Array<U> & { length: 3 }>; function map<T1, T2, U>( entries: [Arg<T1>, Arg<T2>], mapFn: (item: T1 | T2) => U, label?: string ): RSVP.Promise<Array<U> & { length: 2 }>; function map<T, U>( entries: Arg<T>[], mapFn: (item: T) => U, label?: string ): RSVP.Promise<Array<U> & { length: 1 }>; function filter<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>, Arg<T10>], filterFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>>; function filter<T1, T2, T3, T4, T5, T6, T7, T8, T9>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>, Arg<T9>], filterFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>>; function filter<T1, T2, T3, T4, T5, T6, T7, T8>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>, Arg<T8>], filterFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>>; function filter<T1, T2, T3, T4, T5, T6, T7>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>, Arg<T7>], filterFn: (item: T1 | T2 | T3 | T4 | T5 | T6 | T7) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5 | T6 | T7>>; function filter<T1, T2, T3, T4, T5, T6>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>, Arg<T6>], filterFn: (item: T1 | T2 | T3 | T4 | T5 | T6) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5 | T6> & { length: 6 }>; function filter<T1, T2, T3, T4, T5>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>, Arg<T5>], filterFn: (item: T1 | T2 | T3 | T4 | T5) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4 | T5>>; function filter<T1, T2, T3, T4>( entries: [Arg<T1>, Arg<T2>, Arg<T3>, Arg<T4>], filterFn: (item: T1 | T2 | T3 | T4) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3 | T4>>; function filter<T1, T2, T3>( entries: [Arg<T1>, Arg<T2>, Arg<T3>], filterFn: (item: T1 | T2 | T3) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2 | T3>>; function filter<T1, T2>( entries: [Arg<T1>, Arg<T2>], filterFn: (item: T1 | T2) => boolean, label?: string ): RSVP.Promise<Array<T1 | T2>>; function filter<T>(entries: Arg<T>[], filterFn: (item: T) => boolean, label?: string): RSVP.Promise<Array<T>>; function defer<T>(label?: string): Deferred<T>; function configure<T>(name: string): T; function configure<T>(name: string, value: T): void; function asap<T, U>(callback: (callbackArg: T) => U, arg: T): void; const async: typeof asap; } export default RSVP; export interface Promise<T> extends RSVP.Promise<T> {} export const Promise: typeof RSVP.Promise; export interface EventTarget extends RSVP.EventTarget {} export const EventTarget: typeof RSVP.EventTarget; export const asap: typeof RSVP.asap; export const cast: typeof RSVP.cast; export const all: typeof RSVP.all; export const allSettled: typeof RSVP.allSettled; export const race: typeof RSVP.race; export const hash: typeof RSVP.hash; export const hashSettled: typeof RSVP.hashSettled; export const rethrow: typeof RSVP.rethrow; export const defer: typeof RSVP.defer; export const denodeify: typeof RSVP.denodeify; export const configure: typeof RSVP.configure; export const on: typeof RSVP.on; export const off: typeof RSVP.off; export const resolve: typeof RSVP.resolve; export const reject: typeof RSVP.reject; export const map: typeof RSVP.map; export const async: typeof RSVP.async; export const filter: typeof RSVP.filter;
the_stack
import * as Examples from './components/demos'; interface DemoInterface { /** ID for the demo, it will be used to help generate general ids to help with testing */ id: string; /** The name of the demo */ name: string; /** Demo component associated with the demo */ componentType: any; } /** Add the name of the demo and it's component here to have them show up in the demo app */ export const Demos: DemoInterface[] = [ { id: 'about-modal-demo', name: 'About Modal Demo', componentType: Examples.AboutModalDemo }, { id: 'accordion-demo', name: 'Accordion Demo', componentType: Examples.AccordionDemo }, { id: 'alert-timeout-close-button-demo', name: 'Alert Timeout Close Button Demo', componentType: Examples.AlertTimeoutCloseButtonDemo }, { id: 'alert-demo', name: 'Alert Demo', componentType: Examples.AlertDemo }, { id: 'alert-group-demo', name: 'Alert Group Demo', componentType: Examples.AlertGroupDemo }, { id: 'alert-custom-timeout-demo', name: 'Alert Custom Timeout Demo', componentType: Examples.AlertCustomTimeoutDemo }, { id: 'alert-default-timeout-demo', name: 'Alert Default Timeout Demo', componentType: Examples.AlertDefaultTimeoutDemo }, { id: 'application-launcher-favorites-demo', name: 'Application Launcher Favorites Demo', componentType: Examples.ApplicationLauncherFavoritesDemo }, { id: 'back-to-top-demo', name: 'Back To Top Demo', componentType: Examples.BackToTopDemo }, { id: 'breadcrumb-demo', name: 'Breadcrumb Demo', componentType: Examples.BreadcrumbDemo }, { id: 'button-demo', name: 'Button Demo', componentType: Examples.ButtonDemo }, { id: 'card-demo', name: 'Card Demo', componentType: Examples.CardDemo }, { id: 'chipgroup-demo', name: 'ChipGroup Demo', componentType: Examples.ChipGroupDemo }, { id: 'chipgroup-default-is-open-demo', name: 'ChipGroup Default is Open Demo', componentType: Examples.ChipGroupDefaultIsOpenDemo }, { id: 'chipgroup-with-category-demo', name: 'ChipGroup With Category Demo', componentType: Examples.ChipWithCategoryGroupDemo }, { id: 'chipgroup-with-overflow-chip-event-handler-demo', name: 'ChipGroup With Overflow Event Handler', componentType: Examples.ChipGroupWithOverflowChipEventHandler }, { id: 'clipboard-copy-demo', name: 'ClipboardCopy Demo', componentType: Examples.ClipboardCopyDemo }, { id: 'code-editor-demo', name: 'CodeEditor Demo', componentType: Examples.CodeEditorDemo }, { id: 'consoles-demo', name: 'Consoles Demo', componentType: Examples.ConsolesDemo }, { id: 'context-selector-demo', name: 'ContextSelector Demo', componentType: Examples.ContextSelectorDemo }, { id: 'data-list-demo', name: 'Data List Demo', componentType: Examples.DataListDemo }, { id: 'data-list-draggable-demo', name: 'Data List Draggable Demo', componentType: Examples.DataListDraggableDemo }, { id: 'data-list-compact-demo', name: 'Data List Compact Demo', componentType: Examples.DataListCompactDemo }, { id: 'description-list-demo', name: 'Description List Demo', componentType: Examples.DescriptionListDemo }, { id: 'description-list-breakpoints-demo', name: 'Description List Breakpoints Demo', componentType: Examples.DescriptionListBreakpointsDemo }, { id: 'drawer-demo', name: 'Drawer Demo', componentType: Examples.DrawerDemo }, { id: 'drawer-resize-demo', name: 'Drawer Resize Demo', componentType: Examples.DrawerResizeDemo }, { id: 'dropdown-demo', name: 'Dropdown Demo', componentType: Examples.DropdownDemo }, { id: 'dual-list-selector-basic-demo', name: 'DualListSelector basic Demo', componentType: Examples.DualListSelectorBasicDemo }, { id: 'dual-list-selector-tree-demo', name: 'DualListSelector Tree Demo', componentType: Examples.DualListSelectorTreeDemo }, { id: 'dual-list-selector-with-actions-demo', name: 'DualListSelector with actions Demo', componentType: Examples.DualListSelectorWithActionsDemo }, { id: 'expandable-section-demo', name: 'Expandable Section Demo', componentType: Examples.ExpandableSectionDemo }, { id: 'fileupload-demo', name: 'FileUpload Demo', componentType: Examples.FileUploadDemo }, { id: 'form-demo', name: 'Form Demo', componentType: Examples.FormDemo }, { id: 'jump-links-demo', name: 'Jump Links Demo', componentType: Examples.JumpLinksDemo }, { id: 'input-group-demo', name: 'Input Group Demo', componentType: Examples.InputGroupDemo }, { id: 'label-demo', name: 'Label Demo', componentType: Examples.LabelDemo }, { id: 'labelgroup-editable-demo', name: 'LabelGroup Editable Demo', componentType: Examples.LabelGroupEditableDemo }, { id: 'labelgroup-vertical-demo', name: 'LabelGroup Vertical Demo', componentType: Examples.LabelGroupVerticalDemo }, { id: 'labelgroup-with-category-demo', name: 'LabelGroup With Category Demo', componentType: Examples.LabelGroupWithCategoryDemo }, { id: 'login-page-demo', name: 'Login Page Demo', componentType: Examples.LoginPageDemo }, { id: 'masthead-demo', name: 'Masthead Demo', componentType: Examples.MastheadDemo }, { id: 'menu-demo', name: 'Menu Demo', componentType: Examples.MenuDemo }, { id: 'menu-drilldown-demo', name: 'Menu Drilldown Demo', componentType: Examples.MenuDrilldownDemo }, { id: 'modal-demo', name: 'Modal Demo', componentType: Examples.ModalDemo }, { id: 'nav-demo', name: 'Nav Demo', componentType: Examples.NavDemo }, { id: 'notification-badge-demo', name: 'Notification Badge Demo', componentType: Examples.NotificationBadgeDemo }, { id: 'notification-drawer-lightweight-demo', name: 'Notification Drawer Lightweight Demo', componentType: Examples.LightweightNotificationDrawerDemo }, { id: 'notification-drawer-basic-demo', name: 'Notification Drawer Basic Demo', componentType: Examples.BasicNotificationDrawerDemo }, { id: 'notification-drawer-groups-demo', name: 'Notification Drawer Groups Demo', componentType: Examples.GroupsNotificationDrawerDemo }, { id: 'numberInput-demo', name: 'Number Input Demo', componentType: Examples.NumberInputDemo }, { id: 'options-menu-demo', name: 'Options Menu Demo', componentType: Examples.OptionsMenuDemo }, { id: 'overflow-menu-demo', name: 'Overflow Menu Demo', componentType: Examples.OverflowMenuDemo }, { id: 'page-demo', name: 'Page Demo', componentType: Examples.PageDemo }, { id: 'page-managed-sidebar-closed-demo', name: 'Page Managed Sidebar Closed Demo', componentType: Examples.PageManagedSidebarClosedDemo }, { id: 'pagination-demo', name: 'Pagination Demo', componentType: Examples.PaginationDemo }, { id: 'popover-demo', name: 'Popover Demo', componentType: Examples.PopoverDemo }, { id: 'radio-demo', name: 'Radio Demo', componentType: Examples.RadioDemo }, { id: 'search-input-demo', name: 'Search Input Demo', componentType: Examples.SearchInputDemo }, { id: 'select-demo', name: 'Select Demo', componentType: Examples.SelectDemo }, { id: 'select-demo-filtering', name: 'Select Demo with Filtering', componentType: Examples.FilteringSelectDemo }, { id: 'select-demo-filtering-live-updates', name: 'Select Demo with Filtering and Live Items Updates', componentType: Examples.FilteringSelectLiveUpdateDemo }, { id: 'select-favorites-demo', name: 'Select Favorites Demo', componentType: Examples.SelectFavoritesDemo }, { id: 'select-validated-demo', name: 'Select Validated Demo', componentType: Examples.SelectValidatedDemo }, { id: 'select-view-more-demo', name: 'Select View More Demo', componentType: Examples.SelectViewMoreDemo }, { id: 'simple-list-demo', name: 'Simple List Demo', componentType: Examples.SimpleListDemo }, { id: 'slider-demo', name: 'Slider Demo', componentType: Examples.SliderDemo }, { id: 'switch-demo', name: 'Switch Demo', componentType: Examples.SwitchDemo }, { id: 'tab-demo', name: 'Tab Demo', componentType: Examples.TabDemo }, { id: 'tab-expandable-demo', name: 'Tab Expandable Demo', componentType: Examples.TabsExpandableDemo }, { id: 'tab-uncontrolled-demo', name: 'Tab Uncontrolled Demo', componentType: Examples.TabUncontrolledDemo }, { id: 'tabs-disabled-demo', name: 'Tabs Disabled Demo', componentType: Examples.TabsDisabledDemo }, { id: 'table-collapsible-demo', name: 'Table Collapsible Demo', componentType: Examples.TableCollapsibleDemo }, { id: 'table-compound-expandable-demo', name: 'Table Compound Expandable Demo', componentType: Examples.TableCompoundExpandableDemo }, { id: 'table-editable-demo', name: 'Table Editable Demo', componentType: Examples.TableEditableDemo }, { id: 'table-editable-compound-expandable-demo', name: 'Table Editable Compound Expandable Demo', componentType: Examples.TableEditableCompoundExpandableDemo }, { id: 'table-row-wrapper-demo', name: 'Table Row Wrapper Demo', componentType: Examples.TableRowWrapperDemo }, { id: 'table-row-click-demo', name: 'Table Row Click Demo', componentType: Examples.TableRowClickDemo }, { id: 'table-selectable-demo', name: 'Table Selectable Demo', componentType: Examples.TableSelectableDemo }, { id: 'table-simple-actions-demo', name: 'Table Simple Actions Demo', componentType: Examples.TableSimpleActionsDemo }, { id: 'table-simple-demo', name: 'Table Simple Demo', componentType: Examples.TableSimpleDemo }, { id: 'table-sortable-demo', name: 'Table Sortable Demo', componentType: Examples.TableSortableDemo }, { id: 'table-favorites-demo', name: 'Table Favorites Demo', componentType: Examples.TableFavoritesDemo }, { id: 'table-composable-demo', name: 'Table Composable Demo', componentType: Examples.TableComposableDemo }, { id: 'tab-string-event-key-demo', name: 'Tab String Event Key Demo', componentType: Examples.TabsStringEventKeyDemo }, { id: 'text-area', name: 'Text Area Demo', componentType: Examples.TextAreaDemo }, { id: 'text-input-demo', name: 'Text Input Demo', componentType: Examples.TextInputDemo }, { id: 'toggle-group-demo', name: 'Toggle Group Demo', componentType: Examples.ToggleGroupDemo }, { id: 'toolbar-demo', name: 'Toolbar Demo', componentType: Examples.ToolbarDemo }, { id: 'toolbar-visibility-demo', name: 'Toolbar Visibility Demo', componentType: Examples.ToolbarVisibilityDemo }, { id: 'toolbar-visiblity-demo', name: 'Toolbar Visiblity Demo (Deprecated)', componentType: Examples.ToolbarVisiblityDemo }, { id: 'tooltip-demo', name: 'Tooltip Demo', componentType: Examples.TooltipDemo }, { id: 'topology-demo', name: 'Topology Demo', componentType: Examples.TopologyDemo }, { id: 'treeview-demo', name: 'Tree View Demo', componentType: Examples.TreeViewDemo }, { id: 'wizard-demo', name: 'Wizard Demo', componentType: Examples.WizardDemo } ]; export default Demos;
the_stack
import { MIRFieldKey, MIRGlobalKey, MIRInvokeKey, MIRResolvedTypeKey, MIRVirtualMethodKey } from "../../../compiler/mir_ops"; import { Argument, ICPPOp } from "./icpp_exp"; import * as assert from "assert"; import { BSQRegex } from "../../../ast/bsqregex"; type TranspilerOptions = { }; type SourceInfo = { line: number; column: number; }; const ICPP_WORD_SIZE = 8; const UNIVERSAL_SIZE = 48; enum ICPPTypeKind { Invalid = 0x0, Register, Struct, String, BigNum, Ref, UnionInline, UnionRef } type RefMask = string; class ICPPTypeSizeInfoSimple { readonly tkey: MIRResolvedTypeKey; readonly inlinedatasize: number; //number of bytes needed in storage location for this (includes type tag for inline union -- is the size of a pointer for ref -- and word size for BSQBool) readonly assigndatasize: number; //number of bytes needed to copy when assigning this to a location -- 1 for BSQBool -- others should be same as inlined size readonly inlinedmask: RefMask; //The mask used to traverse this object as part of inline storage (on stack or inline in an object) -- must traverse full object constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask) { this.tkey = tkey; this.inlinedatasize = inlinedatasize; this.assigndatasize = assigndatasize; this.inlinedmask = inlinedmask; } isScalarOnlyInline(): boolean { return /1*/.test(this.inlinedmask); } static createByRegisterTypeInfo(tkey: MIRResolvedTypeKey, inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfoSimple { return new ICPPTypeSizeInfoSimple(tkey, inlinedatasize, assigndatasize, inlinedmask); } static createByValueTypeInfo(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfoSimple { return new ICPPTypeSizeInfoSimple(tkey, inlinedatasize, inlinedatasize, inlinedmask); } static createByRefTypeInfo(tkey: MIRResolvedTypeKey): ICPPTypeSizeInfoSimple { return new ICPPTypeSizeInfoSimple(tkey, ICPP_WORD_SIZE, ICPP_WORD_SIZE, "2"); } } class ICPPTypeSizeInfo { readonly heapsize: number; //number of bytes needed to represent the data (no type ptr) when storing in the heap readonly inlinedatasize: number; //number of bytes needed in storage location for this (includes type tag for inline union -- is the size of a pointer for ref -- and word size for BSQBool) readonly assigndatasize: number; //number of bytes needed to copy when assigning this to a location -- 1 for BSQBool -- others should be same as inlined size readonly heapmask: RefMask | undefined; //The mask to used to traverse this object during gc (if it is heap allocated) -- null if this is a leaf object -- partial if tailing scalars readonly inlinedmask: RefMask; //The mask used to traverse this object as part of inline storage (on stack or inline in an object) -- must traverse full object constructor(heapsize: number, inlinedatasize: number, assigndatasize: number, heapmask: RefMask | undefined, inlinedmask: RefMask) { this.heapsize = heapsize; this.inlinedatasize = inlinedatasize; this.assigndatasize = assigndatasize; this.heapmask = heapmask; this.inlinedmask = inlinedmask; } isScalarOnlyInline(): boolean { return /1*/.test(this.inlinedmask); } static createByRegisterTypeInfo(inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfo { return new ICPPTypeSizeInfo(inlinedatasize, inlinedatasize, assigndatasize, undefined, inlinedmask); } static createByValueTypeInfo(inlinedatasize: number, inlinedmask: RefMask): ICPPTypeSizeInfo { return new ICPPTypeSizeInfo(inlinedatasize, inlinedatasize, inlinedatasize, undefined, inlinedmask); } static createByRefTypeInfo(heapsize: number, heapmask: RefMask | undefined): ICPPTypeSizeInfo { return new ICPPTypeSizeInfo(heapsize, ICPP_WORD_SIZE, ICPP_WORD_SIZE, heapmask, "2"); } jemit(): any { return {heapsize: this.heapsize, inlinedatasize: this.inlinedatasize, assigndatasize: this.assigndatasize, heapmask: this.heapmask || null, inlinedmask: this.inlinedmask}; } } enum ICPPParseTag { BuiltinTag = 0x0, ValidatorTag, StringOfTag, DataStringTag, TypedNumberTag, VectorTag, ListTag, StackTag, QueueTag, SetTag, MapTag, TupleTag, RecordTag, EntityTag, EphemeralListTag, EnumTag, InlineUnionTag, RefUnionTag } class ICPPType { readonly tkey: MIRResolvedTypeKey; readonly tkind: ICPPTypeKind; readonly allocinfo: ICPPTypeSizeInfo; //memory size information readonly ptag: ICPPParseTag readonly iskey: boolean; constructor(ptag: ICPPParseTag, tkey: MIRResolvedTypeKey, tkind: ICPPTypeKind, allocinfo: ICPPTypeSizeInfo, iskey: boolean) { this.tkey = tkey; this.tkind = tkind; this.allocinfo = allocinfo; this.ptag = ptag; this.iskey = iskey; } jemitType(vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]): object { assert(this.ptag !== ICPPParseTag.BuiltinTag); //shouldn't be emitting these since they are "well known" return {ptag: this.ptag, iskey: this.iskey, tkey: this.tkey, tkind: this.tkind, allocinfo: this.allocinfo.jemit(), name: this.tkey, vtable: vtable}; } } class ICPPTypeRegister extends ICPPType { constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, assigndatasize: number, inlinedmask: RefMask, iskey: boolean) { super(ICPPParseTag.BuiltinTag, tkey, ICPPTypeKind.Register, ICPPTypeSizeInfo.createByRegisterTypeInfo(inlinedatasize, assigndatasize, inlinedmask), iskey); assert(inlinedatasize <= UNIVERSAL_SIZE); } jemitRegister(vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]): object { return this.jemitType(vtable); } } class ICPPTypeTuple extends ICPPType { readonly maxIndex: number; readonly ttypes: MIRResolvedTypeKey[]; readonly idxoffsets: number[]; constructor(tkey: MIRResolvedTypeKey, tkind: ICPPTypeKind, allocinfo: ICPPTypeSizeInfo, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[], iskey: boolean) { super(ICPPParseTag.TupleTag, tkey, tkind, allocinfo, iskey); this.maxIndex = idxtypes.length; this.ttypes = idxtypes; this.idxoffsets = idxoffsets; } static createByValueTuple(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[], iskey: boolean): ICPPTypeTuple { assert(inlinedatasize <= UNIVERSAL_SIZE); return new ICPPTypeTuple(tkey, ICPPTypeKind.Struct, ICPPTypeSizeInfo.createByValueTypeInfo(inlinedatasize, inlinedmask), idxtypes, idxoffsets, iskey); } static createByRefTuple(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, idxtypes: MIRResolvedTypeKey[], idxoffsets: number[], iskey: boolean): ICPPTypeTuple { return new ICPPTypeTuple(tkey, ICPPTypeKind.Ref, ICPPTypeSizeInfo.createByRefTypeInfo(heapsize, heapmask), idxtypes, idxoffsets, iskey); } jemitTupleType(vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]): object { return {...this.jemitType(vtable), maxIndex: this.maxIndex, ttypes: this.ttypes, idxoffsets: this.idxoffsets}; } } class ICPPTypeRecord extends ICPPType { readonly propertynames: string[]; readonly propertytypes: MIRResolvedTypeKey[]; readonly propertyoffsets: number[]; constructor(tkey: MIRResolvedTypeKey, tkind: ICPPTypeKind, allocinfo: ICPPTypeSizeInfo, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[], iskey: boolean) { super(ICPPParseTag.RecordTag, tkey, tkind, allocinfo, iskey); this.propertynames = propertynames; this.propertytypes = propertytypes; this.propertyoffsets = propertyoffsets; } static createByValueRecord(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[], iskey: boolean): ICPPTypeRecord { assert(inlinedatasize <= UNIVERSAL_SIZE); return new ICPPTypeRecord(tkey, ICPPTypeKind.Struct, ICPPTypeSizeInfo.createByValueTypeInfo(inlinedatasize, inlinedmask), propertynames, propertytypes, propertyoffsets, iskey); } static createByRefRecord(tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, propertynames: string[], propertytypes: MIRResolvedTypeKey[], propertyoffsets: number[], iskey: boolean): ICPPTypeRecord { return new ICPPTypeRecord(tkey, ICPPTypeKind.Ref, ICPPTypeSizeInfo.createByRefTypeInfo(heapsize, heapmask), propertynames, propertytypes, propertyoffsets, iskey); } jemitRecord(vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]): object { return {...this.jemitType(vtable), propertynames: this.propertynames, propertytypes: this.propertytypes, propertyoffsets: this.propertyoffsets}; } } class ICPPTypeEntity extends ICPPType { readonly fieldnames: MIRFieldKey[]; readonly fieldtypes: MIRResolvedTypeKey[]; readonly fieldoffsets: number[]; readonly extradata: any; constructor(ptag: ICPPParseTag, tkey: MIRResolvedTypeKey, tkind: ICPPTypeKind, allocinfo: ICPPTypeSizeInfo, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[], iskey: boolean, extradata: any) { super(ptag, tkey, tkind, allocinfo, iskey); this.fieldnames = fieldnames; this.fieldtypes = fieldtypes; this.fieldoffsets = fieldoffsets; this.extradata = extradata; } static createByValueEntity(ptag: ICPPParseTag, tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[], iskey: boolean, extradata: any): ICPPTypeEntity { assert(inlinedatasize <= UNIVERSAL_SIZE); return new ICPPTypeEntity(ptag, tkey, ICPPTypeKind.Struct, ICPPTypeSizeInfo.createByValueTypeInfo(inlinedatasize, inlinedmask), fieldnames, fieldtypes, fieldoffsets, iskey, extradata); } static createByRefEntity(ptag: ICPPParseTag, tkey: MIRResolvedTypeKey, heapsize: number, heapmask: RefMask, fieldnames: string[], fieldtypes: MIRResolvedTypeKey[], fieldoffsets: number[], iskey: boolean, extradata: any): ICPPTypeEntity { return new ICPPTypeEntity(ptag, tkey, ICPPTypeKind.Ref, ICPPTypeSizeInfo.createByRefTypeInfo(heapsize, heapmask), fieldnames, fieldtypes, fieldoffsets, iskey, extradata); } jemitValidator(re: object): object { return {...this.jemitType([]), regex: re}; } jemitStringOf(validator: MIRResolvedTypeKey): object { return {...this.jemitType([]), validator: validator}; } jemitDataString(chkinv: MIRInvokeKey): object { return {...this.jemitType([]), chkinv: chkinv}; } jemitTypedNumber(underlying: MIRResolvedTypeKey, primitive: MIRResolvedTypeKey): object { return {...this.jemitType([]), underlying: underlying, primitive: primitive}; } jemitEnum(underlying: MIRResolvedTypeKey, enuminvs: [string, number][]): object { return {...this.jemitType([]), underlying: underlying, enuminvs: enuminvs}; } jemitVector(etype: MIRResolvedTypeKey, esize: number, emask: RefMask): object { assert(false); return (undefined as any) as object; } jemitList(etype: MIRResolvedTypeKey, esize: number, emask: RefMask): object { return {...this.jemitType([]), etype: etype, esize: esize, emask: emask}; } jemitStack(t: MIRResolvedTypeKey, esize: number, emask: RefMask): object { assert(false); return (undefined as any) as object; } jemitQueue(t: MIRResolvedTypeKey, esize: number, emask: RefMask): object { assert(false); return (undefined as any) as object; } jemitSet(t: MIRResolvedTypeKey, esize: number, emask: RefMask): object { assert(false); return (undefined as any) as object; } jemitMap(k: MIRResolvedTypeKey, kesize: number, kemask: RefMask, v: MIRResolvedTypeKey, vesize: number, vemask: RefMask): object { assert(false); return (undefined as any) as object; } jemitEntity(vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]): object { return {...this.jemitType(vtable), fieldnames: this.fieldnames, fieldtypes: this.fieldtypes, fieldoffsets: this.fieldoffsets}; } } class ICPPTypeEphemeralList extends ICPPType { readonly etypes: MIRResolvedTypeKey[]; readonly eoffsets: number[]; constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, etypes: MIRResolvedTypeKey[], eoffsets: number[]) { super(ICPPParseTag.EphemeralListTag, tkey, ICPPTypeKind.Struct, ICPPTypeSizeInfo.createByValueTypeInfo(inlinedatasize, inlinedmask), false); this.etypes = etypes; this.eoffsets = eoffsets; } jemitEphemeralList(): object { return {...this.jemitType([]), etypes: this.etypes, eoffsets: this.eoffsets}; } } class ICPPTypeInlineUnion extends ICPPType { constructor(tkey: MIRResolvedTypeKey, inlinedatasize: number, inlinedmask: RefMask, iskey: boolean) { super(ICPPParseTag.InlineUnionTag, tkey, ICPPTypeKind.UnionInline, ICPPTypeSizeInfo.createByValueTypeInfo(inlinedatasize, inlinedmask), iskey); } jemitInlineUnion(subtypes: MIRResolvedTypeKey[]): object { return {...this.jemitType([]), subtypes: subtypes}; } } class ICPPTypeRefUnion extends ICPPType { constructor(tkey: MIRResolvedTypeKey, iskey: boolean) { super(ICPPParseTag.RefUnionTag, tkey, ICPPTypeKind.UnionRef, ICPPTypeSizeInfo.createByRefTypeInfo(0, "2"), iskey); } jemitRefUnion(subtypes: MIRResolvedTypeKey[]): object { return {...this.jemitType([]), subtypes: subtypes}; } } class ICPPFunctionParameter { readonly name: string; readonly ptype: ICPPType; constructor(name: string, ptype: ICPPType) { this.name = name; this.ptype = ptype; } jsonEmit(): object { return {name: this.name, ptype: this.ptype.tkey}; } } class ICPPInvokeDecl { readonly name: string; readonly ikey: MIRInvokeKey; readonly srcFile: string; readonly sinfo: SourceInfo; readonly recursive: boolean; readonly params: ICPPFunctionParameter[]; readonly resultType: ICPPType; readonly scalarStackBytes: number; readonly mixedStackBytes: number; readonly mixedStackMask: RefMask; readonly maskSlots: number; constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfo: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], resultType: ICPPType, scalarStackBytes: number, mixedStackBytes: number, mixedStackMask: RefMask, maskSlots: number) { this.name = name; this.ikey = ikey; this.srcFile = srcFile; this.sinfo = sinfo; this.recursive = recursive; this.params = params; this.resultType = resultType; this.scalarStackBytes = scalarStackBytes; this.mixedStackBytes = mixedStackBytes; this.mixedStackMask = mixedStackMask; this.maskSlots = maskSlots; } jsonEmit(): object { return {name: this.name, ikey: this.ikey, srcFile: this.srcFile, sinfo: this.sinfo, recursive: this.recursive, params: this.params.map((param) => param.jsonEmit()), resultType: this.resultType.tkey, scalarStackBytes: this.scalarStackBytes, mixedStackBytes: this.mixedStackBytes, mixedStackMask: this.mixedStackMask, maskSlots: this.maskSlots}; } } class ICPPInvokeBodyDecl extends ICPPInvokeDecl { readonly body: ICPPOp[]; readonly resultArg: Argument; readonly argmaskSize: number; constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfo: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], resultType: ICPPType, resultArg: Argument, scalarStackBytes: number, mixedStackBytes: number, mixedStackMask: RefMask, maskSlots: number, body: ICPPOp[], argmaskSize: number) { super(name, ikey, srcFile, sinfo, recursive, params, resultType, scalarStackBytes, mixedStackBytes, mixedStackMask, maskSlots); this.body = body; this.resultArg = resultArg; this.argmaskSize = argmaskSize; } jsonEmit(): object { return {...super.jsonEmit(), isbuiltin: false, resultArg: this.resultArg, body: this.body, argmaskSize: this.argmaskSize}; } } class ICPPPCode { readonly code: MIRInvokeKey; readonly cargs: Argument[]; constructor(code: MIRInvokeKey, cargs: Argument[]) { this.code = code; this.cargs = cargs; } jsonEmit(): object { return {code: this.code, cargs: this.cargs}; } } class ICPPInvokePrimitiveDecl extends ICPPInvokeDecl { readonly enclosingtype: string | undefined; readonly implkeyname: string; readonly scalaroffsetMap: Map<string, [number, MIRResolvedTypeKey]>; readonly mixedoffsetMap: Map<string, [number, MIRResolvedTypeKey]>; readonly binds: Map<string, ICPPType>; readonly pcodes: Map<string, ICPPPCode>; constructor(name: string, ikey: MIRInvokeKey, srcFile: string, sinfo: SourceInfo, recursive: boolean, params: ICPPFunctionParameter[], resultType: ICPPType, scalarStackBytes: number, mixedStackBytes: number, mixedStackMask: RefMask, maskSlots: number, enclosingtype: string | undefined, implkeyname: string, scalaroffsetMap: Map<string, [number, MIRResolvedTypeKey]>, mixedoffsetMap: Map<string, [number, MIRResolvedTypeKey]>, binds: Map<string, ICPPType>, pcodes: Map<string, ICPPPCode>) { super(name, ikey, srcFile, sinfo, recursive, params, resultType, scalarStackBytes, mixedStackBytes, mixedStackMask, maskSlots); this.enclosingtype = enclosingtype; this.implkeyname = implkeyname; this.scalaroffsetMap = scalaroffsetMap; this.mixedoffsetMap = mixedoffsetMap; this.binds = binds; this.pcodes = pcodes; } jsonEmit(): object { const soffsets = [...this.scalaroffsetMap].map((v) => { return {name: v[0], info: v[1]}; }); const moffsets = [...this.mixedoffsetMap].map((v) => { return {name: v[0], info: v[1]}; }); const binds = [...this.binds].map((v) => { return {name: v[0], ttype: v[1].tkey}; }); const pcodes = [...this.pcodes].map((v) => { return {name: v[0], pc: v[1]}; }); return {...super.jsonEmit(), isbuiltin: true, enclosingtype: this.enclosingtype, implkeyname: this.implkeyname, scalaroffsetMap: soffsets, mixedoffsetMap: moffsets, binds: binds, pcodes: pcodes}; } } class ICPPConstDecl { readonly gkey: MIRGlobalKey; readonly optenumname: [MIRResolvedTypeKey, string] | undefined; readonly storageOffset: number; readonly valueInvoke: MIRInvokeKey; readonly ctype: ICPPType; constructor(gkey: MIRGlobalKey, optenumname: [MIRResolvedTypeKey, string] | undefined, storageOffset: number, valueInvoke: MIRInvokeKey, ctype: ICPPType) { this.gkey = gkey; this.optenumname = optenumname; this.storageOffset = storageOffset; this.valueInvoke = valueInvoke; this.ctype = ctype; } jsonEmit(): object { return { storageOffset: this.storageOffset, valueInvoke: this.valueInvoke, ctype: this.ctype.tkey }; } } class ICPPAssembly { readonly typecount: number; cbuffsize: number = 0; cmask: RefMask = ""; readonly typenames: MIRResolvedTypeKey[]; readonly propertynames: string[]; readonly fieldnames: MIRFieldKey[]; readonly invokenames: MIRInvokeKey[]; readonly vinvokenames: MIRVirtualMethodKey[]; vtable: {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]}[] = []; subtypes: Map<MIRResolvedTypeKey, Set<MIRResolvedTypeKey>> = new Map<MIRResolvedTypeKey, Set<MIRResolvedTypeKey>>(); typedecls: ICPPType[] = []; invdecls: ICPPInvokeDecl[] = []; litdecls: { offset: number, storage: ICPPType, value: string }[] = []; constdecls: ICPPConstDecl[] = []; readonly entrypoint: MIRInvokeKey; constructor(typecount: number, typenames: MIRResolvedTypeKey[], propertynames: string[], fieldnames: MIRFieldKey[], invokenames: MIRInvokeKey[], vinvokenames: MIRVirtualMethodKey[], entrypoint: MIRInvokeKey) { this.typecount = typecount; this.typenames = typenames; this.propertynames = propertynames; this.fieldnames = fieldnames; this.invokenames = invokenames; this.vinvokenames = vinvokenames; this.entrypoint = entrypoint; } jsonEmit(): object { return { typecount: this.typecount, cbuffsize: this.cbuffsize, cmask: this.cmask, typenames: this.typenames.sort(), propertynames: this.propertynames.sort(), fieldnames: this.fieldnames.sort(), invokenames: this.invokenames.sort(), vinvokenames: this.vinvokenames.sort(), vtable: this.vtable.sort((a, b) => a.oftype.localeCompare(b.oftype)), typedecls: this.typedecls.sort((a, b) => a.tkey.localeCompare(b.tkey)).map((tdecl) => { const vtbl = this.vtable.find((vte) => vte.oftype === tdecl.tkey) as {oftype: MIRResolvedTypeKey, vtable: {vcall: MIRVirtualMethodKey, inv: MIRInvokeKey}[]}; if(tdecl instanceof ICPPTypeRegister) { return tdecl.jemitRegister(vtbl.vtable); } else if (tdecl instanceof ICPPTypeTuple) { return tdecl.jemitTupleType(vtbl.vtable); } else if (tdecl instanceof ICPPTypeRecord) { return tdecl.jemitRecord(vtbl.vtable); } else if (tdecl instanceof ICPPTypeEphemeralList) { return tdecl.jemitEphemeralList(); } else if(tdecl instanceof ICPPTypeInlineUnion) { return tdecl.jemitInlineUnion([...(this.subtypes.get(tdecl.tkey) as Set<MIRResolvedTypeKey>)].sort()); } else if (tdecl instanceof ICPPTypeRefUnion) { return tdecl.jemitRefUnion([...(this.subtypes.get(tdecl.tkey) as Set<MIRResolvedTypeKey>)].sort()); } else { const edecl = tdecl as ICPPTypeEntity; switch(edecl.ptag) { case ICPPParseTag.ValidatorTag: { return edecl.jemitValidator((edecl.extradata as BSQRegex).jemit()); } case ICPPParseTag.StringOfTag: { return edecl.jemitStringOf(edecl.extradata as MIRResolvedTypeKey); } case ICPPParseTag.DataStringTag: { return edecl.jemitDataString(edecl.extradata as MIRResolvedTypeKey); } case ICPPParseTag.TypedNumberTag: { // //TODO: we need to switch this to encode the underlying and primitive types in the type decl really -- not as // the funky v field -- we probably want to add some extra access (and maybe constructor) magic too // return edecl.jemitTypedNumber(edecl.extradata as MIRResolvedTypeKey, edecl.extradata as MIRResolvedTypeKey); } case ICPPParseTag.EnumTag: { const ddcls = this.constdecls.filter((cdcl) => cdcl.optenumname !== undefined && cdcl.optenumname[0] === tdecl.tkey); const enuminvs = ddcls.map((ddcl) => [`${(ddcl.optenumname as [string, string])[0]}::${(ddcl.optenumname as [string, string])[1]}`, ddcl.storageOffset] as [string, number]); return edecl.jemitEnum(edecl.extradata as MIRResolvedTypeKey, enuminvs); } case ICPPParseTag.VectorTag: { const sdata = edecl.extradata as ICPPTypeSizeInfoSimple; return edecl.jemitVector(sdata.tkey, sdata.inlinedatasize, sdata.inlinedmask); } case ICPPParseTag.ListTag: { const sdata = edecl.extradata as ICPPTypeSizeInfoSimple; return edecl.jemitList(sdata.tkey, sdata.inlinedatasize, sdata.inlinedmask); } case ICPPParseTag.StackTag: { const sdata = edecl.extradata as ICPPTypeSizeInfoSimple; return edecl.jemitStack(sdata.tkey, sdata.inlinedatasize, sdata.inlinedmask); } case ICPPParseTag.QueueTag: { const sdata = edecl.extradata as ICPPTypeSizeInfoSimple; return edecl.jemitQueue(sdata.tkey, sdata.inlinedatasize, sdata.inlinedmask); } case ICPPParseTag.SetTag: { const sdata = edecl.extradata as ICPPTypeSizeInfoSimple; return edecl.jemitSet(sdata.tkey, sdata.inlinedatasize, sdata.inlinedmask); } case ICPPParseTag.MapTag: { const keysdata = edecl.extradata[0] as ICPPTypeSizeInfoSimple; const valsdata = edecl.extradata[1] as ICPPTypeSizeInfoSimple; return edecl.jemitMap(keysdata.tkey, keysdata.inlinedatasize, keysdata.inlinedmask, valsdata.tkey, valsdata.inlinedatasize, valsdata.inlinedmask); } default: return edecl.jemitEntity(vtbl.vtable); } } }), invdecls: this.invdecls.sort((a, b) => a.ikey.localeCompare(b.ikey)).map((inv) => inv.jsonEmit()), litdecls: this.litdecls.sort((a, b) => a.value.localeCompare(b.value)).map((lv) => { return {offset: lv.offset, storage: lv.storage.tkey, value: lv.value}; }), constdecls: this.constdecls.sort((a, b) => a.gkey.localeCompare(b.gkey)).map((cd) => cd.jsonEmit()), entrypoint: this.entrypoint }; } } export { TranspilerOptions, SourceInfo, ICPP_WORD_SIZE, UNIVERSAL_SIZE, ICPPParseTag, ICPPTypeKind, ICPPTypeSizeInfoSimple, ICPPTypeSizeInfo, RefMask, ICPPType, ICPPTypeRegister, ICPPTypeTuple, ICPPTypeRecord, ICPPTypeEntity, ICPPTypeEphemeralList, ICPPTypeInlineUnion, ICPPTypeRefUnion, ICPPInvokeDecl, ICPPFunctionParameter, ICPPPCode, ICPPInvokeBodyDecl, ICPPInvokePrimitiveDecl, ICPPConstDecl, ICPPAssembly };
the_stack
import {ReactTestRenderer, act, create} from 'react-test-renderer'; import { Relationships, Store, createCheckpoints, createIndexes, createLocalPersister, createMetrics, createRelationships, createStore, } from '../../lib/debug/tinybase'; import { StoreListener, createStoreListener, expectChanges, expectChangesNoJson, expectNoChanges, } from './common'; import { useCell, useCellIds, useCheckpointIds, useLinkedRowIds, useLocalRowIds, useMetric, useRemoteRowId, useRow, useRowIds, useSliceIds, useSliceRowIds, useTable, useTableIds, useTables, } from '../../lib/debug/ui-react'; import React from 'react'; let renderer: ReactTestRenderer; const validCell = 1; const validRow = {c1: validCell}; const validTable = {r1: validRow}; const validTables = {t1: validTable}; const validCellSchema: { type: 'string'; default: string; } = {type: 'string', default: 't1'}; const validTableSchema = {c1: validCellSchema}; const validTablesSchema = {t1: validTableSchema}; const INVALID_CELLS: [string, any][] = [ ['Date', new Date()], ['Function', () => 42], ['Regex', /1/], ['empty array', []], ['array', [1, 2, 3]], ['Number', new Number(1)], ['String', new String('1')], ['Boolean', new Boolean(true)], ['null', null], ['undefined', undefined], ['NaN', NaN], ]; const INVALID_OBJECTS: [string, any][] = INVALID_CELLS.concat([ ['number', 1], ['string', '1'], ['boolean', true], ]); describe('Setting invalid', () => { test.each(INVALID_OBJECTS)('Tables; %s', (_name, tables: any) => { const store = createStore().setTables(tables); expect(store.getTables()).toEqual({}); }); test.each(INVALID_OBJECTS)('first Table; %s', (_name, table: any) => { const store = createStore().setTables({t1: table}); expect(store.getTables()).toEqual({}); }); test.each(INVALID_OBJECTS)('second Table; %s', (_name, table: any) => { const store = createStore().setTables({t1: validTable, t2: table}); expect(store.getTables()).toEqual(validTables); }); test.each(INVALID_OBJECTS)('first Row; %s', (_name, row: any) => { const store = createStore().setTables({t1: {r1: row}}); expect(store.getTables()).toEqual({}); }); test.each(INVALID_OBJECTS)('second Row; %s', (_name, row: any) => { const store = createStore().setTables({t1: {r1: validRow, r2: row}}); expect(store.getTables()).toEqual(validTables); }); test.each(INVALID_CELLS)('first Cell; %s', (_name, cell: any) => { const store = createStore().setTables({t1: {r1: {c1: cell}}}); expect(store.getTables()).toEqual({}); }); test.each(INVALID_CELLS)('second Cell; %s', (_name, cell: any) => { const store = createStore().setTables({ t1: {r1: {c1: validCell, c2: cell}}, }); expect(store.getTables()).toEqual(validTables); }); }); describe('Listening to invalid', () => { test.each(INVALID_OBJECTS)('Tables; %s', (_name, tables: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToInvalidCell('invalids', null, null, null); store.setTables(tables); expect(store.getTables()).toEqual(validTables); expectChangesNoJson(listener, 'invalids', { undefined: {undefined: {undefined: [undefined]}}, }); expectNoChanges(listener); }); test.each(INVALID_OBJECTS)( 'Table, alongside valid; %s', (_name, table: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToTable('/t2', 't2'); listener.listenToInvalidCell('invalids', null, null, null); store.setTables({t1: {r1: {c1: 2}}, t2: table}); expect(store.getTables()).toEqual({t1: {r1: {c1: 2}}}); expectChanges(listener, '/', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1', {t1: {r1: {c1: 2}}}); expectChangesNoJson(listener, 'invalids', { t2: {undefined: {undefined: [undefined]}}, }); expectNoChanges(listener); }, ); test.each(INVALID_OBJECTS)( 'existing or new Table; %s', (_name, table: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToTable('/t2', 't2'); listener.listenToInvalidCell('invalids', null, null, null); store.setTable('t1', table); store.setTable('t2', table); expect(store.getTables()).toEqual(validTables); expectChangesNoJson( listener, 'invalids', {t1: {undefined: {undefined: [undefined]}}}, {t2: {undefined: {undefined: [undefined]}}}, ); expectNoChanges(listener); }, ); test.each(INVALID_OBJECTS)('Row, alongside valid; %s', (_name, row: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToRow('/t1/r2', 't1', 'r2'); listener.listenToInvalidCell('invalids', null, null, null); store.setTable('t1', {r1: {c1: 2}, r2: row}); expect(store.getTables()).toEqual({t1: {r1: {c1: 2}}}); expectChanges(listener, '/', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1/r1', {t1: {r1: {c1: 2}}}); expectChangesNoJson(listener, 'invalids', { t1: {r2: {undefined: [undefined]}}, }); expectNoChanges(listener); }); test.each(INVALID_OBJECTS)('existing or new Row; %s', (_name, row: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToRow('/t1/r2', 't1', 'r2'); listener.listenToInvalidCell('invalids', null, null, null); store.setRow('t1', 'r1', row); store.setRow('t1', 'r2', row); expect(store.getTables()).toEqual(validTables); expectChangesNoJson( listener, 'invalids', {t1: {r1: {undefined: [undefined]}}}, {t1: {r2: {undefined: [undefined]}}}, ); expectNoChanges(listener); }); test.each(INVALID_OBJECTS)('add Row; %s', (_name, row: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToRow('/t1/0', 't1', '0'); listener.listenToInvalidCell('invalids', null, null, null); const rowId1 = store.addRow('t1', row); const rowId2 = store.addRow('t1', {c1: 2}); expect(rowId1).toBeUndefined(); expect(rowId2).toEqual('0'); store.delRow('t1', '0'); expect(store.getTables()).toEqual(validTables); expectChanges( listener, '/', {t1: {r1: {c1: 1}, '0': {c1: 2}}}, {t1: {r1: {c1: 1}}}, ); expectChanges( listener, '/t1', {t1: {r1: {c1: 1}, '0': {c1: 2}}}, {t1: {r1: {c1: 1}}}, ); expectChanges(listener, '/t1/0', {t1: {0: {c1: 2}}}, {t1: {0: {}}}); expectChangesNoJson(listener, 'invalids', { t1: {undefined: {undefined: [undefined]}}, }); expectNoChanges(listener); }); test.each(INVALID_CELLS)('add Row; %s', (_name, cell: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToRow('/t1/0', 't1', '0'); listener.listenToInvalidCell('invalids', null, null, null); const rowId = store.addRow('t1', {c1: cell}); expect(rowId).toBeUndefined(); expect(store.getTables()).toEqual(validTables); expectChangesNoJson(listener, 'invalids', { t1: {undefined: {c1: [cell]}}, }); expectNoChanges(listener); }); test.each(INVALID_CELLS)('Cell, alongside valid; %s', (_name, cell: any) => { const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToCell('/t1/r1/c1', 't1', 'r1', 'c1'); listener.listenToCell('/t1/r1/c2', 't1', 'r1', 'c2'); listener.listenToInvalidCell('invalids', null, null, null); store.setRow('t1', 'r1', {c1: 2, c2: cell}); expect(store.getTables()).toEqual({t1: {r1: {c1: 2}}}); expectChanges(listener, '/', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1/r1', {t1: {r1: {c1: 2}}}); expectChanges(listener, '/t1/r1/c1', {t1: {r1: {c1: 2}}}); expectChanges(listener, 'invalids', {t1: {r1: {c2: [cell]}}}); expectNoChanges(listener); }); test.each(INVALID_CELLS.slice(0, 1))( 'existing or new Cell; %s', (_name, cell: any) => { if (typeof cell == 'function') { return; } const store = createStore().setTables(validTables); const listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToRow('/t1/r2', 't1', 'r2'); listener.listenToCell('/t1/r1/c1', 't1', 'r1', 'c1'); listener.listenToCell('/t1/r1/c2', 't1', 'r1', 'c2'); listener.listenToCell('/t1/r2/c1', 't1', 'r2', 'c1'); listener.listenToInvalidCell('invalids', null, null, null); store .setCell('t1', 'r1', 'c1', cell) .setCell('t1', 'r1', 'c2', cell) .setCell('t1', 'r2', 'c1', cell); expect(store.getTables()).toEqual(validTables); expectChanges( listener, 'invalids', {t1: {r1: {c1: [cell]}}}, {t1: {r1: {c2: [cell]}}}, {t1: {r2: {c1: [cell]}}}, ); expectNoChanges(listener); }, ); }); describe('Rejects invalid', () => { test.each(INVALID_OBJECTS)( 'Tables schema; %s', (_name, tablesSchema: any) => { const store = createStore().setSchema(tablesSchema); expect(JSON.parse(store.getSchemaJson())).toEqual({}); }, ); test.each(INVALID_OBJECTS)('Table schema; %s', (_name, tableSchema: any) => { const store = createStore().setSchema({t1: tableSchema}); expect(JSON.parse(store.getSchemaJson())).toEqual({}); }); test.each(INVALID_OBJECTS)( 'Table schema, alongside valid; %s', (_name, tableSchema: any) => { const store = createStore().setSchema({ t1: validTableSchema, t2: tableSchema, }); expect(JSON.parse(store.getSchemaJson())).toEqual(validTablesSchema); }, ); test.each(INVALID_OBJECTS)('Cell schema; %s', (_name, cellSchema: any) => { const store = createStore().setSchema({t1: {c1: cellSchema}}); expect(JSON.parse(store.getSchemaJson())).toEqual({}); }); test.each(INVALID_OBJECTS)( 'Cell schema, alongside valid; %s', (_name, cellSchema: any) => { const store = createStore().setSchema({ t1: {c1: validCellSchema, c2: cellSchema}, }); expect(JSON.parse(store.getSchemaJson())).toEqual(validTablesSchema); }, ); test.each(INVALID_OBJECTS)( '(bad type) Cell schema; %s', (_name, type: any) => { const store = createStore().setSchema({t1: {c1: {type}}}); expect(JSON.parse(store.getSchemaJson())).toEqual({}); }, ); test('(useless) Cell schema', () => { // @ts-ignore const store = createStore().setTables({}, {t1: {c1: {default: 't1'}}}); expect(JSON.parse(store.getSchemaJson())).toEqual({}); }); test('(useless bounds) Cell schema', () => { const store1 = createStore().setSchema({ // @ts-ignore t1: {c1: {type: 'string', min: 1, max: 10}}, }); expect(JSON.parse(store1.getSchemaJson())).toEqual({ t1: {c1: {type: 'string'}}, }); const store2 = createStore().setSchema({ // @ts-ignore t1: {c1: {type: 'boolean', min: 1, max: 10}}, }); expect(JSON.parse(store2.getSchemaJson())).toEqual({ t1: {c1: {type: 'boolean'}}, }); }); test('(extended) Cell schema', () => { const store = createStore().setSchema({ // @ts-ignore t1: {c1: {type: 'string', default: 't1', extraThing1: 1}}, }); expect(JSON.parse(store.getSchemaJson())).toEqual(validTablesSchema); }); test('(inconsistent default) Cell schema', () => { const store = createStore().setSchema({ t1: { // @ts-ignore r1: {type: 'boolean', default: 't1'}, // @ts-ignore r2: {type: 'number', default: 't1'}, // @ts-ignore r3: {type: 'string', default: 2}, }, }); expect(JSON.parse(store.getSchemaJson())).toEqual({ t1: {r1: {type: 'boolean'}, r2: {type: 'number'}, r3: {type: 'string'}}, }); }); }); describe('Get non-existent', () => { test('Table', () => { const store = createStore().setTables(validTables); expect(store.getTable('z')).toEqual({}); }); test('Row', () => { const store = createStore().setTables(validTables); expect(store.getRow('t1', 'z')).toEqual({}); expect(store.getRow('y', 'z')).toEqual({}); }); test('Cell', () => { const store = createStore().setTables(validTables); expect(store.getCell('t1', 'r1', 'z')).toBeUndefined(); expect(store.getCell('t1', 'y', 'z')).toBeUndefined(); expect(store.getCell('x', 'y', 'z')).toBeUndefined(); }); test('Metric', () => { const store = createStore().setTables(validTables); const metrics = createMetrics(store); metrics.setMetricDefinition('m', 't1'); expect(metrics.getMetric('z')).toBeUndefined(); }); test('Index', () => { const store = createStore().setTables(validTables); const indexes = createIndexes(store); indexes.setIndexDefinition('i', 't1'); expect(indexes.getSliceIds('z')).toEqual([]); expect(indexes.getSliceRowIds('z', 'y')).toEqual([]); }); }); describe('Delete non-existent', () => { let store: Store; let listener: StoreListener; beforeEach(() => { store = createStore().setTables(validTables); listener = createStoreListener(store); listener.listenToTables('/'); listener.listenToTable('/t1', 't1'); listener.listenToRow('/t1/r1', 't1', 'r1'); listener.listenToCell('/t1/r1/c1', 't1', 'r1', 'c1'); }); test('Table', () => { store.delTable('t2'); expect(store.getTables()).toEqual(validTables); expectNoChanges(listener); }); test('Row', () => { store.delRow('t1', 'r2'); store.delRow('t2', 'r1'); expect(store.getTables()).toEqual(validTables); expectNoChanges(listener); }); test('Cell', () => { store.delCell('t1', 'r1', 'c2'); store.delCell('t1', 'r2', 'c1'); store.delCell('t2', 'r1', 'c1'); expectNoChanges(listener); }); }); describe.each(INVALID_OBJECTS)( 'Invalid hook container; %s', (_name, container: any) => { test('useTables', () => { const Test = () => <>{JSON.stringify(useTables(container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify({})); }); test('useTableIds', () => { const Test = () => <>{JSON.stringify(useTableIds(container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useTable', () => { const Test = () => <>{JSON.stringify(useTable('t1', container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify({})); }); test('useRowIds', () => { const Test = () => <>{JSON.stringify(useRowIds('t1', container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useRow', () => { const Test = () => <>{JSON.stringify(useRow('t1', 'r1', container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify({})); }); test('useCellIds', () => { const Test = () => ( <>{JSON.stringify(useCellIds('t1', 'r1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useCell', () => { const Test = () => ( <>{JSON.stringify(useCell('t1', 'r1', 'c1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toBeNull(); }); test('useMetric', () => { const Test = () => <>{JSON.stringify(useMetric('m1', container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toBeNull(); }); test('useSliceIds', () => { const Test = () => <>{JSON.stringify(useSliceIds('i1', container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useSliceRowIds', () => { const Test = () => ( <>{JSON.stringify(useSliceRowIds('i1', 's1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useRemoteRowId', () => { const Test = () => ( <>{JSON.stringify(useRemoteRowId('r1', 'r1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toBeNull(); }); test('useLocalRowIds', () => { const Test = () => ( <>{JSON.stringify(useLocalRowIds('r1', 'r1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useLinkedRowIds', () => { const Test = () => ( <>{JSON.stringify(useLinkedRowIds('r1', 'r1', container))}</> ); act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([])); }); test('useCheckpointIds', () => { const Test = () => <>{JSON.stringify(useCheckpointIds(container))}</>; act(() => { renderer = create(<Test />); }); expect(renderer.toJSON()).toEqual(JSON.stringify([[], undefined, []])); }); }, ); describe('Linked lists', () => { let relationships: Relationships; beforeEach( () => (relationships = createRelationships( createStore().setTables({ t1: { r1: {c1: 'r2'}, r2: {c1: 'r3'}, r3: {c1: 'r4'}, r4: {c1: 'r2'}, r5: {c1: 'r6'}, }, }), )), ); test('non-existent relationship', () => { relationships.setRelationshipDefinition('r1', 't1', 't1', 'c1'); expect(relationships.getLinkedRowIds('r2', 'r1')).toEqual(['r1']); }); test('remote table relationship', () => { relationships.setRelationshipDefinition('r1', 't1', 'T1', 'c1'); expect(relationships.getLinkedRowIds('r1', 'r1')).toEqual(['r1']); }); test('self relationship', () => { relationships .setRelationshipDefinition('r1', 't1', 't1', 'c1') .getStore() .setCell('t1', 'r1', 'c1', 'r1'); expect(relationships.getLinkedRowIds('r1', 'r1')).toEqual(['r1']); }); test('circular relationship', () => { relationships.setRelationshipDefinition('r1', 't1', 't1', 'c1'); expect(relationships.getLinkedRowIds('r1', 'r1')).toEqual([ 'r1', 'r2', 'r3', 'r4', ]); }); test('broken relationship', () => { relationships.setRelationshipDefinition('r1', 't1', 't1', 'c2'); expect(relationships.getLinkedRowIds('r1', 'r1')).toEqual(['r1']); }); }); describe('Updating immutables', () => { test('Overriding store methods', () => { const store = createStore().setTables(validTables); expect(() => { store.addRowListener = () => '0'; }).toThrow(); expect(() => { // @ts-ignore store.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore store['foo'] = 'bar'; }).toThrow(); }); test('Overriding metrics methods', () => { const store = createStore().setTables(validTables); const metrics = createMetrics(store); expect(() => { metrics.addMetricListener = () => '0'; }).toThrow(); expect(() => { // @ts-ignore metrics.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore metrics['foo'] = 'bar'; }).toThrow(); }); test('Overriding indexes methods', () => { const store = createStore().setTables(validTables); const indexes = createIndexes(store); expect(() => { indexes.addSliceIdsListener = () => '0'; }).toThrow(); expect(() => { // @ts-ignore indexes.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore indexes['foo'] = 'bar'; }).toThrow(); }); test('Overriding relationships methods', () => { const store = createStore().setTables(validTables); const relationships = createRelationships(store); expect(() => { relationships.addRemoteRowIdListener = () => '0'; }).toThrow(); expect(() => { // @ts-ignore relationships.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore relationships['foo'] = 'bar'; }).toThrow(); }); test('Overriding persister methods', () => { const store = createStore().setTables(validTables); const persister = createLocalPersister(store, 'foo'); expect(() => { persister.load = async () => persister; }).toThrow(); expect(() => { // @ts-ignore persister.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore persister['foo'] = 'bar'; }).toThrow(); }); test('Overriding checkpoints methods', () => { const store = createStore().setTables(validTables); const checkpoints = createCheckpoints(store); expect(() => { checkpoints.addCheckpointIdsListener = () => '0'; }).toThrow(); expect(() => { // @ts-ignore checkpoints.foo = 'bar'; }).toThrow(); expect(() => { // @ts-ignore checkpoints['foo'] = 'bar'; }).toThrow(); }); });
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, } from 'n8n-workflow'; import { googleApiRequest, } from './GenericFunctions'; export class GoogleSlides implements INodeType { description: INodeTypeDescription = { displayName: 'Google Slides', name: 'googleSlides', icon: 'file:googleslides.svg', group: ['input', 'output'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume the Google Slides API', defaults: { name: 'Google Slides', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'googleApi', required: true, displayOptions: { show: { authentication: [ 'serviceAccount', ], }, }, }, { name: 'googleSlidesOAuth2Api', required: true, displayOptions: { show: { authentication: [ 'oAuth2', ], }, }, }, ], properties: [ { displayName: 'Authentication', name: 'authentication', type: 'options', options: [ { name: 'OAuth2', value: 'oAuth2', }, { name: 'Service Account', value: 'serviceAccount', }, ], default: 'serviceAccount', }, { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Page', value: 'page', }, { name: 'Presentation', value: 'presentation', }, ], default: 'presentation', description: 'Resource to operate on', }, { displayName: 'Operation', name: 'operation', type: 'options', options: [ { name: 'Create', value: 'create', description: 'Create a presentation', }, { name: 'Get', value: 'get', description: 'Get a presentation', }, { name: 'Get Slides', value: 'getSlides', description: 'Get presentation slides', }, { name: 'Replace Text', value: 'replaceText', description: 'Replace text in a presentation', }, ], displayOptions: { show: { resource: [ 'presentation', ], }, }, default: 'create', description: 'Operation to perform', }, { displayName: 'Operation', name: 'operation', type: 'options', options: [ { name: 'Get', value: 'get', description: 'Get a page', }, { name: 'Get Thumbnail', value: 'getThumbnail', description: 'Get a thumbnail', }, ], displayOptions: { show: { resource: [ 'page', ], }, }, default: 'get', description: 'Operation to perform', }, { displayName: 'Title', name: 'title', description: 'Title of the presentation to create.', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'presentation', ], operation: [ 'create', ], }, }, }, { displayName: 'Presentation ID', name: 'presentationId', description: 'ID of the presentation to retrieve. Found in the presentation URL: <code>https://docs.google.com/presentation/d/PRESENTATION_ID/edit</code>', placeholder: '1wZtNFZ8MO-WKrxhYrOLMvyiqSgFwdSz5vn8_l_7eNqw', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'presentation', 'page', ], operation: [ 'get', 'getThumbnail', 'getSlides', 'replaceText', ], }, }, }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { operation: [ 'getSlides', ], resource: [ 'presentation', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { operation: [ 'getSlides', ], resource: [ 'presentation', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 500, }, default: 100, description: 'How many results to return.', }, { displayName: 'Page Object ID', name: 'pageObjectId', description: 'ID of the page object to retrieve.', type: 'string', default: '', required: true, displayOptions: { show: { resource: [ 'page', ], operation: [ 'get', 'getThumbnail', ], }, }, }, { displayName: 'Texts To Replace', name: 'textUi', placeholder: 'Add Text', type: 'fixedCollection', typeOptions: { multipleValues: true, }, displayOptions: { show: { resource: [ 'presentation', ], operation: [ 'replaceText', ], }, }, default: {}, options: [ { name: 'textValues', displayName: 'Text', values: [ { displayName: 'Match Case', name: 'matchCase', type: 'boolean', default: false, description: 'Indicates whether the search should respect case. True : the search is case sensitive. False : the search is case insensitive.', }, { displayName: 'Page IDs', name: 'pageObjectIds', type: 'multiOptions', default: [], typeOptions: { loadOptionsMethod: 'getPages', loadOptionsDependsOn: [ 'presentationId', ], }, description: 'If non-empty, limits the matches to page elements only on the given pages.', }, { displayName: 'Replace Text', name: 'replaceText', type: 'string', default: '', description: 'The text that will replace the matched text.', }, { displayName: 'Text', name: 'text', type: 'string', default: '', description: 'The text to search for in the shape or table.', }, ], }, ], }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', displayOptions: { show: { operation: [ 'replaceText', ], resource: [ 'presentation', ], }, }, default: {}, options: [ { displayName: 'Revision ID', name: 'revisionId', type: 'string', default: '', description: `The revision ID of the presentation required for the write request. If specified and the requiredRevisionId doesn't exactly match the presentation's current revisionId, the request will not be processed and will return a 400 bad request error.`, }, ], }, { displayName: 'Download', name: 'download', type: 'boolean', default: false, displayOptions: { show: { resource: [ 'page', ], operation: [ 'getThumbnail', ], }, }, description: 'Name of the binary property to which to write the data of the read page.', }, { displayName: 'Binary Property', name: 'binaryProperty', type: 'string', required: true, default: 'data', description: 'Name of the binary property to which to write to.', displayOptions: { show: { resource: [ 'page', ], operation: [ 'getThumbnail', ], download: [ true, ], }, }, }, ], }; methods = { loadOptions: { // Get all the pages to display them to user so that he can // select them easily async getPages( this: ILoadOptionsFunctions, ): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const presentationId = this.getCurrentNodeParameter('presentationId') as string; const { slides } = await googleApiRequest.call(this, 'GET', `/presentations/${presentationId}`, {}, { fields: 'slides' }); for (const slide of slides) { returnData.push({ name: slide.objectId, value: slide.objectId, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; let responseData; const returnData: INodeExecutionData[] = []; for (let i = 0; i < items.length; i++) { try { if (resource === 'page') { // ********************************************************************* // page // ********************************************************************* if (operation === 'get') { // ---------------------------------- // page: get // ---------------------------------- const presentationId = this.getNodeParameter('presentationId', i) as string; const pageObjectId = this.getNodeParameter('pageObjectId', i) as string; responseData = await googleApiRequest.call(this, 'GET', `/presentations/${presentationId}/pages/${pageObjectId}`); returnData.push({ json: responseData }); } else if (operation === 'getThumbnail') { // ---------------------------------- // page: getThumbnail // ---------------------------------- const presentationId = this.getNodeParameter('presentationId', i) as string; const pageObjectId = this.getNodeParameter('pageObjectId', i) as string; responseData = await googleApiRequest.call(this, 'GET', `/presentations/${presentationId}/pages/${pageObjectId}/thumbnail`); const download = this.getNodeParameter('download', 0) as boolean; if (download === true) { const binaryProperty = this.getNodeParameter('binaryProperty', i) as string; const data = await this.helpers.request({ uri: responseData.contentUrl, method: 'GET', json: false, encoding: null, }); const fileName = pageObjectId + '.png'; const binaryData = await this.helpers.prepareBinaryData(data, fileName || fileName); returnData.push({ json: responseData, binary: { [binaryProperty]: binaryData, }, }); } else { returnData.push({ json: responseData }); } } } else if (resource === 'presentation') { // ********************************************************************* // presentation // ********************************************************************* if (operation === 'create') { // ---------------------------------- // presentation: create // ---------------------------------- const body = { title: this.getNodeParameter('title', i) as string, }; responseData = await googleApiRequest.call(this, 'POST', '/presentations', body); returnData.push({ json: responseData }); } else if (operation === 'get') { // ---------------------------------- // presentation: get // ---------------------------------- const presentationId = this.getNodeParameter('presentationId', i) as string; responseData = await googleApiRequest.call(this, 'GET', `/presentations/${presentationId}`); returnData.push({ json: responseData }); } else if (operation === 'getSlides') { // ---------------------------------- // presentation: getSlides // ---------------------------------- const returnAll = this.getNodeParameter('returnAll', 0) as boolean; const presentationId = this.getNodeParameter('presentationId', i) as string; responseData = await googleApiRequest.call(this, 'GET', `/presentations/${presentationId}`, {}, { fields: 'slides' }); responseData = responseData.slides; if (returnAll === false) { const limit = this.getNodeParameter('limit', i) as number; responseData = responseData.slice(0, limit); } returnData.push(...this.helpers.returnJsonArray(responseData)); } else if (operation === 'replaceText') { // ---------------------------------- // presentation: replaceText // ---------------------------------- const presentationId = this.getNodeParameter('presentationId', i) as string; const texts = this.getNodeParameter('textUi.textValues', i, []) as IDataObject[]; const options = this.getNodeParameter('options', i) as IDataObject; const requests = texts.map((text => { return { replaceAllText: { replaceText: text.replaceText, pageObjectIds: text.pageObjectIds || [], containsText: { text: text.text, matchCase: text.matchCase, }, }, }; })); const body: IDataObject = { requests, }; if (options.revisionId) { body['writeControl'] = { requiredRevisionId: options.revisionId as string, }; } responseData = await googleApiRequest.call(this, 'POST', `/presentations/${presentationId}:batchUpdate`, { requests }); returnData.push({ json: responseData }); } } } catch (error) { if (this.continueOnFail()) { returnData.push({json:{ error: error.message }}); continue; } throw error; } } return [returnData]; } }
the_stack
import expect from 'expect'; import { loadContract } from './utils'; import crypto from 'crypto'; import { publicKeyToHex } from '@solana/solidity'; describe('Deploy solang contract and test', () => { it('flipper', async function () { this.timeout(50000); let { contract } = await loadContract('flipper', 'flipper.abi', [true]); let res = await contract.functions.get({ simulate: true }); expect(res.result).toStrictEqual(true); await contract.functions.flip(); res = await contract.functions.get({ simulate: true }); expect(res.result).toStrictEqual(false); }); it('primitives', async function () { this.timeout(100000); let { contract, payer } = await loadContract('primitives', 'primitives.abi', []); // TEST Basic enums // in ethereum, an enum is described as an uint8 so can't use the enum // names programmatically. 0 = add, 1 = sub, 2 = mul, 3 = div, 4 = mod, 5 = pow, 6 = shl, 7 = shr let res = await contract.functions.is_mul(2, { simulate: true }); expect(res.result).toBe(true); res = await contract.functions.return_div({ simulate: true }); expect(res.result).toBe(3); // TEST uint and int types, and arithmetic/bitwise ops res = await contract.functions.op_i64(0, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(5100); res = await contract.functions.op_i64(1, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(-3100); res = await contract.functions.op_i64(2, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(4100000); res = await contract.functions.op_i64(3, 1000, 10, { simulate: true }); expect(Number(res.result)).toBe(100); res = await contract.functions.op_i64(4, 1000, 99, { simulate: true }); expect(Number(res.result)).toBe(10); res = await contract.functions.op_i64(6, - 1000, 8, { simulate: true }); expect(Number(res.result)).toBe(-256000); res = await contract.functions.op_i64(7, - 1000, 8, { simulate: true }); expect(Number(res.result)).toBe(-4); res = await contract.functions.op_u64(0, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(5100); res = await contract.functions.op_u64(1, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(18446744073709548516); // (2^64)-18446744073709548516 = 3100 res = await contract.functions.op_u64(2, 123456789, 123456789, { simulate: true }); expect(Number(res.result)).toBe(15241578750190521); res = await contract.functions.op_u64(3, 123456789, 100, { simulate: true }); expect(Number(res.result)).toBe(1234567); res = await contract.functions.op_u64(4, 123456789, 100, { simulate: true }); expect(Number(res.result)).toBe(89); res = await contract.functions.op_u64(5, 3, 7, { simulate: true }); expect(Number(res.result)).toBe(2187); res = await contract.functions.op_i64(6, 1000, 8, { simulate: true }); expect(Number(res.result)).toBe(256000); res = await contract.functions.op_i64(7, 1000, 8, { simulate: true }); expect(Number(res.result)).toBe(3); // now for 256 bit operations res = await contract.functions.op_i256(0, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(5100); res = await contract.functions.op_i256(1, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(-3100); res = await contract.functions.op_i256(2, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(4100000); res = await contract.functions.op_i256(3, 1000, 10, { simulate: true }); expect(Number(res.result)).toBe(100); res = await contract.functions.op_i256(4, 1000, 99, { simulate: true }); expect(Number(res.result)).toBe(10); res = await contract.functions.op_i256(6, - 10000000000000, 8, { simulate: true }); expect(Number(res.result)).toBe(-2560000000000000); res = await contract.functions.op_i256(7, - 10000000000000, 8, { simulate: true }); expect(Number(res.result)).toBe(-39062500000); res = await contract.functions.op_u256(0, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(5100); res = await contract.functions.op_u256(1, 1000, 4100, { simulate: true }); expect(Number(res.result)).toBe(115792089237316195423570985008687907853269984665640564039457584007913129636836); // (2^64)-18446744073709548516 = 3100 res = await contract.functions.op_u256(2, 123456789, 123456789, { simulate: true }); expect(Number(res.result)).toBe(15241578750190521); res = await contract.functions.op_u256(3, 123456789, 100, { simulate: true }); expect(Number(res.result)).toBe(1234567); res = await contract.functions.op_u256(4, 123456789, 100, { simulate: true }); expect(Number(res.result)).toBe(89); res = await contract.functions.op_u256(5, 123456789, 9, { simulate: true }); expect(Number(res.result)).toBe(6662462759719942007440037531362779472290810125440036903063319585255179509); res = await contract.functions.op_i256(6, 10000000000000, 8, { simulate: true }); expect(Number(res.result)).toBe(2560000000000000); res = await contract.functions.op_i256(7, 10000000000000, 8, { simulate: true }); expect(Number(res.result)).toBe(39062500000); // TEST bytesN res = await contract.functions.return_u8_6({ simulate: true }); expect(res.result).toBe("0x414243444546"); // TEST bytes5 res = await contract.functions.op_u8_5_shift(6, "0xdeadcafe59", 8, { simulate: true }); expect(res.result).toBe("0xadcafe5900"); res = await contract.functions.op_u8_5_shift(7, "0xdeadcafe59", 8, { simulate: true }); expect(res.result).toBe("0x00deadcafe"); res = await contract.functions.op_u8_5(8, "0xdeadcafe59", "0x0000000006", { simulate: true }); expect(res.result).toBe("0xdeadcafe5f"); res = await contract.functions.op_u8_5(9, "0xdeadcafe59", "0x00000000ff", { simulate: true }); expect(res.result).toBe("0x0000000059"); res = await contract.functions.op_u8_5(10, "0xdeadcafe59", "0x00000000ff", { simulate: true }); expect(res.result).toBe("0xdeadcafea6"); // TEST bytes14 res = await contract.functions.op_u8_14_shift(6, "0xdeadcafe123456789abcdefbeef7", "9", { simulate: true }); expect(res.result).toBe("0x5b95fc2468acf13579bdf7ddee00"); res = await contract.functions.op_u8_14_shift(7, "0xdeadcafe123456789abcdefbeef7", "9", { simulate: true }); expect(res.result).toBe("0x006f56e57f091a2b3c4d5e6f7df7"); res = await contract.functions.op_u8_14(8, "0xdeadcafe123456789abcdefbeef7", "0x0000060000000000000000000000", { simulate: true }); expect(res.result).toBe("0xdeadcefe123456789abcdefbeef7"); res = await contract.functions.op_u8_14(9, "0xdeadcafe123456789abcdefbeef7", "0x000000000000000000ff00000000", { simulate: true }); expect(res.result).toBe("0x000000000000000000bc00000000"); res = await contract.functions.op_u8_14(10, "0xdeadcafe123456789abcdefbeef7", "0xff00000000000000000000000000", { simulate: true }); expect(res.result).toBe("0x21adcafe123456789abcdefbeef7"); // TEST address type. We need to encoding this has a hex string with the '0x' prefix, since solang maps address // to bytes32 type let address = publicKeyToHex(payer.publicKey); res = await contract.functions.address_passthrough(address); expect(res.result).toBe(address); }); it('store', async function () { this.timeout(50000); const { contract } = await loadContract('store', 'store.abi', []); let res = await contract.functions.get_values1({ simulate: true }); expect(res.result.toString()).toEqual("0,0,0,0"); res = await contract.functions.get_values2({ simulate: true }); expect(res.result.toString()).toStrictEqual('0,,0xb00b1e,0x00000000,0'); await contract.functions.set_values(); res = await contract.functions.get_values1({ simulate: true }); expect(res.result.toString()).toStrictEqual('18446744073709551615,3671129839,32766,57896044618658097711785492504343953926634992332820282019728792003956564819967'); res = await contract.functions.get_values2({ simulate: true }); expect(res.result.toString()).toStrictEqual('102,the course of true love never did run smooth,0xb00b1e,0x41424344,1'); await contract.functions.do_ops(); res = await contract.functions.get_values1({ simulate: true }); expect(res.result.toString()).toStrictEqual("1,65263,32767,57896044618658097711785492504343953926634992332820282019728792003956564819966"); res = await contract.functions.get_values2({ simulate: true }); expect(res.result.toString()).toStrictEqual("61200,,0xb0ff1e,0x61626364,3"); await contract.functions.push_zero(); let bs = "0xb0ff1e00"; for (let i = 0; i < 20; i++) { res = await contract.functions.get_bs({ simulate: true }); expect(res.result).toStrictEqual(bs); if (bs.length <= 4 || Math.random() >= 0.5) { let val = ((Math.random() * 256) | 0).toString(16); val = val.length == 1 ? "0" + val : val; await contract.functions.push("0x" + val); bs += val; } else { res = await contract.functions.pop(); let last = bs.slice(-2); expect(res.result.toString()).toStrictEqual("0x" + last); bs = bs.slice(0, -2); } } }); it('structs', async function () { this.timeout(50000); const { contract } = await loadContract('store', 'store.abi', []); await contract.functions.set_foo1(); // get foo1 let res = await contract.functions.get_both_foos({ simulate: true }); // compare without JSON.stringify() results in "Received: serializes to the same string" error. // I have no idea why expect(res.result.toString()).toStrictEqual(([ [ "1", "0x446f6e277420636f756e7420796f757220636869636b656e73206265666f72652074686579206861746368", "-102", "0xedaeda", "You can't have your cake and eat it too", [true, "There are other fish in the sea"] ], [ "0", "0x", "0", "0x000000", "", [false, ""] ] ]).toString()); await contract.functions.set_foo2( [ "1", "0xb52b073595ccb35eaebb87178227b779", "-123112321", "0x123456", "Barking up the wrong tree", [true, "Drive someone up the wall"] ], "nah" ); res = await contract.functions.get_both_foos({ simulate: true }); expect(res.result.toString()).toStrictEqual(([ [ "1", "0x446f6e277420636f756e7420796f757220636869636b656e73206265666f72652074686579206861746368", "-102", "0xedaeda", "You can't have your cake and eat it too", [true, "There are other fish in the sea"] ], [ "1", "0xb52b073595ccb35eaebb87178227b779", "-123112321", "0x123456", "Barking up the wrong tree", [true, "nah"] ] ]).toString()); await contract.functions.delete_foo(true); res = await contract.functions.get_foo(false, { simulate: true }); expect(res.result.toString()).toStrictEqual(([ [ "1", "0xb52b073595ccb35eaebb87178227b779", "-123112321", "0x123456", "Barking up the wrong tree", [true, "nah"] ], ]).toString()); res = await contract.functions.get_foo(true, { simulate: true }); expect(res.result.toString()).toStrictEqual(([ [ "0", "0x", "0", "0x000000", "", [false, ""] ], ]).toString()); await contract.functions.delete_foo(false); res = await contract.functions.get_both_foos({ simulate: true }); // compare without JSON.stringify() results in "Received: serializes to the same string" error. // I have no idea why expect(res.result.toString()).toStrictEqual(([ [ "0", "0x", "0", "0x000000", "", [false, ""] ], [ "0", "0x", "0", "0x000000", "", [false, ""] ] ]).toString()); await contract.functions.struct_literal(); res = await contract.functions.get_foo(true, { simulate: true }); // compare without JSON.stringify() results in "Received: serializes to the same string" error. // I have no idea why expect(res.result.toString()).toStrictEqual(([ [ "3", "0x537570657263616c6966726167696c697374696365787069616c69646f63696f7573", "64927", "0xe282ac", "Antidisestablishmentarianism", [true, "Pseudopseudohypoparathyroidism"], ] ]).toString()); }); it('account storage too small constructor', async function () { this.timeout(50000); await expect(loadContract('store', 'store.abi', [], 100)) .rejects .toThrowError(new Error('account data too small for instruction')); }); it('account storage too small dynamic alloc', async function () { this.timeout(50000); const { contract } = await loadContract('store', 'store.abi', [], 200); // storage.sol needs 168 bytes on constructor, more for string data // set a load of string which will overflow await expect(contract.functions.set_foo1()) .rejects .toThrowError(new Error('account data too small for instruction')); }); it('account storage too small dynamic realloc', async function () { this.timeout(50000); const { contract } = await loadContract('store', 'store.abi', [], 210); async function push_until_bang() { for (let i = 0; i < 100; i++) { await contract.functions.push("0x01"); } } // do realloc until failure await expect(push_until_bang()) .rejects .toThrowError(new Error('account data too small for instruction')); }); it('arrays in account storage', async function () { this.timeout(50000); const { contract } = await loadContract('arrays', 'arrays.abi', []); let users = []; for (let i = 0; i < 3; i++) { let addr = '0x' + crypto.randomBytes(32).toString('hex'); let name = `name${i}`; let id = crypto.randomBytes(4).readUInt32BE(0).toString(); let perms: string[] = []; for (let j = 0; j < Math.random() * 3; j++) { let p = Math.floor(Math.random() * 8); perms.push(`${p}`); } await contract.functions.addUser(id, addr, name, perms); users.push([ name, addr, id, perms ]); } let user = users[Math.floor(Math.random() * users.length)]; let res = await contract.functions.getUserById(user[2], { simulate: true }); expect(res.result.toString()).toStrictEqual(user.toString()); if (user[3].length > 0) { let perms = user[3]; let p = perms[Math.floor(Math.random() * perms.length)]; res = await contract.functions.hasPermission(user[2], p, { simulate: true }); expect(res.result).toStrictEqual(true); } user = users[Math.floor(Math.random() * users.length)]; res = await contract.functions.getUserByAddress(user[1], { simulate: true }); expect(res.result.toString()).toStrictEqual(user.toString()); await contract.functions.removeUser(user[2]); res = await contract.functions.userExists(user[2]); expect(res.result).toStrictEqual(false); }); });
the_stack
import {ClayCheckbox, ClayRadio} from '@clayui/form'; import { MouseSafeArea, TInternalStateOnChange, useInternalState, } from '@clayui/shared'; import React, {useContext, useRef, useState} from 'react'; import warning from 'warning'; import Caption from './Caption'; import Divider from './Divider'; import ClayDropDown from './DropDown'; import ClayDropDownGroup from './Group'; import Help from './Help'; import ClayDropDownMenu from './Menu'; import Search from './Search'; type TType = | 'checkbox' | 'contextual' | 'group' | 'item' | 'radio' | 'radiogroup' | 'divider'; interface IItem { active?: boolean; checked?: boolean; disabled?: boolean; href?: string; items?: Array<IItem>; label?: string; name?: string; onChange?: Function; onClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void; symbolLeft?: string; symbolRight?: string; type?: TType; value?: string; } interface IDropDownContentProps { /** * The path to the SVG spritemap file containing the icons. */ spritemap?: string; /** * List of items to display in drop down menu */ items: Array<IItem>; } export interface IProps extends IDropDownContentProps { active?: React.ComponentProps<typeof ClayDropDown>['active']; /** * Default position of menu element. Values come from `./Menu`. */ alignmentPosition?: React.ComponentProps< typeof ClayDropDownMenu >['alignmentPosition']; /** * Informational text that appears at the end or above the `footerContent` prop. */ caption?: string; className?: string; closeOnClickOutside?: React.ComponentProps< typeof ClayDropDown >['closeOnClickOutside']; /** * HTML element tag that the container should render. */ containerElement?: React.ComponentProps< typeof ClayDropDown >['containerElement']; /** * Add an action button or any other element you want to be fixed position to the * footer from the DropDown. */ footerContent?: React.ReactElement; /** * Element that is used as the trigger which will activate the dropdown on click. */ trigger: React.ReactElement; /** * Add informational text at the top of DropDown. */ helpText?: string; /** * Prop to pass DOM element attributes to <DropDown.Menu />. */ menuElementAttrs?: React.ComponentProps< typeof ClayDropDown >['menuElementAttrs']; menuHeight?: React.ComponentProps<typeof ClayDropDown>['menuHeight']; menuWidth?: React.ComponentProps<typeof ClayDropDown>['menuWidth']; /** * Function for setting the offset of the menu from the trigger. */ offsetFn?: React.ComponentProps<typeof ClayDropDown>['offsetFn']; onActiveChange?: TInternalStateOnChange<boolean>; /** * Callback will always be called when the user is interacting with search. */ onSearchValueChange?: (newValue: string) => void; /** * Flag to show search at the top of the DropDown. */ searchable?: boolean; /** * Pass the props to the Search component. */ searchProps?: Omit< React.ComponentProps<typeof Search>, 'onChange' | 'spritemap' | 'value' >; /** * The value that will be passed to the search input element. */ searchValue?: string; } interface IInternalItem { spritemap?: string; } const Checkbox: React.FunctionComponent<IItem & IInternalItem> = ({ checked = false, onChange = () => {}, ...otherProps }) => { const [value, setValue] = useState<boolean>(checked); return ( <ClayDropDown.Section> <ClayCheckbox {...otherProps} checked={value} onChange={() => { setValue((val) => !val); onChange(!value); }} /> </ClayDropDown.Section> ); }; const ClayDropDownContext = React.createContext({close: () => {}}); const Item: React.FunctionComponent<Omit<IItem, 'onChange'> & IInternalItem> = ({label, onClick, ...props}) => { const {close} = useContext(ClayDropDownContext); return ( <ClayDropDown.Item onClick={(event) => { if (onClick) { onClick(event); } close(); }} {...props} > {label} </ClayDropDown.Item> ); }; const Group: React.FunctionComponent<IItem & IInternalItem> = ({ items, label, spritemap, }) => ( <> <ClayDropDownGroup header={label} /> {items && <DropDownContent items={items} spritemap={spritemap} />} </> ); const Contextual: React.FunctionComponent< Omit<IItem, 'onChange'> & IInternalItem > = ({items, label, spritemap, ...otherProps}) => { const [visible, setVisible] = useState(false); const {close} = useContext(ClayDropDownContext); const triggerElementRef = useRef<HTMLLIElement | null>(null); const menuElementRef = useRef<HTMLDivElement>(null); const timeoutHandleRef = useRef<any>(null); return ( <ClayDropDown.Item {...otherProps} onClick={(event) => { if (event.currentTarget === event.target) { setVisible(true); clearTimeout(timeoutHandleRef.current); timeoutHandleRef.current = null; } }} onMouseEnter={() => { if (!visible) { timeoutHandleRef.current = setTimeout( () => setVisible(true), 500 ); } }} onMouseLeave={() => { setVisible(false); clearTimeout(timeoutHandleRef.current); timeoutHandleRef.current = null; }} ref={triggerElementRef} spritemap={spritemap} symbolRight="angle-right" > {label} {items && ( <ClayDropDown.Menu active={visible} alignElementRef={triggerElementRef} alignmentPosition={8} onSetActive={setVisible} ref={menuElementRef} > {visible && <MouseSafeArea parentRef={menuElementRef} />} <ClayDropDownContext.Provider value={{ close: () => { setVisible(false); close(); }, }} > <DropDownContent items={items} spritemap={spritemap} /> </ClayDropDownContext.Provider> </ClayDropDown.Menu> )} </ClayDropDown.Item> ); }; interface IRadioContext { checked: string; name?: string; onChange: (value: string) => void; } const RadioGroupContext = React.createContext({} as IRadioContext); const Radio: React.FunctionComponent<IItem & IInternalItem> = ({ value = '', ...otherProps }) => { const {checked, name, onChange} = useContext(RadioGroupContext); return ( <ClayDropDown.Section> <ClayRadio {...otherProps} checked={checked === value} inline name={name} onChange={() => onChange(value as string)} value={value as string} /> </ClayDropDown.Section> ); }; const RadioGroup: React.FunctionComponent<IItem & IInternalItem> = ({ items, label, name, onChange = () => {}, spritemap, }) => { const [value, setValue] = useState(''); const params = { checked: value, name, onChange: (value: string) => { onChange(value); setValue(value); }, }; warning( items && items.filter((item) => item.type !== 'radio').length === 0, 'ClayDropDownWithItems -> Items of type `radiogroup` should be used `radio` if you need to use others, it is recommended to use type `group`.' ); return ( <> {label && <ClayDropDownGroup header={label} />} {items && ( <li aria-label={label} role="radiogroup"> <RadioGroupContext.Provider value={params}> <DropDownContent items={items} spritemap={spritemap} /> </RadioGroupContext.Provider> </li> )} </> ); }; const DividerWithItem = () => <Divider />; const TYPE_MAP = { checkbox: Checkbox, contextual: Contextual, divider: DividerWithItem, group: Group, item: Item, radio: Radio, radiogroup: RadioGroup, }; const DropDownContent: React.FunctionComponent<IDropDownContentProps> = ({ items, spritemap, }) => ( <ClayDropDown.ItemList> {items.map(({type, ...item}, key) => { const Item = TYPE_MAP[type || 'item']; return <Item {...item} key={key} spritemap={spritemap} />; })} </ClayDropDown.ItemList> ); const findNested = < T extends {items?: Array<T>; [key: string]: any}, K extends keyof T >( items: Array<T>, key: K ): T | undefined => items.find((item) => { if (item[key]) { return true; } if (item.items) { return findNested(item.items, key); } return false; }); export const ClayDropDownWithItems: React.FunctionComponent<IProps> = ({ active, alignmentPosition, caption, className, closeOnClickOutside, containerElement, footerContent, helpText, items, menuElementAttrs, menuHeight, menuWidth, offsetFn, onActiveChange, onSearchValueChange = () => {}, searchable, searchProps, searchValue = '', spritemap, trigger, }: IProps) => { const [internalActive, setInternalActive] = useInternalState({ initialValue: false, onChange: onActiveChange, value: active, }); const hasRightSymbols = React.useMemo( () => !!findNested(items, 'symbolRight'), [items] ); const hasLeftSymbols = React.useMemo( () => !!findNested(items, 'symbolLeft'), [items] ); const Wrap = footerContent ? 'form' : React.Fragment; return ( <ClayDropDown active={internalActive} alignmentPosition={alignmentPosition} className={className} closeOnClickOutside={closeOnClickOutside} containerElement={containerElement} hasLeftSymbols={hasLeftSymbols} hasRightSymbols={hasRightSymbols} menuElementAttrs={menuElementAttrs} menuHeight={menuHeight} menuWidth={menuWidth} offsetFn={offsetFn} onActiveChange={setInternalActive} trigger={trigger} > <ClayDropDownContext.Provider value={{close: () => setInternalActive(false)}} > {helpText && <Help>{helpText}</Help>} {searchable && ( <Search {...searchProps} onChange={(event) => onSearchValueChange(event.target.value) } spritemap={spritemap} value={searchValue} /> )} <Wrap> {footerContent ? ( <div className="inline-scroller"> <DropDownContent items={items} spritemap={spritemap} /> </div> ) : ( <DropDownContent items={items} spritemap={spritemap} /> )} {caption && <Caption>{caption}</Caption>} {footerContent && ( <div className="dropdown-section">{footerContent}</div> )} </Wrap> </ClayDropDownContext.Provider> </ClayDropDown> ); }; ClayDropDownWithItems.displayName = 'ClayDropDownWithItems';
the_stack
import * as ts from 'typescript'; import * as fs from 'fs'; enum SyntaxKindMapped { Unknown, EndOfFileToken, SingleLineCommentTrivia, MultiLineCommentTrivia, NewLineTrivia, WhitespaceTrivia, // We detect and preserve #! on the first line ShebangTrivia, // We detect and provide better error recovery when we encounter a git merge marker. This // allows us to edit files with git-conflict markers in them in a much more pleasant manner. ConflictMarkerTrivia, // Literals NumericLiteral, BigIntLiteral, StringLiteral, JsxText, JsxTextAllWhiteSpaces, RegularExpressionLiteral, NoSubstitutionTemplateLiteral, // Pseudo-literals TemplateHead, TemplateMiddle, TemplateTail, // Punctuation OpenBraceToken, CloseBraceToken, OpenParenToken, CloseParenToken, OpenBracketToken, CloseBracketToken, DotToken, DotDotDotToken, SemicolonToken, CommaToken, QuestionDotToken, LessThanToken, LessThanSlashToken, GreaterThanToken, LessThanEqualsToken, GreaterThanEqualsToken, EqualsEqualsToken, ExclamationEqualsToken, EqualsEqualsEqualsToken, ExclamationEqualsEqualsToken, EqualsGreaterThanToken, PlusToken, MinusToken, AsteriskToken, AsteriskAsteriskToken, SlashToken, PercentToken, PlusPlusToken, MinusMinusToken, LessThanLessThanToken, GreaterThanGreaterThanToken, GreaterThanGreaterThanGreaterThanToken, AmpersandToken, BarToken, CaretToken, ExclamationToken, TildeToken, AmpersandAmpersandToken, BarBarToken, QuestionToken, ColonToken, AtToken, QuestionQuestionToken, /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */ BacktickToken, // Assignments EqualsToken, PlusEqualsToken, MinusEqualsToken, AsteriskEqualsToken, AsteriskAsteriskEqualsToken, SlashEqualsToken, PercentEqualsToken, LessThanLessThanEqualsToken, GreaterThanGreaterThanEqualsToken, GreaterThanGreaterThanGreaterThanEqualsToken, AmpersandEqualsToken, BarEqualsToken, BarBarEqualsToken, AmpersandAmpersandEqualsToken, QuestionQuestionEqualsToken, CaretEqualsToken, // Identifiers and PrivateIdentifiers Identifier, PrivateIdentifier, // Reserved words BreakKeyword, CaseKeyword, CatchKeyword, ClassKeyword, ConstKeyword, ContinueKeyword, DebuggerKeyword, DefaultKeyword, DeleteKeyword, DoKeyword, ElseKeyword, EnumKeyword, ExportKeyword, ExtendsKeyword, FalseKeyword, FinallyKeyword, ForKeyword, FunctionKeyword, IfKeyword, ImportKeyword, InKeyword, InstanceOfKeyword, NewKeyword, NullKeyword, ReturnKeyword, SuperKeyword, SwitchKeyword, ThisKeyword, ThrowKeyword, TrueKeyword, TryKeyword, TypeOfKeyword, VarKeyword, VoidKeyword, WhileKeyword, WithKeyword, // Strict mode reserved words ImplementsKeyword, InterfaceKeyword, LetKeyword, PackageKeyword, PrivateKeyword, ProtectedKeyword, PublicKeyword, StaticKeyword, YieldKeyword, // Contextual keywords AbstractKeyword, AsKeyword, AssertsKeyword, AnyKeyword, AsyncKeyword, AwaitKeyword, BooleanKeyword, ConstructorKeyword, DeclareKeyword, GetKeyword, InferKeyword, IntrinsicKeyword, IsKeyword, KeyOfKeyword, ModuleKeyword, NamespaceKeyword, NeverKeyword, ReadonlyKeyword, RequireKeyword, NumberKeyword, ObjectKeyword, SetKeyword, StringKeyword, SymbolKeyword, TypeKeyword, UndefinedKeyword, UniqueKeyword, UnknownKeyword, FromKeyword, GlobalKeyword, BigIntKeyword, OfKeyword, // LastKeyword and LastToken and LastContextualKeyword // Parse tree nodes // Names QualifiedName, ComputedPropertyName, // Signature elements TypeParameter, Parameter, Decorator, // TypeMember PropertySignature, PropertyDeclaration, MethodSignature, MethodDeclaration, Constructor, GetAccessor, SetAccessor, CallSignature, ConstructSignature, IndexSignature, // Type TypePredicate, TypeReference, FunctionType, ConstructorType, TypeQuery, TypeLiteral, ArrayType, TupleType, OptionalType, RestType, UnionType, IntersectionType, ConditionalType, InferType, ParenthesizedType, ThisType, TypeOperator, IndexedAccessType, MappedType, LiteralType, NamedTupleMember, TemplateLiteralType, TemplateLiteralTypeSpan, ImportType, // Binding patterns ObjectBindingPattern, ArrayBindingPattern, BindingElement, // Expression ArrayLiteralExpression, ObjectLiteralExpression, PropertyAccessExpression, ElementAccessExpression, CallExpression, NewExpression, TaggedTemplateExpression, TypeAssertionExpression, ParenthesizedExpression, FunctionExpression, ArrowFunction, DeleteExpression, TypeOfExpression, VoidExpression, AwaitExpression, PrefixUnaryExpression, PostfixUnaryExpression, BinaryExpression, ConditionalExpression, TemplateExpression, YieldExpression, SpreadElement, ClassExpression, OmittedExpression, ExpressionWithTypeArguments, AsExpression, NonNullExpression, MetaProperty, SyntheticExpression, // Misc TemplateSpan, SemicolonClassElement, // Element Block, EmptyStatement, VariableStatement, ExpressionStatement, IfStatement, DoStatement, WhileStatement, ForStatement, ForInStatement, ForOfStatement, ContinueStatement, BreakStatement, ReturnStatement, WithStatement, SwitchStatement, LabeledStatement, ThrowStatement, TryStatement, DebuggerStatement, VariableDeclaration, VariableDeclarationList, FunctionDeclaration, ClassDeclaration, InterfaceDeclaration, TypeAliasDeclaration, EnumDeclaration, ModuleDeclaration, ModuleBlock, CaseBlock, NamespaceExportDeclaration, ImportEqualsDeclaration, ImportDeclaration, ImportClause, NamespaceImport, NamedImports, ImportSpecifier, ExportAssignment, ExportDeclaration, NamedExports, NamespaceExport, ExportSpecifier, MissingDeclaration, // Module references ExternalModuleReference, // JSX JsxElement, JsxSelfClosingElement, JsxOpeningElement, JsxClosingElement, JsxFragment, JsxOpeningFragment, JsxClosingFragment, JsxAttribute, JsxAttributes, JsxSpreadAttribute, JsxExpression, // Clauses CaseClause, DefaultClause, HeritageClause, CatchClause, // Property assignments PropertyAssignment, ShorthandPropertyAssignment, SpreadAssignment, // Enum EnumMember, // Unparsed UnparsedPrologue, UnparsedPrepend, UnparsedText, UnparsedInternalText, UnparsedSyntheticReference, // Top-level nodes SourceFile, Bundle, UnparsedSource, InputFiles, // JSDoc nodes JSDocTypeExpression, JSDocNameReference, JSDocAllType, // The * type JSDocUnknownType, // The ? type JSDocNullableType, JSDocNonNullableType, JSDocOptionalType, JSDocFunctionType, JSDocVariadicType, JSDocNamepathType, // https://jsdoc.app/about-namepaths.html JSDocComment, JSDocTypeLiteral, JSDocSignature, JSDocTag, JSDocAugmentsTag, JSDocImplementsTag, JSDocAuthorTag, JSDocDeprecatedTag, JSDocClassTag, JSDocPublicTag, JSDocPrivateTag, JSDocProtectedTag, JSDocReadonlyTag, JSDocCallbackTag, JSDocEnumTag, JSDocParameterTag, JSDocReturnTag, JSDocThisTag, JSDocTypeTag, JSDocTemplateTag, JSDocTypedefTag, JSDocSeeTag, JSDocPropertyTag, // Synthesized list SyntaxList, // Transformation nodes NotEmittedStatement, PartiallyEmittedExpression, CommaListExpression, MergeDeclarationMarker, EndOfDeclarationMarker, SyntheticReferenceExpression, // Enum value count Count } enum SyntaxKindMapped2 { FirstAssignment = SyntaxKindMapped.EqualsToken, LastAssignment = SyntaxKindMapped.CaretEqualsToken, FirstCompoundAssignment = SyntaxKindMapped.PlusEqualsToken, LastCompoundAssignment = SyntaxKindMapped.CaretEqualsToken, FirstReservedWord = SyntaxKindMapped.BreakKeyword, LastReservedWord = SyntaxKindMapped.WithKeyword, FirstKeyword = SyntaxKindMapped.BreakKeyword, LastKeyword = SyntaxKindMapped.OfKeyword, FirstFutureReservedWord = SyntaxKindMapped.ImplementsKeyword, LastFutureReservedWord = SyntaxKindMapped.YieldKeyword, FirstTypeNode = SyntaxKindMapped.TypePredicate, LastTypeNode = SyntaxKindMapped.ImportType, FirstPunctuation = SyntaxKindMapped.OpenBraceToken, LastPunctuation = SyntaxKindMapped.CaretEqualsToken, FirstToken = SyntaxKindMapped.Unknown, LastToken = SyntaxKindMapped.OfKeyword, FirstTriviaToken = SyntaxKindMapped.SingleLineCommentTrivia, LastTriviaToken = SyntaxKindMapped.ConflictMarkerTrivia, FirstLiteralToken = SyntaxKindMapped.NumericLiteral, LastLiteralToken = SyntaxKindMapped.NoSubstitutionTemplateLiteral, FirstTemplateToken = SyntaxKindMapped.NoSubstitutionTemplateLiteral, LastTemplateToken = SyntaxKindMapped.TemplateTail, FirstBinaryOperator = SyntaxKindMapped.LessThanToken, LastBinaryOperator = SyntaxKindMapped.CaretEqualsToken, FirstStatement = SyntaxKindMapped.VariableStatement, LastStatement = SyntaxKindMapped.DebuggerStatement, FirstNode = SyntaxKindMapped.QualifiedName, FirstJSDocNode = SyntaxKindMapped.JSDocTypeExpression, LastJSDocNode = SyntaxKindMapped.JSDocPropertyTag, FirstJSDocTagNode = SyntaxKindMapped.JSDocTag, LastJSDocTagNode = SyntaxKindMapped.JSDocPropertyTag, FirstContextualKeyword = SyntaxKindMapped.AbstractKeyword, LastContextualKeyword = SyntaxKindMapped.OfKeyword }; let data; try { fs.statSync(process.argv[2]); data = ts.sys.readFile(process.argv[2]); } catch (e) { data = process.argv[2]; } const dataStr = "" + data; const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, dataStr); let token = ts.SyntaxKind.Unknown; while (token != ts.SyntaxKind.EndOfFileToken) { token = scanner.scan(); const strToken = ts.SyntaxKind[token]; console.log(SyntaxKindMapped[strToken] || SyntaxKindMapped2[strToken], scanner.getTokenText()); }
the_stack
/* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- */ "use strict"; import FormInputInterfaces = require("../interfaces/common/FormInputInterfaces"); import VSSInterfaces = require("../interfaces/common/VSSInterfaces"); export interface ActorFilter extends RoleBasedFilter { } export interface ActorNotificationReason extends NotificationReason { matchedRoles?: string[]; } /** * Artifact filter options. Used in "follow" subscriptions. */ export interface ArtifactFilter extends BaseSubscriptionFilter { artifactId?: string; artifactType?: string; artifactUri?: string; type?: string; } export interface BaseSubscriptionFilter { eventType?: string; type?: string; } export interface BatchNotificationOperation { notificationOperation?: NotificationOperation; notificationQueryConditions?: NotificationQueryCondition[]; } export interface BlockFilter extends RoleBasedFilter { } export interface BlockSubscriptionChannel { type?: string; } /** * Default delivery preference for group subscribers. Indicates how the subscriber should be notified. */ export enum DefaultGroupDeliveryPreference { NoDelivery = -1, EachMember = 2, } export interface DiagnosticIdentity { displayName?: string; emailAddress?: string; id?: string; } export interface DiagnosticNotification { eventId?: number; eventType?: string; id?: number; messages?: NotificationDiagnosticLogMessage[]; recipients?: { [key: string] : DiagnosticRecipient; }; result?: string; stats?: { [key: string] : number; }; subscriptionId?: string; } export interface DiagnosticRecipient { recipient?: DiagnosticIdentity; status?: string; } export interface EmailHtmlSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } export interface EmailPlaintextSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } /** * Describes the subscription evaluation operation status. */ export enum EvaluationOperationStatus { /** * The operation object does not have the status set. */ NotSet = 0, /** * The operation has been queued. */ Queued = 1, /** * The operation is in progress. */ InProgress = 2, /** * The operation was cancelled by the user. */ Cancelled = 3, /** * The operation completed successfully. */ Succeeded = 4, /** * The operation completed with a failure. */ Failed = 5, /** * The operation timed out. */ TimedOut = 6, /** * The operation could not be found. */ NotFound = 7, } export interface EventBacklogStatus { captureTime?: Date; jobId?: string; lastEventBatchStartTime?: Date; lastEventProcessedTime?: Date; lastJobBatchStartTime?: Date; lastJobProcessedTime?: Date; oldestPendingEventTime?: Date; publisher?: string; unprocessedEvents?: number; } export interface EventBatch { endTime?: any; eventCounts?: { [key: string] : number; }; eventIds?: string; notificationCounts?: { [key: string] : number; }; preProcessEndTime?: any; preProcessStartTime?: any; processEndTime?: any; processStartTime?: any; startTime?: any; subscriptionCounts?: { [key: string] : number; }; } export interface EventProcessingLog extends NotificationJobDiagnosticLog { batches?: EventBatch[]; matcherResults?: MatcherResult[]; } /** * Set of flags used to determine which set of information is retrieved when querying for event publishers */ export enum EventPublisherQueryFlags { None = 0, /** * Include event types from the remote services too */ IncludeRemoteServices = 2, } /** * Encapsulates events result properties. It defines the total number of events used and the number of matched events. */ export interface EventsEvaluationResult { /** * Count of events evaluated. */ count?: number; /** * Count of matched events. */ matchedCount?: number; } /** * A transform request specify the properties of a notification event to be transformed. */ export interface EventTransformRequest { /** * Event payload. */ eventPayload: string; /** * Event type. */ eventType: string; /** * System inputs. */ systemInputs: { [key: string] : string; }; } /** * Result of transforming a notification event. */ export interface EventTransformResult { /** * Transformed html content. */ content: string; /** * Calculated data. */ data?: any; /** * Calculated system inputs. */ systemInputs?: { [key: string] : string; }; } /** * Set of flags used to determine which set of information is retrieved when querying for eventtypes */ export enum EventTypeQueryFlags { None = 0, /** * IncludeFields will include all fields and their types */ IncludeFields = 1, } export interface ExpressionFilter extends BaseSubscriptionFilter { criteria?: ExpressionFilterModel; type?: string; } /** * Subscription Filter Clause represents a single clause in a subscription filter e.g. If the subscription has the following criteria "Project Name = [Current Project] AND Assigned To = [Me] it will be represented as two Filter Clauses Clause 1: Index = 1, Logical Operator: NULL , FieldName = 'Project Name', Operator = '=', Value = '[Current Project]' Clause 2: Index = 2, Logical Operator: 'AND' , FieldName = 'Assigned To' , Operator = '=', Value = '[Me]' */ export interface ExpressionFilterClause { fieldName?: string; /** * The order in which this clause appeared in the filter query */ index?: number; /** * Logical Operator 'AND', 'OR' or NULL (only for the first clause in the filter) */ logicalOperator?: string; operator?: string; value?: string; } /** * Represents a hierarchy of SubscritionFilterClauses that have been grouped together through either adding a group in the WebUI or using parethesis in the Subscription condition string */ export interface ExpressionFilterGroup { /** * The index of the last FilterClause in this group */ end?: number; /** * Level of the group, since groups can be nested for each nested group the level will increase by 1 */ level?: number; /** * The index of the first FilterClause in this group */ start?: number; } export interface ExpressionFilterModel { /** * Flat list of clauses in this subscription */ clauses?: ExpressionFilterClause[]; /** * Grouping of clauses in the subscription */ groups?: ExpressionFilterGroup[]; /** * Max depth of the Subscription tree */ maxGroupLevel?: number; } export interface FieldInputValues extends FormInputInterfaces.InputValues { operators?: number[]; } export interface FieldValuesQuery extends FormInputInterfaces.InputValuesQuery { inputValues?: FieldInputValues[]; scope?: string; } export interface GeneratedNotification { recipients?: DiagnosticIdentity[]; } export interface GroupSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } /** * Abstraction interface for the diagnostic log. Primarily for deserialization. */ export interface INotificationDiagnosticLog { /** * Identifier used for correlating to other diagnostics that may have been recorded elsewhere. */ activityId?: string; /** * Description of what subscription or notification job is being logged. */ description?: string; /** * Time the log ended. */ endTime?: Date; /** * Unique instance identifier. */ id?: string; /** * Type of information being logged. */ logType?: string; /** * List of log messages. */ messages?: NotificationDiagnosticLogMessage[]; /** * Dictionary of log properties and settings for the job. */ properties?: { [key: string] : string; }; /** * This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. */ source?: string; /** * Time the log started. */ startTime?: Date; } export interface ISubscriptionChannel { type?: string; } export interface ISubscriptionFilter { eventType?: string; type?: string; } export interface MatcherResult { matcher?: string; stats?: { [key: string] : { [key: string] : number; }; }; } export interface MessageQueueSubscriptionChannel { type?: string; } export interface NotificationAdminSettings { /** * The default group delivery preference for groups in this collection */ defaultGroupDeliveryPreference?: DefaultGroupDeliveryPreference; } export interface NotificationAdminSettingsUpdateParameters { defaultGroupDeliveryPreference?: DefaultGroupDeliveryPreference; } export interface NotificationBacklogStatus { captureTime?: Date; channel?: string; jobId?: string; lastJobBatchStartTime?: Date; lastJobProcessedTime?: Date; lastNotificationBatchStartTime?: Date; lastNotificationProcessedTime?: Date; oldestPendingNotificationTime?: Date; publisher?: string; /** * Null status is unprocessed */ status?: string; unprocessedNotifications?: number; } export interface NotificationBatch { endTime?: any; notificationCount?: number; notificationIds?: string; problematicNotifications?: DiagnosticNotification[]; startTime?: any; } export interface NotificationDeliveryLog extends NotificationJobDiagnosticLog { batches?: NotificationBatch[]; } /** * Abstract base class for all of the diagnostic logs. */ export interface NotificationDiagnosticLog { /** * Identifier used for correlating to other diagnostics that may have been recorded elsewhere. */ activityId?: string; description?: string; endTime?: Date; errors?: number; /** * Unique instance identifier. */ id?: string; logType?: string; messages?: NotificationDiagnosticLogMessage[]; properties?: { [key: string] : string; }; /** * This identifier depends on the logType. For notification jobs, this will be the job Id. For subscription tracing, this will be a special root Guid with the subscription Id encoded. */ source?: string; startTime?: Date; warnings?: number; } export interface NotificationDiagnosticLogMessage { /** * Corresponds to .Net TraceLevel enumeration */ level?: number; message?: string; time?: any; } export interface NotificationEventBacklogStatus { eventBacklogStatus?: EventBacklogStatus[]; notificationBacklogStatus?: NotificationBacklogStatus[]; } /** * Encapsulates the properties of a filterable field. A filterable field is a field in an event that can used to filter notifications for a certain event type. */ export interface NotificationEventField { /** * Gets or sets the type of this field. */ fieldType?: NotificationEventFieldType; /** * Gets or sets the unique identifier of this field. */ id?: string; /** * Gets or sets the name of this field. */ name?: string; /** * Gets or sets the path to the field in the event object. This path can be either Json Path or XPath, depending on if the event will be serialized into Json or XML */ path?: string; /** * Gets or sets the scopes that this field supports. If not specified then the event type scopes apply. */ supportedScopes?: string[]; } /** * Encapsulates the properties of a field type. It includes a unique id for the operator and a localized string for display name */ export interface NotificationEventFieldOperator { /** * Gets or sets the display name of an operator */ displayName?: string; /** * Gets or sets the id of an operator */ id?: string; } /** * Encapsulates the properties of a field type. It describes the data type of a field, the operators it support and how to populate it in the UI */ export interface NotificationEventFieldType { /** * Gets or sets the unique identifier of this field type. */ id?: string; operatorConstraints?: OperatorConstraint[]; /** * Gets or sets the list of operators that this type supports. */ operators?: NotificationEventFieldOperator[]; subscriptionFieldType?: SubscriptionFieldType; /** * Gets or sets the value definition of this field like the getValuesMethod and template to display in the UI */ value?: ValueDefinition; } /** * Encapsulates the properties of a notification event publisher. */ export interface NotificationEventPublisher { id?: string; subscriptionManagementInfo?: SubscriptionManagement; url?: string; } /** * Encapsulates the properties of an event role. An event Role is used for role based subscription for example for a buildCompletedEvent, one role is request by field */ export interface NotificationEventRole { /** * Gets or sets an Id for that role, this id is used by the event. */ id?: string; /** * Gets or sets the Name for that role, this name is used for UI display. */ name?: string; /** * Gets or sets whether this role can be a group or just an individual user */ supportsGroups?: boolean; } /** * Encapsulates the properties of an event type. It defines the fields, that can be used for filtering, for that event type. */ export interface NotificationEventType { category?: NotificationEventTypeCategory; /** * Gets or sets the color representing this event type. Example: rgb(128,245,211) or #fafafa */ color?: string; customSubscriptionsAllowed?: boolean; eventPublisher?: NotificationEventPublisher; fields?: { [key: string] : NotificationEventField; }; hasInitiator?: boolean; /** * Gets or sets the icon representing this event type. Can be a URL or a CSS class. Example: css://some-css-class */ icon?: string; /** * Gets or sets the unique identifier of this event definition. */ id?: string; /** * Gets or sets the name of this event definition. */ name?: string; roles?: NotificationEventRole[]; /** * Gets or sets the scopes that this event type supports */ supportedScopes?: string[]; /** * Gets or sets the rest end point to get this event type details (fields, fields types) */ url?: string; } /** * Encapsulates the properties of a category. A category will be used by the UI to group event types */ export interface NotificationEventTypeCategory { /** * Gets or sets the unique identifier of this category. */ id?: string; /** * Gets or sets the friendly name of this category. */ name?: string; } export interface NotificationJobDiagnosticLog extends NotificationDiagnosticLog { result?: string; stats?: { [key: string] : { [key: string] : number; }; }; } export enum NotificationOperation { None = 0, SuspendUnprocessed = 1, } export interface NotificationQueryCondition { eventInitiator?: string; eventType?: string; subscriber?: string; subscriptionId?: string; } export interface NotificationReason { notificationReasonType?: NotificationReasonType; targetIdentities?: VSSInterfaces.IdentityRef[]; } export enum NotificationReasonType { Unknown = 0, Follows = 1, Personal = 2, PersonalAlias = 3, DirectMember = 4, IndirectMember = 5, GroupAlias = 6, SubscriptionAlias = 7, SingleRole = 8, DirectMemberGroupRole = 9, InDirectMemberGroupRole = 10, AliasMemberGroupRole = 11, } /** * Encapsulates notifications result properties. It defines the number of notifications and the recipients of notifications. */ export interface NotificationsEvaluationResult { /** * Count of generated notifications */ count?: number; } export interface NotificationStatistic { date?: Date; hitCount?: number; path?: string; type?: NotificationStatisticType; user?: VSSInterfaces.IdentityRef; } export interface NotificationStatisticsQuery { conditions?: NotificationStatisticsQueryConditions[]; } export interface NotificationStatisticsQueryConditions { endDate?: Date; hitCountMinimum?: number; path?: string; startDate?: Date; type?: NotificationStatisticType; user?: VSSInterfaces.IdentityRef; } export enum NotificationStatisticType { NotificationBySubscription = 0, EventsByEventType = 1, NotificationByEventType = 2, EventsByEventTypePerUser = 3, NotificationByEventTypePerUser = 4, Events = 5, Notifications = 6, NotificationFailureBySubscription = 7, UnprocessedRangeStart = 100, UnprocessedEventsByPublisher = 101, UnprocessedEventDelayByPublisher = 102, UnprocessedNotificationsByChannelByPublisher = 103, UnprocessedNotificationDelayByChannelByPublisher = 104, DelayRangeStart = 200, TotalPipelineTime = 201, NotificationPipelineTime = 202, EventPipelineTime = 203, HourlyRangeStart = 1000, HourlyNotificationBySubscription = 1001, HourlyEventsByEventTypePerUser = 1002, HourlyEvents = 1003, HourlyNotifications = 1004, HourlyUnprocessedEventsByPublisher = 1101, HourlyUnprocessedEventDelayByPublisher = 1102, HourlyUnprocessedNotificationsByChannelByPublisher = 1103, HourlyUnprocessedNotificationDelayByChannelByPublisher = 1104, HourlyTotalPipelineTime = 1201, HourlyNotificationPipelineTime = 1202, HourlyEventPipelineTime = 1203, } /** * A subscriber is a user or group that has the potential to receive notifications. */ export interface NotificationSubscriber { /** * Indicates how the subscriber should be notified by default. */ deliveryPreference?: NotificationSubscriberDeliveryPreference; flags?: SubscriberFlags; /** * Identifier of the subscriber. */ id?: string; /** * Preferred email address of the subscriber. A null or empty value indicates no preferred email address has been set. */ preferredEmailAddress?: string; } /** * Delivery preference for a subscriber. Indicates how the subscriber should be notified. */ export enum NotificationSubscriberDeliveryPreference { /** * Do not send notifications by default. Note: notifications can still be delivered to this subscriber, for example via a custom subscription. */ NoDelivery = -1, /** * Deliver notifications to the subscriber's preferred email address. */ PreferredEmailAddress = 1, /** * Deliver notifications to each member of the group representing the subscriber. Only applicable when the subscriber is a group. */ EachMember = 2, /** * Use default */ UseDefault = 3, } /** * Updates to a subscriber. Typically used to change (or set) a preferred email address or default delivery preference. */ export interface NotificationSubscriberUpdateParameters { /** * New delivery preference for the subscriber (indicates how the subscriber should be notified). */ deliveryPreference?: NotificationSubscriberDeliveryPreference; /** * New preferred email address for the subscriber. Specify an empty string to clear the current address. */ preferredEmailAddress?: string; } /** * A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. */ export interface NotificationSubscription { /** * Links to related resources, APIs, and views for the subscription. */ _links?: any; /** * Admin-managed settings for the subscription. Only applies when the subscriber is a group. */ adminSettings?: SubscriptionAdminSettings; /** * Channel for delivering notifications triggered by the subscription. */ channel?: ISubscriptionChannel; /** * Description of the subscription. Typically describes filter criteria which helps identity the subscription. */ description?: string; /** * Diagnostics for this subscription. */ diagnostics?: SubscriptionDiagnostics; /** * Any extra properties like detailed description for different contexts, user/group contexts */ extendedProperties?: { [key: string] : string; }; /** * Matching criteria for the subscription. ExpressionFilter */ filter: ISubscriptionFilter; /** * Read-only indicators that further describe the subscription. */ flags?: SubscriptionFlags; /** * Subscription identifier. */ id?: string; /** * User that last modified (or created) the subscription. */ lastModifiedBy?: VSSInterfaces.IdentityRef; /** * Date when the subscription was last modified. If the subscription has not been updated since it was created, this value will indicate when the subscription was created. */ modifiedDate?: Date; /** * The permissions the user have for this subscriptions. */ permissions?: SubscriptionPermissions; /** * The container in which events must be published from in order to be matched by the subscription. If empty, the scope is the current host (typically an account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. */ scope?: SubscriptionScope; /** * Status of the subscription. Typically indicates whether the subscription is enabled or not. */ status?: SubscriptionStatus; /** * Message that provides more details about the status of the subscription. */ statusMessage?: string; /** * User or group that will receive notifications for events matching the subscription's filter criteria. */ subscriber?: VSSInterfaces.IdentityRef; /** * REST API URL of the subscriotion. */ url?: string; /** * User-managed settings for the subscription. Only applies when the subscriber is a group. Typically used to indicate whether the calling user is opted in or out of a group subscription. */ userSettings?: SubscriptionUserSettings; } /** * Parameters for creating a new subscription. A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. */ export interface NotificationSubscriptionCreateParameters { /** * Channel for delivering notifications triggered by the new subscription. */ channel?: ISubscriptionChannel; /** * Brief description for the new subscription. Typically describes filter criteria which helps identity the subscription. */ description?: string; /** * Matching criteria for the new subscription. ExpressionFilter */ filter: ISubscriptionFilter; /** * The container in which events must be published from in order to be matched by the new subscription. If not specified, defaults to the current host (typically an account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. */ scope?: SubscriptionScope; /** * User or group that will receive notifications for events matching the subscription's filter criteria. If not specified, defaults to the calling user. */ subscriber?: VSSInterfaces.IdentityRef; } export interface NotificationSubscriptionTemplate { description?: string; filter: ISubscriptionFilter; id?: string; notificationEventInformation?: NotificationEventType; type?: SubscriptionTemplateType; } /** * Parameters for updating an existing subscription. A subscription defines criteria for matching events and how the subscription's subscriber should be notified about those events. Note: only the fields to be updated should be set. */ export interface NotificationSubscriptionUpdateParameters { /** * Admin-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group. */ adminSettings?: SubscriptionAdminSettings; /** * Channel for delivering notifications triggered by the subscription. */ channel?: ISubscriptionChannel; /** * Updated description for the subscription. Typically describes filter criteria which helps identity the subscription. */ description?: string; /** * Matching criteria for the subscription. ExpressionFilter */ filter?: ISubscriptionFilter; /** * The container in which events must be published from in order to be matched by the new subscription. If not specified, defaults to the current host (typically the current account or project collection). For example, a subscription scoped to project A will not produce notifications for events published from project B. */ scope?: SubscriptionScope; /** * Updated status for the subscription. Typically used to enable or disable a subscription. */ status?: SubscriptionStatus; /** * Optional message that provides more details about the updated status. */ statusMessage?: string; /** * User-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group. Typically used to opt-in or opt-out a user from a group subscription. */ userSettings?: SubscriptionUserSettings; } /** * Encapsulates the properties of an operator constraint. An operator constraint defines if some operator is available only for specific scope like a project scope. */ export interface OperatorConstraint { operator?: string; /** * Gets or sets the list of scopes that this type supports. */ supportedScopes?: string[]; } export interface ProcessedEvent { /** * All of the users that were associated with this event and their role. */ actors?: VSSInterfaces.EventActor[]; allowedChannels?: string; artifactUri?: string; deliveryIdentities?: ProcessingIdentities; /** * Evaluations for each user */ evaluations?: { [key: string] : SubscriptionEvaluation; }; eventId?: number; /** * Which members were excluded from evaluation (only applies to ActorMatcher subscriptions) */ exclusions?: VSSInterfaces.EventActor[]; /** * Which members were included for evaluation (only applies to ActorMatcher subscriptions) */ inclusions?: VSSInterfaces.EventActor[]; notifications?: GeneratedNotification[]; } export interface ProcessingDiagnosticIdentity extends DiagnosticIdentity { deliveryPreference?: string; isActive?: boolean; isGroup?: boolean; message?: string; } export interface ProcessingIdentities { excludedIdentities?: { [key: string] : ProcessingDiagnosticIdentity; }; includedIdentities?: { [key: string] : ProcessingDiagnosticIdentity; }; messages?: NotificationDiagnosticLogMessage[]; missingIdentities?: string[]; properties?: { [key: string] : string; }; } export interface RoleBasedFilter extends ExpressionFilter { exclusions?: string[]; inclusions?: string[]; } export interface ServiceBusSubscriptionChannel { type?: string; } export interface ServiceHooksSubscriptionChannel { type?: string; } export interface SoapSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } export enum SubscriberFlags { None = 0, /** * Subscriber's delivery preferences could be updated */ DeliveryPreferencesEditable = 2, /** * Subscriber's delivery preferences supports email delivery */ SupportsPreferredEmailAddressDelivery = 4, /** * Subscriber's delivery preferences supports individual members delivery(group expansion) */ SupportsEachMemberDelivery = 8, /** * Subscriber's delivery preferences supports no delivery */ SupportsNoDelivery = 16, /** * Subscriber is a user */ IsUser = 32, /** * Subscriber is a group */ IsGroup = 64, /** * Subscriber is a team */ IsTeam = 128, } /** * Admin-managed settings for a group subscription. */ export interface SubscriptionAdminSettings { /** * If true, members of the group subscribed to the associated subscription cannot opt (choose not to get notified) */ blockUserOptOut: boolean; } export interface SubscriptionChannelWithAddress { address?: string; type?: string; useCustomAddress?: boolean; } /** * Contains all the diagnostics settings for a subscription. */ export interface SubscriptionDiagnostics { /** * Diagnostics settings for retaining delivery results. Used for Service Hooks subscriptions. */ deliveryResults?: SubscriptionTracing; /** * Diagnostics settings for troubleshooting notification delivery. */ deliveryTracing?: SubscriptionTracing; /** * Diagnostics settings for troubleshooting event matching. */ evaluationTracing?: SubscriptionTracing; } export interface SubscriptionEvaluation { clauses?: SubscriptionEvaluationClause[]; user?: DiagnosticIdentity; } export interface SubscriptionEvaluationClause { clause?: string; order?: number; result?: boolean; } /** * Encapsulates the properties of a SubscriptionEvaluationRequest. It defines the subscription to be evaluated and time interval for events used in evaluation. */ export interface SubscriptionEvaluationRequest { /** * The min created date for the events used for matching in UTC. Use all events created since this date */ minEventsCreatedDate: Date; /** * User or group that will receive notifications for events matching the subscription's filter criteria. If not specified, defaults to the calling user. */ subscriptionCreateParameters?: NotificationSubscriptionCreateParameters; } /** * Encapsulates the subscription evaluation results. It defines the Date Interval that was used, number of events evaluated and events and notifications results */ export interface SubscriptionEvaluationResult { /** * Subscription evaluation job status */ evaluationJobStatus?: EvaluationOperationStatus; /** * Subscription evaluation events results. */ events?: EventsEvaluationResult; /** * The requestId which is the subscription evaluation jobId */ id?: string; /** * Subscription evaluation notification results. */ notifications?: NotificationsEvaluationResult; } /** * Encapsulates the subscription evaluation settings needed for the UI */ export interface SubscriptionEvaluationSettings { /** * Indicates whether subscription evaluation before saving is enabled or not */ enabled?: boolean; /** * Time interval to check on subscription evaluation job in seconds */ interval?: number; /** * Threshold on the number of notifications for considering a subscription too noisy */ threshold?: number; /** * Time out for the subscription evaluation check in seconds */ timeOut?: number; } export enum SubscriptionFieldType { String = 1, Integer = 2, DateTime = 3, PlainText = 5, Html = 7, TreePath = 8, History = 9, Double = 10, Guid = 11, Boolean = 12, Identity = 13, PicklistInteger = 14, PicklistString = 15, PicklistDouble = 16, TeamProject = 17, } /** * Read-only indicators that further describe the subscription. */ export enum SubscriptionFlags { /** * None */ None = 0, /** * Subscription's subscriber is a group, not a user */ GroupSubscription = 1, /** * Subscription is contributed and not persisted. This means certain fields of the subscription, like Filter, are read-only. */ ContributedSubscription = 2, /** * A user that is member of the subscription's subscriber group can opt in/out of the subscription. */ CanOptOut = 4, /** * If the subscriber is a group, is it a team. */ TeamSubscription = 8, /** * For role based subscriptions, there is an expectation that there will always be at least one actor that matches */ OneActorMatches = 16, } /** * Encapsulates the properties needed to manage subscriptions, opt in and out of subscriptions. */ export interface SubscriptionManagement { serviceInstanceType?: string; url?: string; } /** * The permissions that a user has to a certain subscription */ export enum SubscriptionPermissions { /** * None */ None = 0, /** * full view of description, filters, etc. Not limited. */ View = 1, /** * update subscription */ Edit = 2, /** * delete subscription */ Delete = 4, } /** * Notification subscriptions query input. */ export interface SubscriptionQuery { /** * One or more conditions to query on. If more than 2 conditions are specified, the combined results of each condition is returned (i.e. conditions are logically OR'ed). */ conditions: SubscriptionQueryCondition[]; /** * Flags the refine the types of subscriptions that will be returned from the query. */ queryFlags?: SubscriptionQueryFlags; } /** * Conditions a subscription must match to qualify for the query result set. Not all fields are required. A subscription must match all conditions specified in order to qualify for the result set. */ export interface SubscriptionQueryCondition { /** * Filter conditions that matching subscriptions must have. Typically only the filter's type and event type are used for matching. */ filter?: ISubscriptionFilter; /** * Flags to specify the the type subscriptions to query for. */ flags?: SubscriptionFlags; /** * Scope that matching subscriptions must have. */ scope?: string; /** * ID of the subscriber (user or group) that matching subscriptions must be subscribed to. */ subscriberId?: string; /** * ID of the subscription to query for. */ subscriptionId?: string; } /** * Flags that influence the result set of a subscription query. */ export enum SubscriptionQueryFlags { None = 0, /** * Include subscriptions with invalid subscribers. */ IncludeInvalidSubscriptions = 2, /** * Include subscriptions marked for deletion. */ IncludeDeletedSubscriptions = 4, /** * Include the full filter details with each subscription. */ IncludeFilterDetails = 8, /** * For a subscription the caller does not have permission to view, return basic (non-confidential) information. */ AlwaysReturnBasicInformation = 16, /** * Include system subscriptions. */ IncludeSystemSubscriptions = 32, } /** * A resource, typically an account or project, in which events are published from. */ export interface SubscriptionScope extends VSSInterfaces.EventScope { } /** * Subscription status values. A value greater than or equal to zero indicates the subscription is enabled. A negative value indicates the subscription is disabled. */ export enum SubscriptionStatus { /** * Subscription is disabled because it generated a high volume of notifications. */ JailedByNotificationsVolume = -200, /** * Subscription is disabled and will be deleted. */ PendingDeletion = -100, /** * Subscription is disabled because of an Argument Exception while processing the subscription */ DisabledArgumentException = -12, /** * Subscription is disabled because the project is invalid */ DisabledProjectInvalid = -11, /** * Subscription is disabled because the identity does not have the appropriate permissions */ DisabledMissingPermissions = -10, /** * Subscription is disabled service due to failures. */ DisabledFromProbation = -9, /** * Subscription is disabled because the identity is no longer active */ DisabledInactiveIdentity = -8, /** * Subscription is disabled because message queue is not supported. */ DisabledMessageQueueNotSupported = -7, /** * Subscription is disabled because its subscriber is unknown. */ DisabledMissingIdentity = -6, /** * Subscription is disabled because it has an invalid role expression. */ DisabledInvalidRoleExpression = -5, /** * Subscription is disabled because it has an invalid filter expression. */ DisabledInvalidPathClause = -4, /** * Subscription is disabled because it is a duplicate of a default subscription. */ DisabledAsDuplicateOfDefault = -3, /** * Subscription is disabled by an administrator, not the subscription's subscriber. */ DisabledByAdmin = -2, /** * Subscription is disabled, typically by the owner of the subscription, and will not produce any notifications. */ Disabled = -1, /** * Subscription is active. */ Enabled = 0, /** * Subscription is active, but is on probation due to failed deliveries or other issues with the subscription. */ EnabledOnProbation = 1, } /** * Set of flags used to determine which set of templates is retrieved when querying for subscription templates */ export enum SubscriptionTemplateQueryFlags { None = 0, /** * Include user templates */ IncludeUser = 1, /** * Include group templates */ IncludeGroup = 2, /** * Include user and group templates */ IncludeUserAndGroup = 4, /** * Include the event type details like the fields and operators */ IncludeEventTypeInformation = 22, } export enum SubscriptionTemplateType { User = 0, Team = 1, Both = 2, None = 3, } export interface SubscriptionTraceDiagnosticLog extends NotificationDiagnosticLog { /** * Indicates the job Id that processed or delivered this subscription */ jobId?: string; /** * Indicates unique instance identifier for the job that processed or delivered this subscription */ jobInstanceId?: string; subscriptionId?: string; } export interface SubscriptionTraceEventProcessingLog extends SubscriptionTraceDiagnosticLog { channel?: string; evaluationIdentities?: ProcessingIdentities; /** * Which members opted out from receiving notifications from this subscription */ optedOut?: DiagnosticIdentity[]; processedEvents?: { [key: number] : ProcessedEvent; }; } export interface SubscriptionTraceNotificationDeliveryLog extends SubscriptionTraceDiagnosticLog { notifications?: DiagnosticNotification[]; } /** * Data controlling a single diagnostic setting for a subscription. */ export interface SubscriptionTracing { /** * Indicates whether the diagnostic tracing is enabled or not. */ enabled: boolean; /** * Trace until the specified end date. */ endDate?: Date; /** * The maximum number of result details to trace. */ maxTracedEntries?: number; /** * The date and time tracing started. */ startDate?: Date; /** * Trace until remaining count reaches 0. */ tracedEntries?: number; } /** * User-managed settings for a group subscription. */ export interface SubscriptionUserSettings { /** * Indicates whether the user will receive notifications for the associated group subscription. */ optedOut: boolean; } export interface UnsupportedFilter extends BaseSubscriptionFilter { type?: string; } export interface UnsupportedSubscriptionChannel { type?: string; } /** * Parameters to update diagnostics settings for a subscription. */ export interface UpdateSubscripitonDiagnosticsParameters { /** * Diagnostics settings for retaining delivery results. Used for Service Hooks subscriptions. */ deliveryResults?: UpdateSubscripitonTracingParameters; /** * Diagnostics settings for troubleshooting notification delivery. */ deliveryTracing?: UpdateSubscripitonTracingParameters; /** * Diagnostics settings for troubleshooting event matching. */ evaluationTracing?: UpdateSubscripitonTracingParameters; } /** * Parameters to update a specific diagnostic setting. */ export interface UpdateSubscripitonTracingParameters { /** * Indicates whether to enable to disable the diagnostic tracing. */ enabled: boolean; } export interface UserSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } export interface UserSystemSubscriptionChannel extends SubscriptionChannelWithAddress { type?: string; } /** * Encapsulates the properties of a field value definition. It has the information needed to retrieve the list of possible values for a certain field and how to handle that field values in the UI. This information includes what type of object this value represents, which property to use for UI display and which property to use for saving the subscription */ export interface ValueDefinition { /** * Gets or sets the data source. */ dataSource?: FormInputInterfaces.InputValue[]; /** * Gets or sets the rest end point. */ endPoint?: string; /** * Gets or sets the result template. */ resultTemplate?: string; } export var TypeInfo = { ActorNotificationReason: <any>{ }, BatchNotificationOperation: <any>{ }, DefaultGroupDeliveryPreference: { enumValues: { "noDelivery": -1, "eachMember": 2 } }, EvaluationOperationStatus: { enumValues: { "notSet": 0, "queued": 1, "inProgress": 2, "cancelled": 3, "succeeded": 4, "failed": 5, "timedOut": 6, "notFound": 7 } }, EventBacklogStatus: <any>{ }, EventProcessingLog: <any>{ }, EventPublisherQueryFlags: { enumValues: { "none": 0, "includeRemoteServices": 2 } }, EventTypeQueryFlags: { enumValues: { "none": 0, "includeFields": 1 } }, INotificationDiagnosticLog: <any>{ }, NotificationAdminSettings: <any>{ }, NotificationAdminSettingsUpdateParameters: <any>{ }, NotificationBacklogStatus: <any>{ }, NotificationDeliveryLog: <any>{ }, NotificationDiagnosticLog: <any>{ }, NotificationEventBacklogStatus: <any>{ }, NotificationEventField: <any>{ }, NotificationEventFieldType: <any>{ }, NotificationEventType: <any>{ }, NotificationJobDiagnosticLog: <any>{ }, NotificationOperation: { enumValues: { "none": 0, "suspendUnprocessed": 1 } }, NotificationReason: <any>{ }, NotificationReasonType: { enumValues: { "unknown": 0, "follows": 1, "personal": 2, "personalAlias": 3, "directMember": 4, "indirectMember": 5, "groupAlias": 6, "subscriptionAlias": 7, "singleRole": 8, "directMemberGroupRole": 9, "inDirectMemberGroupRole": 10, "aliasMemberGroupRole": 11 } }, NotificationStatistic: <any>{ }, NotificationStatisticsQuery: <any>{ }, NotificationStatisticsQueryConditions: <any>{ }, NotificationStatisticType: { enumValues: { "notificationBySubscription": 0, "eventsByEventType": 1, "notificationByEventType": 2, "eventsByEventTypePerUser": 3, "notificationByEventTypePerUser": 4, "events": 5, "notifications": 6, "notificationFailureBySubscription": 7, "unprocessedRangeStart": 100, "unprocessedEventsByPublisher": 101, "unprocessedEventDelayByPublisher": 102, "unprocessedNotificationsByChannelByPublisher": 103, "unprocessedNotificationDelayByChannelByPublisher": 104, "delayRangeStart": 200, "totalPipelineTime": 201, "notificationPipelineTime": 202, "eventPipelineTime": 203, "hourlyRangeStart": 1000, "hourlyNotificationBySubscription": 1001, "hourlyEventsByEventTypePerUser": 1002, "hourlyEvents": 1003, "hourlyNotifications": 1004, "hourlyUnprocessedEventsByPublisher": 1101, "hourlyUnprocessedEventDelayByPublisher": 1102, "hourlyUnprocessedNotificationsByChannelByPublisher": 1103, "hourlyUnprocessedNotificationDelayByChannelByPublisher": 1104, "hourlyTotalPipelineTime": 1201, "hourlyNotificationPipelineTime": 1202, "hourlyEventPipelineTime": 1203 } }, NotificationSubscriber: <any>{ }, NotificationSubscriberDeliveryPreference: { enumValues: { "noDelivery": -1, "preferredEmailAddress": 1, "eachMember": 2, "useDefault": 3 } }, NotificationSubscriberUpdateParameters: <any>{ }, NotificationSubscription: <any>{ }, NotificationSubscriptionTemplate: <any>{ }, NotificationSubscriptionUpdateParameters: <any>{ }, SubscriberFlags: { enumValues: { "none": 0, "deliveryPreferencesEditable": 2, "supportsPreferredEmailAddressDelivery": 4, "supportsEachMemberDelivery": 8, "supportsNoDelivery": 16, "isUser": 32, "isGroup": 64, "isTeam": 128 } }, SubscriptionDiagnostics: <any>{ }, SubscriptionEvaluationRequest: <any>{ }, SubscriptionEvaluationResult: <any>{ }, SubscriptionFieldType: { enumValues: { "string": 1, "integer": 2, "dateTime": 3, "plainText": 5, "html": 7, "treePath": 8, "history": 9, "double": 10, "guid": 11, "boolean": 12, "identity": 13, "picklistInteger": 14, "picklistString": 15, "picklistDouble": 16, "teamProject": 17 } }, SubscriptionFlags: { enumValues: { "none": 0, "groupSubscription": 1, "contributedSubscription": 2, "canOptOut": 4, "teamSubscription": 8, "oneActorMatches": 16 } }, SubscriptionPermissions: { enumValues: { "none": 0, "view": 1, "edit": 2, "delete": 4 } }, SubscriptionQuery: <any>{ }, SubscriptionQueryCondition: <any>{ }, SubscriptionQueryFlags: { enumValues: { "none": 0, "includeInvalidSubscriptions": 2, "includeDeletedSubscriptions": 4, "includeFilterDetails": 8, "alwaysReturnBasicInformation": 16, "includeSystemSubscriptions": 32 } }, SubscriptionStatus: { enumValues: { "jailedByNotificationsVolume": -200, "pendingDeletion": -100, "disabledArgumentException": -12, "disabledProjectInvalid": -11, "disabledMissingPermissions": -10, "disabledFromProbation": -9, "disabledInactiveIdentity": -8, "disabledMessageQueueNotSupported": -7, "disabledMissingIdentity": -6, "disabledInvalidRoleExpression": -5, "disabledInvalidPathClause": -4, "disabledAsDuplicateOfDefault": -3, "disabledByAdmin": -2, "disabled": -1, "enabled": 0, "enabledOnProbation": 1 } }, SubscriptionTemplateQueryFlags: { enumValues: { "none": 0, "includeUser": 1, "includeGroup": 2, "includeUserAndGroup": 4, "includeEventTypeInformation": 22 } }, SubscriptionTemplateType: { enumValues: { "user": 0, "team": 1, "both": 2, "none": 3 } }, SubscriptionTraceDiagnosticLog: <any>{ }, SubscriptionTraceEventProcessingLog: <any>{ }, SubscriptionTraceNotificationDeliveryLog: <any>{ }, SubscriptionTracing: <any>{ }, }; TypeInfo.ActorNotificationReason.fields = { notificationReasonType: { enumType: TypeInfo.NotificationReasonType } }; TypeInfo.BatchNotificationOperation.fields = { notificationOperation: { enumType: TypeInfo.NotificationOperation } }; TypeInfo.EventBacklogStatus.fields = { captureTime: { isDate: true, }, lastEventBatchStartTime: { isDate: true, }, lastEventProcessedTime: { isDate: true, }, lastJobBatchStartTime: { isDate: true, }, lastJobProcessedTime: { isDate: true, }, oldestPendingEventTime: { isDate: true, } }; TypeInfo.EventProcessingLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.INotificationDiagnosticLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.NotificationAdminSettings.fields = { defaultGroupDeliveryPreference: { enumType: TypeInfo.DefaultGroupDeliveryPreference } }; TypeInfo.NotificationAdminSettingsUpdateParameters.fields = { defaultGroupDeliveryPreference: { enumType: TypeInfo.DefaultGroupDeliveryPreference } }; TypeInfo.NotificationBacklogStatus.fields = { captureTime: { isDate: true, }, lastJobBatchStartTime: { isDate: true, }, lastJobProcessedTime: { isDate: true, }, lastNotificationBatchStartTime: { isDate: true, }, lastNotificationProcessedTime: { isDate: true, }, oldestPendingNotificationTime: { isDate: true, } }; TypeInfo.NotificationDeliveryLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.NotificationDiagnosticLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.NotificationEventBacklogStatus.fields = { eventBacklogStatus: { isArray: true, typeInfo: TypeInfo.EventBacklogStatus }, notificationBacklogStatus: { isArray: true, typeInfo: TypeInfo.NotificationBacklogStatus } }; TypeInfo.NotificationEventField.fields = { fieldType: { typeInfo: TypeInfo.NotificationEventFieldType } }; TypeInfo.NotificationEventFieldType.fields = { subscriptionFieldType: { enumType: TypeInfo.SubscriptionFieldType } }; TypeInfo.NotificationEventType.fields = { fields: { isDictionary: true, dictionaryValueTypeInfo: TypeInfo.NotificationEventField } }; TypeInfo.NotificationJobDiagnosticLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.NotificationReason.fields = { notificationReasonType: { enumType: TypeInfo.NotificationReasonType } }; TypeInfo.NotificationStatistic.fields = { date: { isDate: true, }, type: { enumType: TypeInfo.NotificationStatisticType } }; TypeInfo.NotificationStatisticsQuery.fields = { conditions: { isArray: true, typeInfo: TypeInfo.NotificationStatisticsQueryConditions } }; TypeInfo.NotificationStatisticsQueryConditions.fields = { endDate: { isDate: true, }, startDate: { isDate: true, }, type: { enumType: TypeInfo.NotificationStatisticType } }; TypeInfo.NotificationSubscriber.fields = { deliveryPreference: { enumType: TypeInfo.NotificationSubscriberDeliveryPreference }, flags: { enumType: TypeInfo.SubscriberFlags } }; TypeInfo.NotificationSubscriberUpdateParameters.fields = { deliveryPreference: { enumType: TypeInfo.NotificationSubscriberDeliveryPreference } }; TypeInfo.NotificationSubscription.fields = { diagnostics: { typeInfo: TypeInfo.SubscriptionDiagnostics }, flags: { enumType: TypeInfo.SubscriptionFlags }, modifiedDate: { isDate: true, }, permissions: { enumType: TypeInfo.SubscriptionPermissions }, status: { enumType: TypeInfo.SubscriptionStatus } }; TypeInfo.NotificationSubscriptionTemplate.fields = { notificationEventInformation: { typeInfo: TypeInfo.NotificationEventType }, type: { enumType: TypeInfo.SubscriptionTemplateType } }; TypeInfo.NotificationSubscriptionUpdateParameters.fields = { status: { enumType: TypeInfo.SubscriptionStatus } }; TypeInfo.SubscriptionDiagnostics.fields = { deliveryResults: { typeInfo: TypeInfo.SubscriptionTracing }, deliveryTracing: { typeInfo: TypeInfo.SubscriptionTracing }, evaluationTracing: { typeInfo: TypeInfo.SubscriptionTracing } }; TypeInfo.SubscriptionEvaluationRequest.fields = { minEventsCreatedDate: { isDate: true, } }; TypeInfo.SubscriptionEvaluationResult.fields = { evaluationJobStatus: { enumType: TypeInfo.EvaluationOperationStatus } }; TypeInfo.SubscriptionQuery.fields = { conditions: { isArray: true, typeInfo: TypeInfo.SubscriptionQueryCondition }, queryFlags: { enumType: TypeInfo.SubscriptionQueryFlags } }; TypeInfo.SubscriptionQueryCondition.fields = { flags: { enumType: TypeInfo.SubscriptionFlags } }; TypeInfo.SubscriptionTraceDiagnosticLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.SubscriptionTraceEventProcessingLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.SubscriptionTraceNotificationDeliveryLog.fields = { endTime: { isDate: true, }, startTime: { isDate: true, } }; TypeInfo.SubscriptionTracing.fields = { endDate: { isDate: true, }, startDate: { isDate: true, } };
the_stack
class DisplayTemplateTokenSyntax { public static get TokenLogicCodeBegin(): string { return "<!--#_"; } public static get TokenLogicCodeEnd(): string { return "_#-->"; } public static get TokenRenderExpressionBegin(): string { return "_#="; } public static get TokenRenderExpressionEnd(): string { return "=#_"; } } enum TransformState { HtmlBlock, LogicBlock, RenderExpression, } enum TransformIndexType { NoTokenFound, ContentStart, ContentEnd, CodeBeginToken, CodeEndToken, RenderBeginToken, RenderEndToken, } class DisplayTemplateTransformer { private CurrentLine: string; private Indexes: { [key: number]: number }; private CurrentState: TransformState; private PreviousState: TransformState; private NextTokenType: TransformIndexType; private StartHtmlPos: number; private HtmlToTransform: string; private PositionMap: { js: number, html: number }[]; private UniqueId: string; private TemplateData: any; private TemplateName: string; private ScriptBlockContent: string; private ScriptBlockPosInHtml: number; private ScriptBlockPosInJs: number; private static tokenIndices: TransformIndexType[] = [ TransformIndexType.CodeBeginToken, TransformIndexType.CodeEndToken, TransformIndexType.RenderBeginToken, TransformIndexType.RenderEndToken ]; constructor(html: string, uniqueId: string, templateData: any) { var match = html.match(/<div[^>]*>/); var divtag_endpos = 0; this.TemplateName = uniqueId; if (match != null) { divtag_endpos = match.index + match[0].length; match = match[0].match(/id\s*=\s*["'](\w+)/); if (match != null) this.TemplateName = match[1]; } this.PositionMap = []; this.StartHtmlPos = divtag_endpos; match = html.match(/<script[^>]*>/); var scripttag_endpos = 0; var scripttag_contentslength = 0; if (match != null) { scripttag_endpos = match.index + match[0].length; scripttag_contentslength = html.indexOf("</script>", scripttag_endpos) - scripttag_endpos; } this.ScriptBlockPosInHtml = scripttag_endpos; this.CurrentState = this.PreviousState = TransformState.HtmlBlock; this.UniqueId = uniqueId; this.TemplateData = templateData; if (divtag_endpos) { this.HtmlToTransform = html.substr(divtag_endpos); this.ScriptBlockContent = scripttag_endpos == 0 ? "" : html.substr(scripttag_endpos, scripttag_contentslength); } else { this.HtmlToTransform = ""; this.ScriptBlockContent = html; } } public Transform(): string { var jsContent = ""; jsContent += "window.DisplayTemplate_" + this.UniqueId + " = function(ctx) {\n"; jsContent += " var ms_outHtml=[];\n"; jsContent += " var cachePreviousTemplateData = ctx['DisplayTemplateData'];\n"; jsContent += " ctx['DisplayTemplateData'] = new Object();\n"; jsContent += " DisplayTemplate_" + this.UniqueId + ".DisplayTemplateData = ctx['DisplayTemplateData'];\n"; jsContent += " ctx['DisplayTemplateData']['TemplateUrl']='" + this.TemplateData.TemplateUrl + "';\n"; jsContent += " ctx['DisplayTemplateData']['TemplateType']='" + this.TemplateData.TemplateType + "';\n"; jsContent += " ctx['DisplayTemplateData']['TargetControlType']=" + JSON.stringify(this.TemplateData.TargetControlType) + ";\n"; jsContent += " this.DisplayTemplateData = ctx['DisplayTemplateData'];\n"; jsContent += "\n"; if (this.TemplateData.TemplateType == "Filter") { jsContent += " ctx['DisplayTemplateData']['CompatibleSearchDataTypes']=" + JSON.stringify(this.TemplateData.CompatibleSearchDataTypes) + ";\n"; jsContent += " ctx['DisplayTemplateData']['CompatibleManagedProperties']=" + JSON.stringify(this.TemplateData.CompatibleManagedProperties) + ";\n"; } if (this.TemplateData.TemplateType == "Item") { jsContent += " ctx['DisplayTemplateData']['ManagedPropertyMapping']=" + JSON.stringify(this.TemplateData.ManagedPropertyMapping) + ";\n"; jsContent += " var cachePreviousItemValuesFunction = ctx['ItemValues'];\n"; jsContent += " ctx['ItemValues'] = function(slotOrPropName) {\n"; jsContent += " return Srch.ValueInfo.getCachedCtxItemValue(ctx, slotOrPropName)\n"; jsContent += " };\n" } // --- jsContent += "\n"; jsContent += " ms_outHtml.push(''"; var currentPos = this.StartHtmlPos; this.PositionMap.push({ js: jsContent.length, html: currentPos }); var htmlLines = this.HtmlToTransform.split('\n'); var divs = 0; while (htmlLines.length > 0) { this.CurrentLine = htmlLines.shift(); this.ResetIndexes(); var length = -1; do { this.ProcessLineSegment(); var segmentContent = this.CurrentLine.substr(this.Indexes[TransformIndexType.ContentStart], this.Indexes[TransformIndexType.ContentEnd] - this.Indexes[TransformIndexType.ContentStart]); if (this.CurrentState == TransformState.HtmlBlock) { var nextDivPos = -1; while ((nextDivPos = segmentContent.indexOf("<div", nextDivPos+1)) > -1) divs++; nextDivPos = -1; while ((nextDivPos = segmentContent.indexOf("</div", nextDivPos+1)) > -1) divs--; if (divs < 0) { htmlLines = []; break; } } if (this.CurrentState == TransformState.LogicBlock && this.PreviousState == TransformState.HtmlBlock) jsContent += ");"; else if (this.CurrentState == TransformState.HtmlBlock && this.PreviousState == TransformState.LogicBlock) jsContent += " ms_outHtml.push("; else if (this.CurrentState != TransformState.LogicBlock) jsContent += ","; this.PositionMap.push({ js: jsContent.length, html: currentPos + this.Indexes[TransformIndexType.ContentStart] }); switch (this.CurrentState) { case TransformState.HtmlBlock: jsContent += "'" + this.EscapeHtmlSegment(segmentContent) + "'"; break; case TransformState.LogicBlock: jsContent += segmentContent; break; case TransformState.RenderExpression: var str = segmentContent.replace("<![CDATA[", '').replace("]]>", ''); if (length != -1 && this.CurrentLine.substr(0, length).trim().match(/=\"$/)) str = str.replace("&quot;", "\""); jsContent += str; break; } this.Indexes[TransformIndexType.ContentStart] = this.Indexes[TransformIndexType.ContentEnd]; this.PreviousState = this.CurrentState; if (this.Indexes[TransformIndexType.ContentEnd] <= length) throw "ParseProgressException"; else length = this.Indexes[TransformIndexType.ContentEnd]; this.PositionMap.push({ js: jsContent.length, html: currentPos + length }); } while (this.Indexes[TransformIndexType.ContentEnd] < this.CurrentLine.length); jsContent += "\n"; currentPos += this.CurrentLine.length + 1; } jsContent += ");\n"; if (this.TemplateData.TemplateType == "Item") jsContent += " ctx['ItemValues'] = cachePreviousItemValuesFunction;\n"; jsContent += " ctx['DisplayTemplateData'] = cachePreviousTemplateData;\n"; jsContent += " return ms_outHtml.join('');\n"; jsContent += "};\n"; jsContent += ` function RegisterTemplate_${this.UniqueId}() { if ("undefined" != typeof (Srch) && "undefined" != typeof (Srch.U) && typeof(Srch.U.registerRenderTemplateByName) == "function") { Srch.U.registerRenderTemplateByName("${this.TemplateName}", DisplayTemplate_${this.UniqueId}); Srch.U.registerRenderTemplateByName("${this.TemplateData.TemplateUrl}", DisplayTemplate_${this.UniqueId}); }`; this.ScriptBlockPosInJs = jsContent.length; jsContent += this.ScriptBlockContent; jsContent += `} RegisterTemplate_${this.UniqueId}();`; this.PositionMap.push({ js: jsContent.length, html: currentPos }); return jsContent; } public GetPositionInHtml(posInJs: number): number { if (this.PositionMap.length == 0) return posInJs; if (this.ScriptBlockContent.length > 0 && this.ScriptBlockPosInJs <= posInJs && posInJs < this.ScriptBlockPosInJs + this.ScriptBlockContent.length) return this.ScriptBlockPosInHtml + posInJs - this.ScriptBlockPosInJs; for(var i=0;i<this.PositionMap.length-1;i++) { if (this.PositionMap[i].js <= posInJs && posInJs < this.PositionMap[i+1].js) { return this.PositionMap[i].html + posInJs - this.PositionMap[i].js; } } return -1; } public GetPositionInJs(posInHtml: number): number { if (this.PositionMap.length == 0) return posInHtml; if (this.ScriptBlockContent.length > 0 && this.ScriptBlockPosInHtml <= posInHtml && posInHtml < this.ScriptBlockPosInHtml + this.ScriptBlockContent.length) return this.ScriptBlockPosInJs + posInHtml - this.ScriptBlockPosInHtml; for(var i=0;i<this.PositionMap.length-1;i++) { if (this.PositionMap[i].html <= posInHtml && posInHtml < this.PositionMap[i+1].html) { return this.PositionMap[i].js + posInHtml - this.PositionMap[i].html; } } return -1; } private ProcessLineSegment() { this.FindLineTokenIndices(); this.FindSegmentTypeAndContent(); } private FindSegmentTypeAndContent() { var flag = false; switch (this.CurrentState) { case TransformState.HtmlBlock: if (this.Indexes[TransformIndexType.CodeBeginToken] == this.Indexes[TransformIndexType.ContentStart]) { flag = true; this.PreviousState = this.CurrentState; this.CurrentState = TransformState.LogicBlock; this.Indexes[TransformIndexType.ContentStart] = this.Indexes[TransformIndexType.ContentStart] + DisplayTemplateTokenSyntax.TokenLogicCodeBegin.length; } else if (this.Indexes[TransformIndexType.RenderBeginToken] == this.Indexes[TransformIndexType.ContentStart]) { flag = true; this.PreviousState = this.CurrentState; this.CurrentState = TransformState.RenderExpression; this.Indexes[TransformIndexType.ContentStart] = this.Indexes[TransformIndexType.ContentStart] + DisplayTemplateTokenSyntax.TokenRenderExpressionBegin.length; } break; case TransformState.LogicBlock: if (this.Indexes[TransformIndexType.CodeEndToken] == this.Indexes[TransformIndexType.ContentStart]) { flag = true; this.PreviousState = this.CurrentState; this.CurrentState = TransformState.HtmlBlock; this.Indexes[TransformIndexType.ContentStart] = this.Indexes[TransformIndexType.ContentStart] + DisplayTemplateTokenSyntax.TokenLogicCodeEnd.length; } break; case TransformState.RenderExpression: if (this.Indexes[TransformIndexType.RenderEndToken] == this.Indexes[TransformIndexType.ContentStart]) { flag = true; this.PreviousState = this.CurrentState; this.CurrentState = TransformState.HtmlBlock; this.Indexes[TransformIndexType.ContentStart] = this.Indexes[TransformIndexType.ContentStart] + DisplayTemplateTokenSyntax.TokenRenderExpressionEnd.length; } break; } if (flag) { //console.log("FindSegmentTypeAndContent: State changed as a shortcut to "+this.CurrentState+" with segment content now starting at " + this.Indexes[TransformIndexType.ContentStart]); this.FindLineTokenIndices(); } this.FindNextTokenTypeAndContentEnd(); } private FindLineTokenIndices() { this.Indexes[TransformIndexType.CodeBeginToken] = this.CurrentLine.indexOf(DisplayTemplateTokenSyntax.TokenLogicCodeBegin, this.Indexes[TransformIndexType.ContentStart]); this.Indexes[TransformIndexType.CodeEndToken] = this.CurrentLine.indexOf(DisplayTemplateTokenSyntax.TokenLogicCodeEnd, this.Indexes[TransformIndexType.ContentStart]); this.Indexes[TransformIndexType.RenderBeginToken] = this.CurrentLine.indexOf(DisplayTemplateTokenSyntax.TokenRenderExpressionBegin, this.Indexes[TransformIndexType.ContentStart]); this.Indexes[TransformIndexType.RenderEndToken] = this.CurrentLine.indexOf(DisplayTemplateTokenSyntax.TokenRenderExpressionEnd, this.Indexes[TransformIndexType.ContentStart]); } private FindNextTokenTypeAndContentEnd() { var transformIndexType = TransformIndexType.NoTokenFound; var dictionary = {}; for (let index of DisplayTemplateTransformer.tokenIndices) { if (!(this.Indexes[index] in dictionary)) dictionary[this.Indexes[index]] = index; } var sortedSet = Object.keys(dictionary).map(k => +k).sort((a,b) => a - b); if (sortedSet.length > 1) { let index = +sortedSet.filter(n => n > -1)[0]; transformIndexType = dictionary[index]; this.Indexes[TransformIndexType.ContentEnd] = index; } else this.Indexes[TransformIndexType.ContentEnd] = this.CurrentLine.length; this.NextTokenType = transformIndexType; } private EscapeHtmlSegment(s: string) { return s.replace(/\\/g, '\\\\').replace(/'/g, '\\\''); } private ResetIndexes() { this.Indexes = {}; for (let index of Object.keys(TransformIndexType).map(v => parseInt(v, 10)).filter(v => !isNaN(v))) this.Indexes[index] = index != TransformIndexType.ContentStart ? -1 : 0; } }
the_stack
import { DatabaseService, Repositories } from "@arkecosystem/core-database"; import { Container, Contracts, Enums, Providers, Types, Utils } from "@arkecosystem/core-kernel"; import { DatabaseInteraction } from "@arkecosystem/core-state"; import { Blocks, Crypto, Interfaces, Managers } from "@arkecosystem/crypto"; import { ProcessBlocksJob } from "./process-blocks-job"; import { StateMachine } from "./state-machine"; import { blockchainMachine } from "./state-machine/machine"; // todo: reduce the overall complexity of this class and remove all helpers and getters that just serve as proxies @Container.injectable() export class Blockchain implements Contracts.Blockchain.Blockchain { @Container.inject(Container.Identifiers.Application) public readonly app!: Contracts.Kernel.Application; @Container.inject(Container.Identifiers.PluginConfiguration) @Container.tagged("plugin", "@arkecosystem/core-blockchain") private readonly configuration!: Providers.PluginConfiguration; @Container.inject(Container.Identifiers.StateStore) private readonly stateStore!: Contracts.State.StateStore; @Container.inject(Container.Identifiers.DatabaseInteraction) private readonly databaseInteraction!: DatabaseInteraction; @Container.inject(Container.Identifiers.DatabaseService) private readonly database!: DatabaseService; @Container.inject(Container.Identifiers.DatabaseBlockRepository) private readonly blockRepository!: Repositories.BlockRepository; @Container.inject(Container.Identifiers.TransactionPoolService) private readonly transactionPool!: Contracts.TransactionPool.Service; @Container.inject(Container.Identifiers.StateMachine) private readonly stateMachine!: StateMachine; @Container.inject(Container.Identifiers.PeerNetworkMonitor) private readonly networkMonitor!: Contracts.P2P.NetworkMonitor; @Container.inject(Container.Identifiers.PeerRepository) private readonly peerRepository!: Contracts.P2P.PeerRepository; @Container.inject(Container.Identifiers.EventDispatcherService) private readonly events!: Contracts.Kernel.EventDispatcher; @Container.inject(Container.Identifiers.LogService) private readonly logger!: Contracts.Kernel.Logger; private queue!: Contracts.Kernel.Queue; private stopped!: boolean; private booted: boolean = false; private missedBlocks: number = 0; private lastCheckNetworkHealthTs: number = 0; @Container.postConstruct() public async initialize(): Promise<void> { this.stopped = false; // flag to force a network start this.stateStore.setNetworkStart(this.configuration.getOptional("options.networkStart", false)); if (this.stateStore.getNetworkStart()) { this.logger.warning( "ARK Core is launched in Genesis Start mode. This is usually for starting the first node on the blockchain. Unless you know what you are doing, this is likely wrong.", ); } this.queue = await this.app.get<Types.QueueFactory>(Container.Identifiers.QueueFactory)(); this.queue.on("drain", () => { this.dispatch("PROCESSFINISHED"); }); this.queue.on("jobError", (job, error) => { const blocks = (job as ProcessBlocksJob).getBlocks(); this.logger.error( `Failed to process ${Utils.pluralize( "block", blocks.length, true, )} from height ${blocks[0].height.toLocaleString()} in queue.`, ); }); } /** * Determine if the blockchain is stopped. */ public isStopped(): boolean { return this.stopped; } public isBooted(): boolean { return this.booted; } public getQueue(): Contracts.Kernel.Queue { return this.queue; } /** * Dispatch an event to transition the state machine. * @param {String} event * @return {void} */ public dispatch(event: string): void { return this.stateMachine.transition(event); } /** * Start the blockchain and wait for it to be ready. * @return {void} */ public async boot(skipStartedCheck = false): Promise<boolean> { this.logger.info("Starting Blockchain Manager"); this.stateStore.reset(blockchainMachine); this.dispatch("START"); if (skipStartedCheck || process.env.CORE_SKIP_BLOCKCHAIN_STARTED_CHECK) { return true; } while (!this.stateStore.isStarted() && !this.stopped) { await Utils.sleep(1000); } await this.networkMonitor.cleansePeers({ forcePing: true, peerCount: 10, }); this.events.listen(Enums.ForgerEvent.Missing, { handle: this.checkMissingBlocks }); this.events.listen(Enums.RoundEvent.Applied, { handle: this.resetMissedBlocks }); this.booted = true; return true; } public async dispose(): Promise<void> { if (!this.stopped) { this.logger.info("Stopping Blockchain Manager"); this.stopped = true; this.stateStore.clearWakeUpTimeout(); this.dispatch("STOP"); await this.queue.stop(); } } /** * Set wakeup timeout to check the network for new blocks. */ public setWakeUp(): void { this.stateStore.setWakeUpTimeout(() => { this.dispatch("WAKEUP"); }, 60000); } /** * Reset the wakeup timeout. */ public resetWakeUp(): void { this.stateStore.clearWakeUpTimeout(); this.setWakeUp(); } /** * Clear and stop the queue. * @return {void} */ public clearAndStopQueue(): void { this.stateStore.setLastDownloadedBlock(this.getLastBlock().data); this.queue.pause(); this.clearQueue(); } /** * Clear the queue. * @return {void} */ public clearQueue(): void { this.queue.clear(); } /** * Push a block to the process queue. */ public async handleIncomingBlock(block: Interfaces.IBlockData, fromForger = false): Promise<void> { const blockTimeLookup = await Utils.forgingInfoCalculator.getBlockTimeLookup(this.app, block.height); const currentSlot: number = Crypto.Slots.getSlotNumber(blockTimeLookup); const receivedSlot: number = Crypto.Slots.getSlotNumber(blockTimeLookup, block.timestamp); if (fromForger) { const minimumMs: number = 2000; const timeLeftInMs: number = Crypto.Slots.getTimeInMsUntilNextSlot(blockTimeLookup); if (currentSlot !== receivedSlot || timeLeftInMs < minimumMs) { this.logger.info(`Discarded block ${block.height.toLocaleString()} because it was received too late.`); return; } } if (receivedSlot > currentSlot) { this.logger.info(`Discarded block ${block.height.toLocaleString()} because it takes a future slot.`); return; } this.pushPingBlock(block, fromForger); if (this.stateStore.isStarted()) { this.dispatch("NEWBLOCK"); this.enqueueBlocks([block]); this.events.dispatch(Enums.BlockEvent.Received, block); } else { this.logger.info(`Block disregarded because blockchain is not ready`); this.events.dispatch(Enums.BlockEvent.Disregarded, block); } } /** * Enqueue blocks in process queue and set last downloaded block to last item in list. */ public enqueueBlocks(blocks: Interfaces.IBlockData[]): void { if (blocks.length === 0) { return; } const __createQueueJob = (blocks: Interfaces.IBlockData[]) => { const processBlocksJob = this.app.resolve<ProcessBlocksJob>(ProcessBlocksJob); processBlocksJob.setBlocks(blocks); this.queue.push(processBlocksJob); this.queue.resume(); }; const lastDownloadedHeight: number = this.getLastDownloadedBlock().height; const milestoneHeights: number[] = Managers.configManager .getMilestones() .map((milestone) => milestone.height) .sort((a, b) => a - b) .filter((height) => height >= lastDownloadedHeight); // divide blocks received into chunks depending on number of transactions // this is to avoid blocking the application when processing "heavy" blocks let currentBlocksChunk: any[] = []; let currentTransactionsCount = 0; for (const block of blocks) { Utils.assert.defined<Interfaces.IBlockData>(block); currentBlocksChunk.push(block); currentTransactionsCount += block.numberOfTransactions; const nextMilestone = milestoneHeights[0] && milestoneHeights[0] === block.height; if ( currentTransactionsCount >= 150 || currentBlocksChunk.length >= Math.min(this.stateStore.getMaxLastBlocks(), 100) || nextMilestone ) { __createQueueJob(currentBlocksChunk); currentBlocksChunk = []; currentTransactionsCount = 0; if (nextMilestone) { milestoneHeights.shift(); } } } __createQueueJob(currentBlocksChunk); } /** * Remove N number of blocks. * @param {Number} nblocks * @return {void} */ public async removeBlocks(nblocks: number): Promise<void> { try { this.clearAndStopQueue(); const lastBlock: Interfaces.IBlock = this.stateStore.getLastBlock(); // If the current chain height is H and we will be removing blocks [N, H], // then blocksToRemove[] will contain blocks [N - 1, H - 1]. const blocksToRemove: Interfaces.IBlockData[] = await this.database.getBlocks( lastBlock.data.height - nblocks, lastBlock.data.height, ); const removedBlocks: Interfaces.IBlockData[] = []; const removedTransactions: Interfaces.ITransaction[] = []; const revertLastBlock = async () => { const lastBlock: Interfaces.IBlock = this.stateStore.getLastBlock(); await this.databaseInteraction.revertBlock(lastBlock); removedBlocks.push(lastBlock.data); removedTransactions.push(...[...lastBlock.transactions].reverse()); blocksToRemove.pop(); let newLastBlock: Interfaces.IBlock; if (blocksToRemove[blocksToRemove.length - 1].height === 1) { newLastBlock = this.stateStore.getGenesisBlock(); } else { const tempNewLastBlockData: Interfaces.IBlockData = blocksToRemove[blocksToRemove.length - 1]; Utils.assert.defined<Interfaces.IBlockData>(tempNewLastBlockData); const tempNewLastBlock: Interfaces.IBlock | undefined = Blocks.BlockFactory.fromData( tempNewLastBlockData, { deserializeTransactionsUnchecked: true, }, ); Utils.assert.defined<Interfaces.IBlockData>(tempNewLastBlock); newLastBlock = tempNewLastBlock; } this.stateStore.setLastBlock(newLastBlock); this.stateStore.setLastDownloadedBlock(newLastBlock.data); }; const __removeBlocks = async (numberOfBlocks) => { if (numberOfBlocks < 1) { return; } const lastBlock: Interfaces.IBlock = this.stateStore.getLastBlock(); this.logger.info(`Undoing block ${lastBlock.data.height.toLocaleString()}`); await revertLastBlock(); await __removeBlocks(numberOfBlocks - 1); }; if (nblocks >= lastBlock.data.height) { nblocks = lastBlock.data.height - 1; } const resetHeight: number = lastBlock.data.height - nblocks; this.logger.info( `Removing ${Utils.pluralize("block", nblocks, true)}. Reset to height ${resetHeight.toLocaleString()}`, ); this.stateStore.setLastDownloadedBlock(lastBlock.data); await __removeBlocks(nblocks); await this.blockRepository.deleteBlocks(removedBlocks.reverse()); this.stateStore.setLastStoredBlockHeight(lastBlock.data.height - nblocks); await this.transactionPool.readdTransactions(removedTransactions.reverse()); // Validate last block const lastStoredBlock = await this.database.getLastBlock(); if (lastStoredBlock.data.id !== this.stateStore.getLastBlock().data.id) { throw new Error( `Last stored block (${lastStoredBlock.data.id}) is not the same as last block from state store (${ this.stateStore.getLastBlock().data.id })`, ); } } catch (err) { this.logger.error(err.stack); this.logger.warning("Shutting down app, because state might be corrupted"); process.exit(1); } } /** * Remove the top blocks from database. * NOTE: Only used when trying to restore database integrity. * @param {Number} count * @return {void} */ public async removeTopBlocks(count: number): Promise<void> { this.logger.info(`Removing top ${Utils.pluralize("block", count, true)}`); await this.blockRepository.deleteTopBlocks(count); } /** * Reset the last downloaded block to last chained block. */ public resetLastDownloadedBlock(): void { this.stateStore.setLastDownloadedBlock(this.getLastBlock().data); } /** * Called by forger to wake up and sync with the network. * It clears the wakeUpTimeout if set. */ public forceWakeup(): void { this.stateStore.clearWakeUpTimeout(); this.dispatch("WAKEUP"); } /** * Fork the chain at the given block. */ public forkBlock(block: Interfaces.IBlock, numberOfBlockToRollback?: number): void { this.stateStore.setForkedBlock(block); this.clearAndStopQueue(); /* istanbul ignore else */ if (numberOfBlockToRollback) { this.stateStore.setNumberOfBlocksToRollback(numberOfBlockToRollback); } this.dispatch("FORK"); } /** * Determine if the blockchain is synced. */ public isSynced(block?: Interfaces.IBlockData): boolean { if (!this.peerRepository.hasPeers()) { return true; } block = block || this.getLastBlock().data; return ( Crypto.Slots.getTime() - block.timestamp < 3 * Managers.configManager.getMilestone(block.height).blocktime ); } /** * Get the last block of the blockchain. */ public getLastBlock(): Interfaces.IBlock { return this.stateStore.getLastBlock(); } /** * Get the last height of the blockchain. */ public getLastHeight(): number { return this.getLastBlock().data.height; } /** * Get the last downloaded block of the blockchain. */ public getLastDownloadedBlock(): Interfaces.IBlockData { return this.stateStore.getLastDownloadedBlock() || this.getLastBlock().data; } /** * Get the block ping. */ public getBlockPing(): Contracts.State.BlockPing | undefined { return this.stateStore.getBlockPing(); } /** * Ping a block. */ public pingBlock(incomingBlock: Interfaces.IBlockData): boolean { return this.stateStore.pingBlock(incomingBlock); } /** * Push ping block. */ public pushPingBlock(block: Interfaces.IBlockData, fromForger = false): void { this.stateStore.pushPingBlock(block, fromForger); } /** * Check if the blockchain should roll back due to missing blocks. */ public async checkMissingBlocks(): Promise<void> { this.missedBlocks++; if ( this.missedBlocks >= Managers.configManager.getMilestone().activeDelegates / 3 - 1 && Math.random() <= 0.8 ) { this.resetMissedBlocks(); // do not check network health here more than every 10 minutes const nowTs = Date.now(); if (nowTs - this.lastCheckNetworkHealthTs < 10 * 60 * 1000) { return; } this.lastCheckNetworkHealthTs = nowTs; const networkStatus = await this.networkMonitor.checkNetworkHealth(); if (networkStatus.forked) { this.stateStore.setNumberOfBlocksToRollback(networkStatus.blocksToRollback || 0); this.dispatch("FORK"); } } } private resetMissedBlocks(): void { this.missedBlocks = 0; } }
the_stack
import { produce, enablePatches, produceWithPatches, Patch, applyPatches, current, isDraft, } from 'immer' enablePatches() export declare type StateObject = Record<string | number | symbol, any> export declare type StateSelector<T extends StateObject, U> = (state: T) => U const syncedStates = new Map<string, State<any>>() class Stack<T> { private items: Array<T> = [] push(t: T) { this.items.push(t) } pop(): T | undefined { return this.items.pop() } peek(): T { return this.items[this.items.length - 1] } } interface Change { apply: Patch[] revert: Patch[] } interface History { changelist: Array<Change> position: number } function createHistory(): History { return { changelist: [], position: 0, } } function pushHistory(history: History, change: Change): History { return produce(history, history => { if (change.apply.length === 0) { history.changelist.splice(history.position, 0, change) history.position++ } else { history.changelist = history.changelist.splice(0, history.position) history.changelist.push(change) history.position++ } }) } function undoHistory( history: History, apply: (changes: Patch[]) => void, ): History { return produce(history, history => { if (history.position === 0) { return } const change = history.changelist[history.position - 1] apply(change.revert) history.position-- }) } function redoHistory( history: History, apply: (changes: Patch[]) => void, ): History { return produce(history, history => { if (history.position === history.changelist.length) { return } const change = history.changelist[history.position] apply(change.apply) history.position++ }) } function compressHistory(prev: History, curr: History): History { let start = 0 for (let i = 0; i < curr.position; i++) { start = i if (prev.changelist[i] !== curr.changelist[i]) { break } } // prev is not a prefix of curr (curr has gone backwards in history) // we are unable to compress the history in this case if (start < prev.position) { return curr } const change = curr.changelist.slice(start, curr.position).reduce( (acc, curr) => ({ apply: [...acc.apply, ...curr.apply], revert: [...curr.revert, ...acc.revert], }), { apply: [], revert: [] }, ) return { changelist: [...curr.changelist.slice(0, start), change], position: start + 1, } } function difference<T>(a: T, b: T): Patch[] { const [, patches] = produceWithPatches(a, a => Object.assign(a, b)) return patches } export class State<T> { readonly syncKey?: string private _initial: T private _value: T private _history: History private _subscriptions = new Set<(v: T) => void>() private _transactions = new Stack<{ value: T; history: History }>() constructor(initial: T, syncKey?: string) { this._initial = produce(initial, () => {}) this._value = this._initial this.syncKey = syncKey this._history = createHistory() if (syncKey) { syncedStates.set(syncKey, this) } } resetForTesting() { if (this._transactions.peek()) { throw new Error('Cannot reset during a transaction') } this._value = this._initial this.clearHistory() } get(): T get<R>(selector: StateSelector<T, R>): R get<R = T>(selector?: StateSelector<T, R>): R { if (selector) { return selector(this._value) } else { return this._value as any } } set<R>(producer: (t: T) => R): R set(update: Partial<T>): void set<R>(producer: ((t: T) => R) | Partial<T>) { let updater: (t: T) => R | undefined if (typeof producer === 'function') { updater = producer } else { updater = (t: T) => { Object.assign(t, producer) return undefined } } let returnValue: R | undefined const [value, patches, reversePatches] = produceWithPatches<T, T>( this._value, (t: T) => { const v = updater(t) returnValue = isDraft(v) ? current(v) : v }, ) this._value = value this._history = pushHistory(this._history, { apply: patches, revert: reversePatches, }) if (!this._transactions.peek()) { this.syncPatches(patches) this.notifyChanges() } return returnValue } setNoHistory(producer: (t: T) => void) { this._value = produce(this._value, producer) if (!this._transactions.peek()) { this.notifyChanges() } } // This internal function will only do a single undo, even if that undo results // in no changes. _undoSingle(): Patch[] | null { let changes: Patch[] | null = null this._history = undoHistory(this._history, patches => { changes = current(patches) this._value = applyPatches(this._value, patches) if (!this._transactions.peek() && patches.length > 0) { this.syncPatches(current(patches)) this.notifyChanges() } }) return changes } // This internal function will only do a single redo, even if that redo results // in no changes. _redoSingle(): Patch[] | null { let changes: Patch[] | null = null this._history = redoHistory(this._history, patches => { changes = current(patches) this._value = applyPatches(this._value, patches) if (!this._transactions.peek() && patches.length > 0) { this.syncPatches(current(patches)) this.notifyChanges() } }) return changes } undo() { while (true) { const result = this._undoSingle() if (result === null || result.length > 0) { break } } } redo() { while (true) { const result = this._redoSingle() if (result === null || result.length > 0) { break } } } _beginTransaction() { this._transactions.push({ value: this._value, history: this._history }) } _abortTransaction() { const transaction = this._transactions.pop() if (!transaction) { throw new Error('No transaction in progress') } this._value = transaction.value this._history = transaction.history } _commitTransaction() { const transaction = this._transactions.pop() if (!transaction) { throw new Error('No transaction in progress') } this._history = compressHistory(transaction.history, this._history) if (!this._transactions.peek()) { const patches = difference(transaction.value, this._value) if (patches.length > 0) { this.syncPatches(patches) this.notifyChanges() } } } transaction(perform: () => void) { this._beginTransaction() try { perform() this._commitTransaction() } catch (e) { this._abortTransaction() throw e } } subscribe(subscriber: (v: T) => void) { this._subscriptions.add(subscriber) return () => { this._subscriptions.delete(subscriber) } } clearHistory() { this._history = createHistory() } _applyPatchesWithHistory(patches: Patch[], reversePatches: Patch[]) { this._value = applyPatches(this._value, patches) this._history = pushHistory(this._history, { apply: patches, revert: reversePatches, }) if (!this._transactions.peek()) { this.syncPatches(patches) this.notifyChanges() } } _applyPatches(patches: Patch[]) { this._value = applyPatches(this._value, patches) if (!this._transactions.peek()) { this.notifyChanges() } } _setState(s: T) { this._value = produce(s, () => {}) this.clearHistory() if (!this._transactions.peek()) { this.notifyChanges() } } private notifyChanges() { if (this._transactions.peek()) { throw new Error('Cannot notify changes during a transaction') } this._subscriptions.forEach(s => s(this.get())) } private syncPatches(patches: Patch[]) { if (this._transactions.peek()) { throw new Error('Cannot sync patches during a transaction') } if (broadcastPatches && this.syncKey) { broadcastPatches(this.syncKey, patches) } } } export class DerivedState<T, U> { readonly _selector: StateSelector<T, U> readonly _state: AnyState<T> constructor(state: AnyState<T>, selector: StateSelector<T, U>) { this._selector = selector this._state = state } resetForTesting() { this._state.resetForTesting() } get(): U get<R>(selector: StateSelector<U, R>): R get<R = U>(selector?: StateSelector<U, R>): R { const value = this._selector(this._state.get()) if (selector) { return selector(value) } else { return value as any } } subscribe(subscriber: (v: U) => void): () => void { return this._state.subscribe((v: T) => { subscriber(this._selector(v)) }) } undo() { this._state.undo() } redo() { this._state.redo() } transaction(perform: () => void) { this._state.transaction(perform) } clearHistory() { this._state.clearHistory() } } type PatchApplicator = (key: string, patches: Patch[]) => void export type SyncAdapter = ( applyPatches: (key: string, t: Patch[]) => void, setState: (key: string, t: unknown) => void, syncedStates: Map<string, State<unknown>>, ) => PatchApplicator let broadcastPatches: PatchApplicator | undefined export function setSyncAdapter(adapter: SyncAdapter | null) { broadcastPatches = adapter?.( (key: string, patches: Patch[]) => { syncedStates.get(key)?._applyPatches(patches) }, (key: string, t: unknown) => { syncedStates.get(key)?._setState(t) }, syncedStates, ) } export class CombinedState<T extends StateObject> { readonly _states: { [K in keyof T]: State<T[K]> } readonly _api: { getState: () => T } constructor(states: { [K in keyof T]: State<T[K]> }) { this._states = states this._api = { getState: () => { return this.get() }, } } resetForTesting() { Object.values(this._states).forEach(s => s.resetForTesting()) } get(): T get<R>(selector: StateSelector<T, R>): R get<R = T>(selector?: StateSelector<T, R>): R { const value = Object.entries(this._states).reduce( (acc, [key, store]) => { acc[key as any] = store.get() return acc }, {} as T, ) const sel = selector ?? identity return sel(value as any) } set<R>(producer: (t: T) => R): R set(update: Partial<T>): void set<R>(producer: ((t: T) => R) | Partial<T>) { let updater: (t: T) => R | undefined if (producer instanceof Function) { updater = producer } else { updater = (t: T) => { for (const key in producer) { t[key as any] = producer[key] } return undefined } } let returnValue: R | undefined const state = this.get() const [, patches, reversePatches] = produceWithPatches( state, (t: T) => { const v = updater(t) returnValue = isDraft(v) ? current(v) : v }, ) this.transaction(() => { for (const [key, store] of Object.entries(this._states)) { const filter = (patches: Patch[]) => { return patches .filter(patch => patch.path[0] === key) .map(patch => ({ ...patch, path: patch.path.slice(1) })) } store._applyPatchesWithHistory( filter(patches), filter(reversePatches), ) } }) return returnValue } setNoHistory(producer: (t: { [K in keyof T]: T[K] }) => void) { const state = this.get() const [, patches] = produceWithPatches(state, producer) this.transaction(() => { for (const [key, store] of Object.entries(this._states)) { const filter = (patches: Patch[]) => { return patches .filter(patch => patch.path[0] === key) .map(patch => ({ ...patch, path: patch.path.slice(1) })) } store._applyPatches(filter(patches)) } }) } undo() { this.transaction(() => { while (true) { const done = Object.values(this._states) .map(s => s._undoSingle()) .reduce((acc, curr) => { return acc || curr === null || curr.length > 0 }, false) if (done) { break } } }) } redo() { this.transaction(() => { while (true) { const done = Object.values(this._states) .map(s => s._redoSingle()) .reduce((acc, curr) => { return acc || curr === null || curr.length > 0 }, false) if (done) { break } } }) } transaction(perform: () => void) { Object.values(this._states).forEach(s => s._beginTransaction()) try { perform() Object.values(this._states).forEach(s => s._commitTransaction()) } catch (e) { Object.values(this._states).forEach(s => s._abortTransaction()) throw e } } subscribe(subscriber: (v: T) => void) { const unsubs = Object.values(this._states).map(s => { return s.subscribe(() => subscriber(this.get())) }) return () => { unsubs.forEach(s => s()) } } clearHistory() { Object.values(this._states).forEach(s => s.clearHistory()) } } export function identity<T>(t: T) { return t } export type AnyState<T> = State<T> | DerivedState<any, T> | CombinedState<T> export function combinedState<T extends Record<string, unknown>>( states: { [K in keyof T]: State<T[K]> }, ) { return new CombinedState(states) } export function derivedState<T, U>( state: AnyState<T>, selector: StateSelector<T, U>, ): DerivedState<T, U> { return new DerivedState(state, selector) } export function syncedState<T>(syncKey: string, initial: T) { return new State(initial, syncKey) } export function state<T>(initial: T) { return new State(initial) }
the_stack
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, HostBinding, HostListener, Input, NgZone, OnDestroy, OnInit, } from '@angular/core'; import { ArgumentHelper } from '../utils/argument.helper'; /** * Supported button types. */ export type SohoButtonType = 'btn' | 'primary' | 'secondary' | 'tertiary' | 'icon' | 'favorite' | 'modal' | 'modal-primary'; @Component({ selector: 'button[soho-button]', // eslint-disable-line templateUrl: 'soho-button.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class SohoButtonComponent implements AfterViewInit, OnDestroy, OnInit { // ------------------------------------------- // Supported button types. // ------------------------------------------- static BTN: SohoButtonType = 'btn'; static PRIMARY: SohoButtonType = 'primary'; static SECONDARY: SohoButtonType = 'secondary'; static TERTIARY: SohoButtonType = 'tertiary'; static ICON: SohoButtonType = 'icon'; static FAVORITE: SohoButtonType = 'favorite'; static MODAL: SohoButtonType = 'modal'; static MODAL_PRIMARY: SohoButtonType = 'modal-primary'; // ------------------------------------------- // Private Member Data // ------------------------------------------- /** Reference to the jQuery control. */ private jQueryElement?: JQuery; /** Reference to the Soho control api. */ private button?: SohoButtonStatic | null; /** The type of the button. */ private buttonType?: SohoButtonType; private _buttonOptions: SohoButtonOptions = {}; private _isToggle = false; private _isTogglePressed = false; private _isPressed = false; /** * The type of the button, defaulting to 'secondary'. * * Allow override of input, to match component selector. */ // eslint-disable-next-line @angular-eslint/no-input-rename @Input('soho-button') set sohoButton(type: SohoButtonType) { this.buttonType = type ? type : SohoButtonComponent.SECONDARY; } /** * Sets the button options */ @Input() set buttonOptions(buttonOptions: SohoButtonOptions) { ArgumentHelper.checkNotNull('buttonOptions', buttonOptions); this._buttonOptions = buttonOptions; if (this.jQueryElement) { // todo: how to update the button when options change? } } get buttonOptions(): SohoButtonOptions { return this._buttonOptions; } @Input() set toggleOnIcon(toggleOnIcon: string) { this._buttonOptions.toggleOnIcon = toggleOnIcon; if (this.jQueryElement) { // todo: how to update the button when toggleOnIcon changes? } } @Input() set toggleOffIcon(toggleOffIcon: string) { this._buttonOptions.toggleOffIcon = toggleOffIcon; if (this.jQueryElement) { // todo: how to update the button when toggleOffIcon changes? } } @Input() set replaceText(replaceText: boolean) { this._buttonOptions.replaceText = replaceText; if (this.jQueryElement) { ((this.button as any).settings as any).replaceText = replaceText; } } @Input() set hideMenuArrow(value: boolean | undefined) { this._buttonOptions.hideMenuArrow = value; if (this.button) { this.button.settings.hideMenuArrow = value; } } get hideMenuArrow(): boolean | undefined { return this._buttonOptions.hideMenuArrow; } /** * Used to add a bigger hit area (for mobile) */ @Input() set hitbox(value: boolean | undefined) { this._buttonOptions.hitbox = value; if (this.button) { this.button.settings.hitbox = value; } } get hitbox(): boolean | undefined { return this._buttonOptions.hitbox; } /** * Used to set a notification badge on the button */ @Input() set notificationBadge(value: boolean | undefined) { this._buttonOptions.notificationBadge = value; if (this.button) { this.button.settings.notificationBadge = value; } } get notificationBadge(): boolean | undefined { return this._buttonOptions.notificationBadge; } /** * Set the position and color of the notification badge on the button */ @Input() set notificationBadgeOptions(value: SohoNotificationBadgeOptions | undefined) { this._buttonOptions.notificationBadgeOptions = value; if (this.button) { this.button.settings.notificationBadgeOptions = value; } } get notificationBadgeOptions(): SohoNotificationBadgeOptions | undefined { return this._buttonOptions.notificationBadgeOptions; } /** * Used to set an extra class on the soho-icon being used by soho-button. * Useful to set emerald06-color azure10-color to change the icon color. */ @Input() extraIconClass?: string; /** * Whether this button should be a toggle button or not. Alternate toggle on/off icons * can be used through toggleOnIcon/toggleOffIcon inputs. */ @Input() set isToggle(isToggle: boolean) { this._isToggle = isToggle; } get isToggle(): boolean { return this._isToggle; } /** * Whether the toggle button should be in a pressed state or not. */ @Input() set isTogglePressed(isTogglePressed: boolean) { this._isTogglePressed = isTogglePressed; } get isTogglePressed(): boolean { return this._isTogglePressed; } /** * The icon to be used * - shows when the state is true if toggle has a value */ @Input() icon?: string; /** Sets the button type to 'submit' when true. */ @Input() isSubmit = false; /** Sets whether the button should have a ripple effect on click. */ @Input() ripple = true; /** * Binary state (toggle): * 0 - shows toggle * 1 - shows icon (default) * * @deprecated use isToggle=true input instead along with toggleOnIcon/toggleOffIcon options */ @Input() state?: boolean; /** * The icon to be used when the state is false. * * @deprecated use isToggle=true input instead along with toggleOnIcon/toggleOffIcon options */ @Input() toggle?: string; /** * Sets the expandable-expander class to be placed on the button for the * soho-expandablearea to use as it's expand/collapse trigger * */ @Input() expandableExpander = false; @HostBinding('class.btn') get btn() { return this.buttonType === SohoButtonComponent.BTN; } @HostBinding('class.btn-primary') get btnPrimary() { return this.buttonType === SohoButtonComponent.PRIMARY; } @HostBinding('class.btn-secondary') get btnSecondary() { return this.buttonType === SohoButtonComponent.SECONDARY; } @HostBinding('class.btn-tertiary') get btnTertiary(): boolean { return this.buttonType === SohoButtonComponent.TERTIARY; } @HostBinding('class.btn-icon') get btnIcon(): boolean { return this.buttonType === SohoButtonComponent.ICON || this.buttonType === SohoButtonComponent.FAVORITE; } @HostBinding('class.btn-toggle') get btnToggle() { return this.isToggle; } @HostBinding('class.btn-modal') get btnModal() { return this.buttonType === SohoButtonComponent.MODAL; } @HostBinding('class.btn-modal-primary') get btnModalPrimary() { return this.buttonType === SohoButtonComponent.MODAL_PRIMARY; } @HostBinding('class.is-pressed') get btnTogglePressed() { return this.isTogglePressed; } @HostBinding('class.icon-favorite') get iconFavorite(): boolean { return this.buttonType === SohoButtonComponent.FAVORITE; } @HostBinding('class.btn-moveto-left') @Input() moveToLeft: any; @HostBinding('class.btn-moveto-right') @Input() moveToRight: any; @HostBinding('class.btn-moveto-selected') @Input() moveToSelected: any; @HostBinding('class.no-ripple') get noRipple(): boolean { return !this.ripple; } @HostBinding('attr.type') get type() { return this.isSubmit ? 'submit' : 'button'; } @HostBinding('class.expandable-expander') get isExpandableExpander() { return this.expandableExpander; } /** * @deprecated no longer needed once this.toggle is removed. */ @HostListener('click') toggleState() { if (this.toggle) { // eslint-disable-line this.state = !this.state; // eslint-disable-line } } @HostBinding('attr.aria-pressed') get ariaPressed() { return this.isTogglePressed; } /** * Constructor. * * @param elementRef - the element matching the component's selector. */ constructor(private element: ElementRef, private ngZone: NgZone) { } // ------------------------------------------ // Lifecycle Events // ------------------------------------------ ngOnInit() { if (this.buttonType === SohoButtonComponent.FAVORITE) { if (this.isToggle) { this.toggleOffIcon = 'star-outlined'; this.toggleOnIcon = 'star-filled'; } else { // deprecated in 4.3.0 sohoxi this.toggle = 'star-outlined'; // eslint-disable-line this.icon = 'star-filled'; } } } ngAfterViewInit() { this.ngZone.runOutsideAngular(() => { // Wrap the element in a jQuery selector. this.jQueryElement = jQuery(this.element.nativeElement); // Initialise the Soho control. this.jQueryElement.button(this._buttonOptions); // Initialize title attribute as a soho tooltip if (this.jQueryElement.has('[title]') && !this.jQueryElement.has('[popover]')) { this.jQueryElement.tooltip(); } // Once the control is initialised, extract the control // plug-in from the element. The element name is defined // by the plug-in, but in this case is 'button'. this.button = this.jQueryElement.data('button'); if (this.state !== undefined) { // eslint-disable-line // turn off the default handling of the favorite icon switching // in the sohoxi controls (button.js). This is so that only this // button-component handles the switching of the toggle icon for // favorite. if (this.buttonType === SohoButtonComponent.FAVORITE) { this.jQueryElement.off('click.favorite'); } } // Remove aria-pressed attribute if button is not toggle if (!this.isToggle) { if (this.jQueryElement.attr('aria-pressed') !== undefined) { this.jQueryElement.removeAttr('aria-pressed'); } } }); // There are no 'extra' event handlers for button. } /** * Destructor. */ ngOnDestroy() { this.ngZone.runOutsideAngular(() => { if (this.jQueryElement) { this.jQueryElement.off(); } if (this.button) { this.button.destroy(); this.button = null; } }); } get hasIcon() { return (this.icon || (this.buttonOptions.toggleOnIcon && this.buttonOptions.toggleOffIcon)); } get currentIcon() { if (this.isToggle && this.buttonOptions.toggleOnIcon && this.buttonOptions.toggleOffIcon) { return this.isTogglePressed ? this.buttonOptions.toggleOnIcon : this.buttonOptions.toggleOffIcon; } if (this.toggle) { // eslint-disable-line return this.state ? this.icon : this.toggle; // eslint-disable-line } return this.icon; } /** * @deprecated use isToggle and isTogglePressed instead. */ public isPressed(): boolean { return this.ngZone.runOutsideAngular(() => { const pressed = this.element.nativeElement.getAttribute('aria-pressed'); this._isPressed = (pressed === true || pressed === 'true'); return this._isPressed; }); } }
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/consumersurveys/v2/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Consumer Surveys API v2 */ function load(name: "consumersurveys", version: "v2"): PromiseLike<void>; function load(name: "consumersurveys", version: "v2", callback: () => any): void; const mobileapppanels: consumersurveys.MobileapppanelsResource; const results: consumersurveys.ResultsResource; const surveys: consumersurveys.SurveysResource; namespace consumersurveys { interface FieldMask { fields?: FieldMask[]; id?: number; } interface MobileAppPanel { country?: string; isPublicPanel?: boolean; language?: string; mobileAppPanelId?: string; name?: string; owners?: string[]; } interface MobileAppPanelsListResponse { pageInfo?: PageInfo; /** Unique request ID used for logging and debugging. Please include in any error reporting or troubleshooting requests. */ requestId?: string; /** An individual predefined panel of Opinion Rewards mobile users. */ resources?: MobileAppPanel[]; tokenPagination?: TokenPagination; } interface PageInfo { resultPerPage?: number; startIndex?: number; totalResults?: number; } interface ResultsGetRequest { resultMask?: ResultsMask; } interface ResultsMask { fields?: FieldMask[]; projection?: string; } interface Survey { audience?: SurveyAudience; cost?: SurveyCost; customerData?: string; description?: string; owners?: string[]; questions?: SurveyQuestion[]; rejectionReason?: SurveyRejection; state?: string; surveyUrlId?: string; title?: string; wantedResponseCount?: number; } interface SurveyAudience { ages?: string[]; country?: string; countrySubdivision?: string; gender?: string; languages?: string[]; mobileAppPanelId?: string; populationSource?: string; } interface SurveyCost { costPerResponseNanos?: string; currencyCode?: string; maxCostPerResponseNanos?: string; nanos?: string; } interface SurveyQuestion { answerOrder?: string; answers?: string[]; hasOther?: boolean; highValueLabel?: string; images?: SurveyQuestionImage[]; lastAnswerPositionPinned?: boolean; lowValueLabel?: string; mustPickSuggestion?: boolean; numStars?: string; openTextPlaceholder?: string; openTextSuggestions?: string[]; question?: string; sentimentText?: string; singleLineResponse?: boolean; thresholdAnswers?: string[]; type?: string; unitOfMeasurementLabel?: string; videoId?: string; } interface SurveyQuestionImage { altText?: string; data?: string; url?: string; } interface SurveyRejection { explanation?: string; type?: string; } interface SurveyResults { status?: string; surveyUrlId?: string; } interface SurveysDeleteResponse { /** Unique request ID used for logging and debugging. Please include in any error reporting or troubleshooting requests. */ requestId?: string; } interface SurveysListResponse { pageInfo?: PageInfo; /** Unique request ID used for logging and debugging. Please include in any error reporting or troubleshooting requests. */ requestId?: string; /** An individual survey resource. */ resources?: Survey[]; tokenPagination?: TokenPagination; } interface SurveysStartRequest { /** Threshold to start a survey automically if the quoted prices is less than or equal to this value. See Survey.Cost for more details. */ maxCostPerResponseNanos?: string; } interface SurveysStartResponse { /** Unique request ID used for logging and debugging. Please include in any error reporting or troubleshooting requests. */ requestId?: string; } interface SurveysStopResponse { /** Unique request ID used for logging and debugging. Please include in any error reporting or troubleshooting requests. */ requestId?: string; } interface TokenPagination { nextPageToken?: string; previousPageToken?: string; } interface MobileapppanelsResource { /** Retrieves a MobileAppPanel that is available to the authenticated user. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** External URL ID for the panel. */ panelId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<MobileAppPanel>; /** Lists the MobileAppPanels available to the authenticated user. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; startIndex?: number; token?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<MobileAppPanelsListResponse>; /** Updates a MobileAppPanel. Currently the only property that can be updated is the owners property. */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** External URL ID for the panel. */ panelId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<MobileAppPanel>; } interface ResultsResource { /** * Retrieves any survey results that have been produced so far. Results are formatted as an Excel file. You must add "?alt=media" to the URL as an * argument to get results. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** External URL ID for the survey. */ surveyUrlId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<SurveyResults>; } interface SurveysResource { /** Removes a survey from view in all user GET requests. */ delete(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** External URL ID for the survey. */ surveyUrlId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<SurveysDeleteResponse>; /** Retrieves information about the specified survey. */ get(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** External URL ID for the survey. */ surveyUrlId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Survey>; /** Creates a survey. */ insert(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Survey>; /** Lists the surveys owned by the authenticated user. */ list(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; startIndex?: number; token?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<SurveysListResponse>; /** Begins running a survey. */ start(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; resourceId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<SurveysStartResponse>; /** Stops a running survey. */ stop(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; resourceId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<SurveysStopResponse>; /** Updates a survey. Currently the only property that can be updated is the owners property. */ update(request: { /** Data format for the response. */ alt?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** External URL ID for the survey. */ surveyUrlId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Survey>; } } }
the_stack
import { HttpClient } from '@angular/common/http'; import { ChangeDetectionStrategy, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Store } from '@ngrx/store'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service'; import { ObjectCacheService } from '../../../../core/cache/object-cache.service'; import { BitstreamDataService } from '../../../../core/data/bitstream-data.service'; import { CommunityDataService } from '../../../../core/data/community-data.service'; import { DefaultChangeAnalyzer } from '../../../../core/data/default-change-analyzer.service'; import { DSOChangeAnalyzer } from '../../../../core/data/dso-change-analyzer.service'; import { ItemDataService } from '../../../../core/data/item-data.service'; import { RelationshipService } from '../../../../core/data/relationship.service'; import { RemoteData } from '../../../../core/data/remote-data'; import { Bitstream } from '../../../../core/shared/bitstream.model'; import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service'; import { RelationshipType } from '../../../../core/shared/item-relationships/relationship-type.model'; import { Relationship } from '../../../../core/shared/item-relationships/relationship.model'; import { Item } from '../../../../core/shared/item.model'; import { UUIDService } from '../../../../core/shared/uuid.service'; import { isNotEmpty } from '../../../../shared/empty.util'; import { TranslateLoaderMock } from '../../../../shared/mocks/translate-loader.mock'; import { NotificationsService } from '../../../../shared/notifications/notifications.service'; import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { GenericItemPageFieldComponent } from '../../field-components/specific-field/generic/generic-item-page-field.component'; import { compareArraysUsing, compareArraysUsingIds } from './item-relationships-utils'; import { ItemComponent } from './item.component'; import { createPaginatedList } from '../../../../shared/testing/utils.test'; import { RouteService } from '../../../../core/services/route.service'; import { MetadataValue } from '../../../../core/shared/metadata.models'; export const iiifEnabled = Object.assign(new MetadataValue(),{ 'value': 'true', 'language': null, 'authority': null, 'confidence': -1, 'place': 0 }); export const iiifSearchEnabled = Object.assign(new MetadataValue(), { 'value': 'true', 'language': null, 'authority': null, 'confidence': -1, 'place': 0 }); export const mockRouteService = jasmine.createSpyObj('RouteService', ['getPreviousUrl']); /** * Create a generic test for an item-page-fields component using a mockItem and the type of component * @param {Item} mockItem The item to use for testing. The item needs to contain just the metadata necessary to * execute the tests for it's component. * @param component The type of component to create test cases for. * @returns {() => void} Returns a specDefinition for the test. */ export function getItemPageFieldsTest(mockItem: Item, component) { return () => { let comp: any; let fixture: ComponentFixture<any>; beforeEach(waitForAsync(() => { const mockBitstreamDataService = { getThumbnailFor(item: Item): Observable<RemoteData<Bitstream>> { return createSuccessfulRemoteDataObject$(new Bitstream()); } }; TestBed.configureTestingModule({ imports: [TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: TranslateLoaderMock } })], declarations: [component, GenericItemPageFieldComponent, TruncatePipe], providers: [ { provide: ItemDataService, useValue: {} }, { provide: TruncatableService, useValue: {} }, { provide: RelationshipService, useValue: {} }, { provide: ObjectCacheService, useValue: {} }, { provide: UUIDService, useValue: {} }, { provide: Store, useValue: {} }, { provide: RemoteDataBuildService, useValue: {} }, { provide: CommunityDataService, useValue: {} }, { provide: HALEndpointService, useValue: {} }, { provide: HttpClient, useValue: {} }, { provide: DSOChangeAnalyzer, useValue: {} }, { provide: NotificationsService, useValue: {} }, { provide: DefaultChangeAnalyzer, useValue: {} }, { provide: BitstreamDataService, useValue: mockBitstreamDataService }, { provide: RouteService, useValue: {} } ], schemas: [NO_ERRORS_SCHEMA] }).overrideComponent(component, { set: { changeDetection: ChangeDetectionStrategy.Default } }).compileComponents(); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(component); comp = fixture.componentInstance; comp.object = mockItem; fixture.detectChanges(); })); for (const key of Object.keys(mockItem.metadata)) { it(`should be calling a component with metadata field ${key}`, () => { const fields = fixture.debugElement.queryAll(By.css('ds-generic-item-page-field')); expect(containsFieldInput(fields, key)).toBeTruthy(); }); } }; } /** * Checks whether in a list of debug elements, at least one of them contains a specific metadata key in their * fields property. * @param {DebugElement[]} fields List of debug elements to check * @param {string} metadataKey A metadata key to look for * @returns {boolean} */ export function containsFieldInput(fields: DebugElement[], metadataKey: string): boolean { for (const field of fields) { const fieldComp = field.componentInstance; if (isNotEmpty(fieldComp.fields)) { if (fieldComp.fields.indexOf(metadataKey) > -1) { return true; } } } return false; } export function createRelationshipsObservable() { return createSuccessfulRemoteDataObject$(createPaginatedList([ Object.assign(new Relationship(), { relationshipType: createSuccessfulRemoteDataObject$(new RelationshipType()), leftItem: createSuccessfulRemoteDataObject$(new Item()), rightItem: createSuccessfulRemoteDataObject$(new Item()) }) ])); } describe('ItemComponent', () => { const arr1 = [ { id: 1, name: 'test' }, { id: 2, name: 'another test' }, { id: 3, name: 'one last test' } ]; const arrWithWrongId = [ { id: 1, name: 'test' }, { id: 5, // Wrong id on purpose name: 'another test' }, { id: 3, name: 'one last test' } ]; const arrWithWrongName = [ { id: 1, name: 'test' }, { id: 2, name: 'wrong test' // Wrong name on purpose }, { id: 3, name: 'one last test' } ]; const arrWithDifferentOrder = [arr1[0], arr1[2], arr1[1]]; const arrWithOneMore = [...arr1, { id: 4, name: 'fourth test' }]; const arrWithAddedProperties = [ { id: 1, name: 'test', extra: 'extra property' }, { id: 2, name: 'another test', extra: 'extra property' }, { id: 3, name: 'one last test', extra: 'extra property' } ]; const arrOfPrimitiveTypes = [1, 2, 3, 4]; const arrOfPrimitiveTypesWithOneWrong = [1, 5, 3, 4]; const arrOfPrimitiveTypesWithDifferentOrder = [1, 3, 2, 4]; const arrOfPrimitiveTypesWithOneMore = [1, 2, 3, 4, 5]; describe('when calling compareArraysUsing', () => { describe('and comparing by id', () => { const compare = compareArraysUsing<any>((o) => o.id); it('should return true when comparing the same array', () => { expect(compare(arr1, arr1)).toBeTruthy(); }); it('should return true regardless of the order', () => { expect(compare(arr1, arrWithDifferentOrder)).toBeTruthy(); }); it('should return true regardless of other properties being different', () => { expect(compare(arr1, arrWithWrongName)).toBeTruthy(); }); it('should return true regardless of extra properties', () => { expect(compare(arr1, arrWithAddedProperties)).toBeTruthy(); }); it('should return false when the ids don\'t match', () => { expect(compare(arr1, arrWithWrongId)).toBeFalsy(); }); it('should return false when the sizes don\'t match', () => { expect(compare(arr1, arrWithOneMore)).toBeFalsy(); }); }); describe('and comparing by name', () => { const compare = compareArraysUsing<any>((o) => o.name); it('should return true when comparing the same array', () => { expect(compare(arr1, arr1)).toBeTruthy(); }); it('should return true regardless of the order', () => { expect(compare(arr1, arrWithDifferentOrder)).toBeTruthy(); }); it('should return true regardless of other properties being different', () => { expect(compare(arr1, arrWithWrongId)).toBeTruthy(); }); it('should return true regardless of extra properties', () => { expect(compare(arr1, arrWithAddedProperties)).toBeTruthy(); }); it('should return false when the names don\'t match', () => { expect(compare(arr1, arrWithWrongName)).toBeFalsy(); }); it('should return false when the sizes don\'t match', () => { expect(compare(arr1, arrWithOneMore)).toBeFalsy(); }); }); describe('and comparing by full objects', () => { const compare = compareArraysUsing<any>((o) => o); it('should return true when comparing the same array', () => { expect(compare(arr1, arr1)).toBeTruthy(); }); it('should return true regardless of the order', () => { expect(compare(arr1, arrWithDifferentOrder)).toBeTruthy(); }); it('should return false when extra properties are added', () => { expect(compare(arr1, arrWithAddedProperties)).toBeFalsy(); }); it('should return false when the ids don\'t match', () => { expect(compare(arr1, arrWithWrongId)).toBeFalsy(); }); it('should return false when the names don\'t match', () => { expect(compare(arr1, arrWithWrongName)).toBeFalsy(); }); it('should return false when the sizes don\'t match', () => { expect(compare(arr1, arrWithOneMore)).toBeFalsy(); }); }); describe('and comparing with primitive objects as source', () => { const compare = compareArraysUsing<any>((o) => o); it('should return true when comparing the same array', () => { expect(compare(arrOfPrimitiveTypes, arrOfPrimitiveTypes)).toBeTruthy(); }); it('should return true regardless of the order', () => { expect(compare(arrOfPrimitiveTypes, arrOfPrimitiveTypesWithDifferentOrder)).toBeTruthy(); }); it('should return false when at least one is wrong', () => { expect(compare(arrOfPrimitiveTypes, arrOfPrimitiveTypesWithOneWrong)).toBeFalsy(); }); it('should return false when the sizes don\'t match', () => { expect(compare(arrOfPrimitiveTypes, arrOfPrimitiveTypesWithOneMore)).toBeFalsy(); }); }); }); describe('when calling compareArraysUsingIds', () => { const compare = compareArraysUsingIds(); it('should return true when comparing the same array', () => { expect(compare(arr1 as any, arr1 as any)).toBeTruthy(); }); it('should return true regardless of the order', () => { expect(compare(arr1 as any, arrWithDifferentOrder as any)).toBeTruthy(); }); it('should return true regardless of other properties being different', () => { expect(compare(arr1 as any, arrWithWrongName as any)).toBeTruthy(); }); it('should return true regardless of extra properties', () => { expect(compare(arr1 as any, arrWithAddedProperties as any)).toBeTruthy(); }); it('should return false when the ids don\'t match', () => { expect(compare(arr1 as any, arrWithWrongId as any)).toBeFalsy(); }); it('should return false when the sizes don\'t match', () => { expect(compare(arr1 as any, arrWithOneMore as any)).toBeFalsy(); }); }); });
the_stack
import { Body, Get, Put, Delete, Param, JsonController, UseBefore, NotFoundError, BadRequestError, Post, Authorized, CurrentUser, UploadedFile, Res, UploadedFiles, InternalServerError, ForbiddenError } from 'routing-controllers'; import passportJwtMiddleware from '../security/passportJwtMiddleware'; import {errorCodes} from '../config/errorCodes'; import {Course} from '../models/Course'; import {Lecture} from '../models/Lecture'; import {IUnitModel, Unit, AssignmentUnit} from '../models/units/Unit'; import {IUser} from '../../../shared/models/IUser'; import {IAssignment} from '../../../shared/models/assignment/IAssignment'; import config from '../config/main'; import {File} from '../models/mediaManager/File'; import {IFile} from '../../../shared/models/mediaManager/IFile'; import {IAssignmentUnit} from '../../../shared/models/units/IAssignmentUnit'; import {IProgress} from '../../build/../../shared/models/progress/IProgress'; import {Progress} from '../models/progress/Progress'; import {IAssignmentUnitProgress} from '../../../shared/models/progress/IAssignmentProgress'; import {User} from '../models/User'; import crypto = require('crypto'); import {IAssignmentUnitModel} from '../models/units/AssignmentUnit'; import {promisify} from 'util'; import {Response} from 'express'; const multer = require('multer'); const path = require('path'); const fs = require('fs'); const archiver = require('archiver'); const uploadOptions = { storage: multer.diskStorage({ destination: (req: any, file: any, cb: any) => { cb(null, config.uploadFolder); }, filename: (req: any, file: any, cb: any) => { crypto.pseudoRandomBytes(16, (err, raw) => { cb(err, err ? undefined : raw.toString('hex') + path.extname(file.originalname)); }); } }), }; @JsonController('/units') @UseBefore(passportJwtMiddleware) export class UnitController { protected waitForArchiveToFinish(output: any, archive: any) { return new Promise((resolve, reject) => { output.on('close', () => { resolve(); }); archive.finalize(); }); } /** * @api {get} /api/units/:id Request unit * @apiName GetUnit * @apiGroup Unit * * @apiParam {String} id Unit ID. * * @apiSuccess {Unit} unit Unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2017-11-08T22:00:11.500Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "unitCreator": "5a037e6b60f72236d8e7c834", * "type": "free-text", * "__v": 0 * } * * @apiError NotFoundError * @apiError ForbiddenError */ @Get('/:id') async getUnit(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const unit = await this.getUnitFor(id, currentUser, 'userCanViewCourse'); return unit.toObject(); } /** * @api {post} /api/units/ Add unit * @apiName PostUnit * @apiGroup Unit * @apiPermission teacher * @apiPermission admin * * @apiParam {Object} file Uploaded file. * @apiParam {Object} data New unit data. * * @apiSuccess {Unit} unit Added unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2017-11-08T22:00:11.500Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "type": "free-text", * "unitCreator": "5a037e6b60f72236d8e7c834", * "__v": 0 * } * * @apiError BadRequestError Invalid combination of file upload and unit data. * @apiError BadRequestError No lecture ID was submitted. * @apiError BadRequestError No unit was submitted. * @apiError BadRequestError Unit has no _course set. * @apiError BadRequestError * @apiError ForbiddenError * @apiError ValidationError */ @Authorized(['teacher', 'admin']) @Post('/') async addUnit(@Body() data: any, @CurrentUser() currentUser: IUser) { // discard invalid requests this.checkPostParam(data); const course = await Course.findById(data.model._course); if (!course.checkPrivileges(currentUser).userCanEditCourse) { throw new ForbiddenError(); } // Set current user as creator, old unit's dont have a creator data.model.unitCreator = currentUser._id; try { const createdUnit = await Unit.create(data.model); return await this.pushToLecture(data.lectureId, createdUnit); } catch (err) { if (err.name === 'ValidationError') { throw err; } else { throw new BadRequestError(err); } } } /** * @api {put} /api/units/:id Update unit * @apiName PutUnit * @apiGroup Unit * @apiPermission teacher * @apiPermission admin * * @apiParam {Object} file Uploaded file. * @apiParam {String} id Unit ID. * @apiParam {Object} data New unit data. * * @apiSuccess {Unit} unit Updated unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2018-01-29T23:43:07.220Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "type": "free-text", * "__v": 0 * } * * @apiError BadRequestError Invalid combination of file upload and unit data. * @apiError BadRequestError * @apiError NotFoundError * @apiError ForbiddenError * @apiError ValidationError */ @Authorized(['teacher', 'admin']) @Put('/:id') async updateUnit(@Param('id') id: string, @Body() data: any, @CurrentUser() currentUser: IUser) { const oldUnit = await this.getUnitFor(id, currentUser, 'userCanEditCourse'); try { oldUnit.set(data); const updatedUnit: IUnitModel = await oldUnit.save(); return updatedUnit.toObject(); } catch (err) { if (err.name === 'ValidationError') { throw err; } else { throw new BadRequestError(err); } } } /** * @api {delete} /api/units/:id Delete unit * @apiName DeleteUnit * @apiGroup Unit * @apiPermission teacher * @apiPermission admin * * @apiParam {String} id Unit ID. * * @apiSuccess {Object} result Empty object. * * @apiSuccessExample {json} Success-Response: * {} * * @apiError NotFoundError * @apiError ForbiddenError */ @Authorized(['teacher', 'admin']) @Delete('/:id') async deleteUnit(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const unit = await this.getUnitFor(id, currentUser, 'userCanEditCourse'); await Lecture.updateMany({}, {$pull: {units: id}}); await unit.remove(); return {}; } private async getUnitFor (unitId: string, currentUser: IUser, privilege: 'userCanViewCourse' | 'userCanEditCourse') { const unit = await Unit.findById(unitId).orFail(new NotFoundError()); const course = await Course.findById(unit._course); if (!course.checkPrivileges(currentUser)[privilege]) { throw new ForbiddenError(); } return unit; } /** * @api {post} /api/units/:id/assignment Add assignment * @apiName PostAssignment * @apiGroup Unit * @apiPermission student * * @apiSuccess {IAssignment} assignment. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2017-11-08T22:00:11.500Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "type": "free-text", * "unitCreator": "5a037e6b60f72236d8e7c834", * "__v": 0 * } * * @apiError BadRequestError No lecture ID was submitted. * @apiError BadRequestError No unit was submitted. * @apiError BadRequestError Unit has no _course set. * @apiError BadRequestError * @apiError ValidationError */ @Authorized(['student']) @Post('/:id/assignment') async addAssignment(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(id).orFail(new NotFoundError()); // TODO: check if user is in course. let assignment: IAssignment = assignmentUnit.assignments.find(submittedAssignment => { return submittedAssignment.user._id.toString() === currentUser._id; }); if (!!assignment) { // The user has already created an assignment. We cannot create another one. throw new BadRequestError(); } try { assignment = { _id: null, files: [], user: currentUser._id, submitted: false, checked: -1, submittedDate: new Date() }; assignmentUnit.assignments.push(assignment); await assignmentUnit.save(); return assignment; } catch (err) { throw new BadRequestError(err); } } /** * Is called when the user wants to add a file to the assignment. * The user can add as much file as she wants as long as the assignment is not finalized/submitted yet. * * @apiParam {String} unitId * @apiParam {Object} uploadedFile * @apiParam {IUser} currentUser * * @apiError NotFoundError The unit was not found or there isn't an assignment from the current user in the unit. */ @Authorized(['student']) @Put('/:id/assignment/files') async addFileToAssignment(@Param('id') unitId: string, @UploadedFile('file', {options: uploadOptions}) uploadedFile: any, @CurrentUser() currentUser: IUser) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(unitId) .orFail(new NotFoundError()); const assignment = assignmentUnit.assignments.find(submittedAssignment => { return submittedAssignment.user._id.toString() === currentUser._id; }); if (!assignment) { throw new NotFoundError(); } // The user already submitted/finalized the assignment. if (assignment.submitted) { throw new BadRequestError(); } const fileMetadata: IFile = new File({ name: uploadedFile.originalname, physicalPath: uploadedFile.path, link: uploadedFile.filename, size: uploadedFile.size, mimeType: uploadedFile.mimetype, }); try { const file = await new File(fileMetadata).save(); if (!assignment.files) { assignment.files = []; } assignment.files.push(file._id); await assignmentUnit.save(); return file.toObject(); } catch (error) { throw new InternalServerError(error.message); } } /** * @api {put} /api/units/:id/assignment Update assignment * @apiName PutUnit * @apiGroup Unit * @apiPermission teacher * @apiPermission admin * * @apiParam {Object} file Uploaded file. * @apiParam {String} id Unit ID. * @apiParam {Object} data New unit data. * * @apiSuccess {Unit} unit Updated unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2018-01-29T23:43:07.220Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "type": "free-text", * "__v": 0 * } * * @apiError NotFoundError * @apiError BadRequestError Invalid combination of file upload and unit data. * @apiError BadRequestError * @apiError ValidationError */ @Authorized(['teacher', 'admin', 'student']) @Put('/:id/assignment') async updateAssignment(@Param('id') id: string, @Body() data: IAssignment, @CurrentUser() currentUser: IUser) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(id).orFail(new NotFoundError()); let assignment: IAssignment = null; // The current user updates an assignment of a student. if (currentUser.role === 'teacher' || currentUser.role === 'admin') { if (!data.user._id) { throw new BadRequestError(); } assignment = assignmentUnit.assignments.find( submittedAssignment => `${submittedAssignment.user}` === data.user._id ); assignment.checked = data.checked; } else { // A student updates her own assignment. // We can just retrieve the assignment where the author is the current user, as an user can // only have one assignment. assignment = assignmentUnit.assignments.find( submittedAssignment => `${submittedAssignment.user}` === currentUser._id ); if (!assignment.submitted) { // Update the submitted state of the assignment. assignment.submitted = data.submitted; assignment.submittedDate = new Date(); } } try { await assignmentUnit.save(); } catch (err) { if (err.name === 'ValidationError') { throw err; } else { throw new BadRequestError(err); } } return true; } /** * @api {delete} /api/units/:id/assignment Delete assignment * @apiName DeleteAssginment * @apiGroup Unit * @apiPermission student * * @apiParam {String} id Unit ID. * * @apiSuccess {Boolean} result Confirmation of deletion. * * @apiSuccessExample {json} Success-Response: * { * "result": true * } * * @apiError NotFoundError */ @Authorized(['student']) @Delete('/:id/assignment') async deleteAssignment(@Param('id') id: string, @CurrentUser() currentUser: IUser) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(id); if (!assignmentUnit) { throw new NotFoundError(); } for (const assignment of assignmentUnit.assignments) { if (assignment.user._id.toString() === currentUser._id) { if (assignment.submitted) { throw new BadRequestError(); } const index = assignmentUnit.assignments.indexOf(assignment, 0); assignmentUnit.assignments.splice(index, 1); await assignmentUnit.save(); return true; } } } /** * @api {get} /api/units/:id/assignments/:assignment Request unit * @apiName GetUnit * @apiGroup Unit * * @apiParam {String} id Unit ID. * @apiParam {String} assignment Assignment id. * * @apiSuccess {Unit} unit Unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2017-11-08T22:00:11.500Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "unitCreator": "5a037e6b60f72236d8e7c834", * "type": "free-text", * "__v": 0 * } */ @Get('/:id/assignments/:user/files') @Authorized(['teacher']) async downloadFilesOfSingleAssignment(@Param('id') id: string, @Param('user') userId: string, @Res() response: Response) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(id); if (!assignmentUnit) { throw new NotFoundError(); } const assignment = assignmentUnit.assignments.find(row => `${row.user._id}` === userId); if (!assignment.files.length) { return; } const user = await User.findById(assignment.user); const filepath = `${config.tmpFileCacheFolder}${user.profile.lastName}_${assignmentUnit.name}.zip`; const output = fs.createWriteStream(filepath); const archive = archiver('zip', { zlib: {level: 9} }); archive.pipe(output); for (const fileMetadata of assignment.files) { const file = await File.findById(fileMetadata); archive .file(`uploads/${file.link}`, { name: user.profile.lastName + '_' + user.profile.firstName + '_' + file.name }); } archive.on('error', () => { throw new NotFoundError(); }); await this.waitForArchiveToFinish(output, archive); response.status(200); response.setHeader('Connection', 'keep-alive'); response.setHeader('Access-Control-Expose-Headers', 'Content-Disposition'); await promisify<string, void>(response.download.bind(response))(filepath); return response; } /** * @api {get} /api/units/:id/assignments Request unit * @apiName GetUnit * @apiGroup Unit * * @apiParam {String} id Unit ID. * * @apiSuccess {Unit} unit Unit. * * @apiSuccessExample {json} Success-Response: * { * "_id": "5a037e6b60f72236d8e7c858", * "updatedAt": "2017-11-08T22:00:11.500Z", * "createdAt": "2017-11-08T22:00:11.500Z", * "name": "What is Lorem Ipsum?", * "description": "...", * "markdown": "# What is Lorem Ipsum?\n**Lorem Ipsum** is simply dummy text of the printing and typesetting industry.", * "_course": "5a037e6b60f72236d8e7c83b", * "unitCreator": "5a037e6b60f72236d8e7c834", * "type": "free-text", * "__v": 0 * } */ @Get('/:id/assignments/files') @Authorized(['teacher']) async getAllAssignments(@Param('id') id: string, @Res() response: Response) { const assignmentUnit = <IAssignmentUnitModel> await Unit.findById(id); if (!assignmentUnit) { throw new NotFoundError(); } const filepath = config.tmpFileCacheFolder + assignmentUnit.name + '.zip'; const output = fs.createWriteStream(filepath); const archive = archiver('zip', { zlib: {level: 9} }); archive.pipe(output); for (const assignment of assignmentUnit.assignments) { const user = await User.findById(assignment.user); for (const fileMetadata of assignment.files) { const file = await File.findById(fileMetadata); archive .file(`uploads/${file.link}`, { name: user.profile.lastName + '_' + user.profile.firstName + '_' + file.name }); } } archive.on('error', () => { throw new NotFoundError(); }); await this.waitForArchiveToFinish(output, archive); response.setHeader('Connection', 'keep-alive'); response.setHeader('Access-Control-Expose-Headers', 'Content-Disposition'); await promisify<string, void>(response.download.bind(response))(filepath); return response; } private pushToLecture(lectureId: string, unit: any) { return Lecture.findById(lectureId) .then((lecture) => { lecture.units.push(unit); return lecture.save(); }) .then(() => { return unit.populateUnit(); }) .then((populatedUnit) => { return populatedUnit.toObject(); }) .catch((err) => { throw new BadRequestError(err); }); } private checkPostParam(data: any) { if (!data.lectureId) { throw new BadRequestError(errorCodes.unit.postMissingLectureId.text); } if (!data.model) { throw new BadRequestError(errorCodes.unit.postMissingUnit.text); } if (!data.model._course) { throw new BadRequestError(errorCodes.unit.postMissingCourse.text); } } }
the_stack
import { Repositories } from "@arkecosystem/core-database"; import { Container, Contracts, Utils as AppUtils } from "@arkecosystem/core-kernel"; import { Enums, Interfaces, Managers, Transactions, Utils } from "@arkecosystem/crypto"; import assert from "assert"; import { ColdWalletError, InsufficientBalanceError, InvalidMultiSignaturesError, InvalidSecondSignatureError, LegacyMultiSignatureError, LegacyMultiSignatureRegistrationError, MissingMultiSignatureOnSenderError, SenderWalletMismatchError, UnexpectedNonceError, UnexpectedSecondSignatureError, UnsupportedMultiSignatureTransactionError, } from "../errors"; // todo: revisit the implementation, container usage and arguments after core-database rework @Container.injectable() export abstract class TransactionHandler { @Container.inject(Container.Identifiers.Application) protected readonly app!: Contracts.Kernel.Application; @Container.inject(Container.Identifiers.DatabaseBlockRepository) protected readonly blockRepository!: Repositories.BlockRepository; @Container.inject(Container.Identifiers.DatabaseTransactionRepository) protected readonly transactionRepository!: Repositories.TransactionRepository; @Container.inject(Container.Identifiers.WalletRepository) protected readonly walletRepository!: Contracts.State.WalletRepository; @Container.inject(Container.Identifiers.LogService) protected readonly logger!: Contracts.Kernel.Logger; public async verify(transaction: Interfaces.ITransaction): Promise<boolean> { AppUtils.assert.defined<string>(transaction.data.senderPublicKey); const senderWallet: Contracts.State.Wallet = this.walletRepository.findByPublicKey( transaction.data.senderPublicKey, ); if (senderWallet.hasMultiSignature()) { transaction.isVerified = this.verifySignatures(senderWallet, transaction.data); } return transaction.isVerified; } public dynamicFee({ addonBytes, satoshiPerByte, transaction, }: Contracts.Shared.DynamicFeeContext): Utils.BigNumber { addonBytes = addonBytes || 0; if (satoshiPerByte <= 0) { satoshiPerByte = 1; } const transactionSizeInBytes: number = Math.round(transaction.serialized.length / 2); return Utils.BigNumber.make(addonBytes + transactionSizeInBytes).times(satoshiPerByte); } public async throwIfCannotBeApplied( transaction: Interfaces.ITransaction, sender: Contracts.State.Wallet, ): Promise<void> { const senderWallet: Contracts.State.Wallet = this.walletRepository.findByAddress(sender.getAddress()); AppUtils.assert.defined<string>(sender.getPublicKey()); if (!this.walletRepository.hasByPublicKey(sender.getPublicKey()!) && senderWallet.getBalance().isZero()) { throw new ColdWalletError(); } return this.performGenericWalletChecks(transaction, sender); } public async apply(transaction: Interfaces.ITransaction): Promise<void> { await this.applyToSender(transaction); await this.applyToRecipient(transaction); } public async revert(transaction: Interfaces.ITransaction): Promise<void> { await this.revertForSender(transaction); await this.revertForRecipient(transaction); } public async applyToSender(transaction: Interfaces.ITransaction): Promise<void> { AppUtils.assert.defined<string>(transaction.data.senderPublicKey); const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); const data: Interfaces.ITransactionData = transaction.data; if (Utils.isException(data)) { this.logger.warning(`Transaction forcibly applied as an exception: ${transaction.id}.`); } await this.throwIfCannotBeApplied(transaction, sender); // TODO: extract version specific code if (data.version && data.version > 1) { this.verifyTransactionNonceApply(sender, transaction); AppUtils.assert.defined<AppUtils.BigNumber>(data.nonce); sender.setNonce(data.nonce); } else { sender.increaseNonce(); } const newBalance: Utils.BigNumber = sender.getBalance().minus(data.amount).minus(data.fee); assert(Utils.isException(transaction.data) || !newBalance.isNegative()); // negativeBalanceExceptions check is never executed, because performGenericWalletChecks already checks balance // if (process.env.CORE_ENV === "test") { // assert(Utils.isException(transaction.data.id) || !newBalance.isNegative()); // } else { // if (newBalance.isNegative()) { // const negativeBalanceExceptions: Record<string, Record<string, string>> = // Managers.configManager.get("exceptions.negativeBalances") || {}; // // AppUtils.assert.defined<string>(sender.publicKey); // // const negativeBalances: Record<string, string> = negativeBalanceExceptions[sender.publicKey] || {}; // // if (!newBalance.isEqualTo(negativeBalances[sender.nonce.toString()] || 0)) { // throw new InsufficientBalanceError(); // } // } // } sender.setBalance(newBalance); } public async revertForSender(transaction: Interfaces.ITransaction): Promise<void> { AppUtils.assert.defined<string>(transaction.data.senderPublicKey); const sender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(transaction.data.senderPublicKey); const data: Interfaces.ITransactionData = transaction.data; sender.increaseBalance(data.amount.plus(data.fee)); // TODO: extract version specific code this.verifyTransactionNonceRevert(sender, transaction); sender.decreaseNonce(); } /** * Database Service */ public emitEvents(transaction: Interfaces.ITransaction, emitter: Contracts.Kernel.EventDispatcher): void {} /** * Transaction Pool logic */ public async throwIfCannotEnterPool(transaction: Interfaces.ITransaction): Promise<void> {} /** * @param {Contracts.State.Wallet} wallet * @param {Interfaces.ITransactionData} transaction * @param {Interfaces.IMultiSignatureAsset} [multiSignature] * @returns {boolean} * @memberof TransactionHandler */ public verifySignatures( wallet: Contracts.State.Wallet, transaction: Interfaces.ITransactionData, multiSignature?: Interfaces.IMultiSignatureAsset, ): boolean { return Transactions.Verifier.verifySignatures( transaction, multiSignature || wallet.getAttribute("multiSignature"), ); } protected async performGenericWalletChecks( transaction: Interfaces.ITransaction, sender: Contracts.State.Wallet, ): Promise<void> { const data: Interfaces.ITransactionData = transaction.data; if (Utils.isException(data)) { return; } this.verifyTransactionNonceApply(sender, transaction); if (sender.getBalance().minus(data.amount).minus(data.fee).isNegative()) { throw new InsufficientBalanceError(); } if (data.senderPublicKey !== sender.getPublicKey()) { throw new SenderWalletMismatchError(); } if (sender.hasSecondSignature()) { AppUtils.assert.defined<string>(data.senderPublicKey); // Ensure the database wallet already has a 2nd signature, in case we checked a pool wallet. const dbSender: Contracts.State.Wallet = this.walletRepository.findByPublicKey(data.senderPublicKey); if (!dbSender.hasSecondSignature()) { throw new UnexpectedSecondSignatureError(); } if (!Transactions.Verifier.verifySecondSignature(data, dbSender.getAttribute("secondPublicKey"))) { throw new InvalidSecondSignatureError(); } } else if (data.secondSignature || data.signSignature) { const isException = Managers.configManager.get("network.name") === "devnet" && Managers.configManager.getMilestone().ignoreInvalidSecondSignatureField; if (!isException) { throw new UnexpectedSecondSignatureError(); } } // Prevent legacy multi signatures from being used const isMultiSignatureRegistration: boolean = transaction.type === Enums.TransactionType.MultiSignature && transaction.typeGroup === Enums.TransactionTypeGroup.Core; if (isMultiSignatureRegistration && !Managers.configManager.getMilestone().aip11) { throw new LegacyMultiSignatureRegistrationError(); } if (sender.hasMultiSignature()) { AppUtils.assert.defined<string>(transaction.data.senderPublicKey); // Ensure the database wallet already has a multi signature, in case we checked a pool wallet. const dbSender: Contracts.State.Wallet = this.walletRepository.findByPublicKey( transaction.data.senderPublicKey, ); if (!dbSender.hasMultiSignature()) { throw new MissingMultiSignatureOnSenderError(); } if (dbSender.hasAttribute("multiSignature.legacy")) { throw new LegacyMultiSignatureError(); } if (!this.verifySignatures(dbSender, data, dbSender.getAttribute("multiSignature"))) { throw new InvalidMultiSignaturesError(); } } else if (transaction.data.signatures && !isMultiSignatureRegistration) { throw new UnsupportedMultiSignatureTransactionError(); } } /** * Verify that the transaction's nonce is the wallet nonce plus one, so that the * transaction can be applied to the wallet. Throw an exception if it is not. * * @param {Interfaces.ITransaction} transaction * @memberof Wallet */ protected verifyTransactionNonceApply(wallet: Contracts.State.Wallet, transaction: Interfaces.ITransaction): void { const version: number = transaction.data.version || 1; const nonce: AppUtils.BigNumber = transaction.data.nonce || AppUtils.BigNumber.ZERO; if (version > 1 && !wallet.getNonce().plus(1).isEqualTo(nonce)) { throw new UnexpectedNonceError(nonce, wallet, false); } } /** * Verify that the transaction's nonce is the same as the wallet nonce, so that the * transaction can be reverted from the wallet. Throw an exception if it is not. * * @param wallet * @param {Interfaces.ITransaction} transaction * @memberof Wallet */ protected verifyTransactionNonceRevert(wallet: Contracts.State.Wallet, transaction: Interfaces.ITransaction): void { const version: number = transaction.data.version || 1; const nonce: AppUtils.BigNumber = transaction.data.nonce || AppUtils.BigNumber.ZERO; if (version > 1 && !wallet.getNonce().isEqualTo(nonce)) { throw new UnexpectedNonceError(nonce, wallet, true); } } public abstract getConstructor(): Transactions.TransactionConstructor; public abstract dependencies(): ReadonlyArray<TransactionHandlerConstructor>; public abstract walletAttributes(): ReadonlyArray<string>; public abstract isActivated(): Promise<boolean>; /** * Wallet logic */ public abstract async bootstrap(): Promise<void>; public abstract async applyToRecipient(transaction: Interfaces.ITransaction): Promise<void>; public abstract async revertForRecipient(transaction: Interfaces.ITransaction): Promise<void>; } export type TransactionHandlerConstructor = new () => TransactionHandler;
the_stack
import {CloudPrintInterfaceEventType, CloudPrintInterfaceImpl, CrButtonElement, Destination, DestinationStoreEventType, LocalDestinationInfo, makeRecentDestination, MeasurementSystemUnitType, NativeInitialSettings, NativeLayerImpl, PluginProxyImpl, PrintPreviewAppElement, ScalingType, State, whenReady} from 'chrome://print/print_preview.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, waitBeforeNextRender} from 'chrome://webui-test/test_util.js'; import {CloudPrintInterfaceStub} from './cloud_print_interface_stub.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {setNativeLayerCrosInstance} from './native_layer_cros_stub.js'; // </if> import {NativeLayerStub} from './native_layer_stub.js'; import {createDestinationWithCertificateStatus, getCddTemplate, getDefaultMediaSize, getDefaultOrientation} from './print_preview_test_utils.js'; import {TestPluginProxy} from './test_plugin_proxy.js'; const invalid_settings_browsertest = { suiteName: 'InvalidSettingsBrowserTest', TestNames: { InvalidSettingsError: 'invalid settings error', InvalidCertificateError: 'invalid certificate error', InvalidCertificateErrorReselectDestination: 'invalid certificate reselect', }, }; Object.assign( window, {invalid_settings_browsertest: invalid_settings_browsertest}); suite(invalid_settings_browsertest.suiteName, function() { let page: PrintPreviewAppElement; let nativeLayer: NativeLayerStub; let cloudPrintInterface: CloudPrintInterfaceStub; const initialSettings: NativeInitialSettings = { isInKioskAutoPrintMode: false, isInAppKioskMode: false, thousandsDelimiter: ',', decimalDelimiter: '.', unitType: MeasurementSystemUnitType.IMPERIAL, previewModifiable: true, destinationsManaged: false, previewIsFromArc: false, documentTitle: 'title', documentHasSelection: true, shouldPrintSelectionOnly: false, uiLocale: 'en-us', printerName: 'FooDevice', pdfPrinterDisabled: false, serializedAppStateStr: null, serializedDefaultDestinationSelectionRulesStr: null }; let localDestinationInfos: LocalDestinationInfo[] = [ {printerName: 'FooName', deviceName: 'FooDevice'}, {printerName: 'BarName', deviceName: 'BarDevice'}, ]; setup(function() { nativeLayer = new NativeLayerStub(); NativeLayerImpl.setInstance(nativeLayer); // <if expr="chromeos_ash or chromeos_lacros"> setNativeLayerCrosInstance(); // </if> cloudPrintInterface = new CloudPrintInterfaceStub(); CloudPrintInterfaceImpl.setInstance(cloudPrintInterface); document.body.innerHTML = ''; }); /** * Initializes the page with initial settings and local destinations * given by |initialSettings| and |localDestinationInfos|. Also creates * the fake plugin. Moved out of setup so tests can set those parameters * differently. */ function createPage() { nativeLayer.setInitialSettings(initialSettings); nativeLayer.setLocalDestinations(localDestinationInfos); PluginProxyImpl.setInstance(new TestPluginProxy()); page = document.createElement('print-preview-app'); document.body.appendChild(page); page.$.documentInfo.init(true, false, 'title', false); } /** * Performs some setup for invalid certificate tests using 2 destinations * in |printers|. printers[0] will be set as the most recent destination, * and printers[1] will be the second most recent destination. Sets up * cloud print interface, user info, and runs createPage(). */ function setupInvalidCertificateTest(printers: Destination[]) { initialSettings.printerName = ''; initialSettings.serializedAppStateStr = JSON.stringify({ version: 2, recentDestinations: [ makeRecentDestination(printers[0]!), makeRecentDestination(printers[1]!), ], }); initialSettings.cloudPrintURL = 'cloudprint URL'; localDestinationInfos = []; loadTimeData.overrideValues({isEnterpriseManaged: false}); createPage(); printers.forEach(printer => cloudPrintInterface.setPrinter(printer)); } // Tests that when a printer cannot be communicated with correctly the // preview area displays an invalid printer error message and printing // is disabled. Verifies that the user can recover from this error by // selecting a different, valid printer. test( assert(invalid_settings_browsertest.TestNames.InvalidSettingsError), function() { createPage(); const barDevice = getCddTemplate('BarDevice'); nativeLayer.setLocalDestinationCapabilities(barDevice); // FooDevice is the default printer, so will be selected for the initial // preview request. nativeLayer.setInvalidPrinterId('FooDevice'); // Expected message const expectedMessage = 'The selected printer is not available or not ' + 'installed correctly. Check your printer or try selecting another ' + 'printer.'; // Get references to relevant elements. const previewAreaEl = page.$.previewArea; const overlay = previewAreaEl.shadowRoot!.querySelector( '.preview-area-overlay-layer')!; const messageEl = previewAreaEl.shadowRoot!.querySelector('.preview-area-message')!; const sidebar = page.shadowRoot!.querySelector('print-preview-sidebar')!; let printButton: CrButtonElement; const destinationSettings = sidebar.shadowRoot!.querySelector( 'print-preview-destination-settings')!; return waitBeforeNextRender(page) .then(() => { const parentElement = sidebar.shadowRoot!.querySelector( 'print-preview-button-strip')!; printButton = parentElement.shadowRoot!.querySelector<CrButtonElement>( '.action-button')!; return Promise.all([ whenReady(), nativeLayer.whenCalled('getInitialSettings'), ]); }) .then(function() { destinationSettings.getDestinationStoreForTest() .startLoadAllDestinations(); // Wait for the preview request. return Promise.all([ nativeLayer.whenCalled('getPrinterCapabilities'), nativeLayer.whenCalled('getPreview') ]); }) .then(function() { // Print preview should have failed with invalid settings, since // FooDevice was set as an invalid printer. assertFalse(overlay.classList.contains('invisible')); assertTrue(messageEl.textContent!.includes(expectedMessage)); assertEquals(State.ERROR, page.state); // Verify that the print button is disabled assertTrue(printButton.disabled); // Select should still be enabled so that the user can select a // new printer. assertFalse(destinationSettings.$.destinationSelect.disabled); // Reset nativeLayer.reset(); // Select a new destination const barDestination = destinationSettings.getDestinationStoreForTest() .destinations() .find((d: Destination) => d.id === 'BarDevice'); destinationSettings.getDestinationStoreForTest() .selectDestination(assert(barDestination!)); // Wait for the preview to be updated. return nativeLayer.whenCalled('getPreview'); }) .then(function() { // Message should be gone. assertTrue(overlay.classList.contains('invisible')); assertFalse(messageEl.textContent!.includes(expectedMessage)); // Has active print button and successfully 'prints', indicating assertFalse(printButton.disabled); assertEquals(State.READY, page.state); printButton.click(); // This should result in a call to print. return nativeLayer.whenCalled('print'); }) .then( /** * @param {string} printTicket The print ticket print() was * called for. */ function(printTicket) { // Sanity check some printing argument values. const ticket = JSON.parse(printTicket); assertEquals( barDevice.printer!.deviceName, ticket.deviceName); assertEquals( getDefaultOrientation(barDevice) === 'LANDSCAPE', ticket.landscape); assertEquals(1, ticket.copies); const mediaDefault = getDefaultMediaSize(barDevice); assertEquals( mediaDefault.width_microns, ticket.mediaSize.width_microns); assertEquals( mediaDefault.height_microns, ticket.mediaSize.height_microns); return nativeLayer.whenCalled('dialogClose'); }); }); // Test that GCP invalid certificate printers disable the print preview when // selected and display an error and that the preview dialog can be // recovered by selecting a new destination. Verifies this works when the // invalid printer is the most recent destination and is selected by // default. test( assert(invalid_settings_browsertest.TestNames.InvalidCertificateError), function() { const invalidPrinter = createDestinationWithCertificateStatus( 'FooDevice', 'FooName', true); const validPrinter = createDestinationWithCertificateStatus( 'BarDevice', 'BarName', false); setupInvalidCertificateTest([invalidPrinter, validPrinter]); // Expected message const expectedMessageStart = 'The selected Google Cloud Print device ' + 'is no longer supported.'; const expectedMessageEnd = 'Try setting up the printer in your ' + 'computer\'s system settings.'; // Get references to relevant elements. const previewAreaEl = page.$.previewArea; const overlayEl = previewAreaEl.shadowRoot!.querySelector( '.preview-area-overlay-layer')!; const messageEl = previewAreaEl.shadowRoot!.querySelector('.preview-area-message')!; const sidebar = page.shadowRoot!.querySelector('print-preview-sidebar')!; let printButton: CrButtonElement; const destinationSettings = sidebar.shadowRoot!.querySelector( 'print-preview-destination-settings')!; const scalingSettings = sidebar.shadowRoot!.querySelector('print-preview-scaling-settings')! .shadowRoot!.querySelector( 'print-preview-number-settings-section')!; const layoutSettings = sidebar.shadowRoot!.querySelector('print-preview-layout-settings')!; return waitBeforeNextRender(page) .then(() => { const parentElement = sidebar.shadowRoot!.querySelector( 'print-preview-button-strip')!; printButton = parentElement.shadowRoot!.querySelector<CrButtonElement>( '.action-button')!; return Promise.all([ whenReady(), nativeLayer.whenCalled('getInitialSettings'), ]); }) .then(function() { // Set this to enable the scaling input. page.setSetting('scalingType', ScalingType.CUSTOM); destinationSettings.getDestinationStoreForTest() .startLoadCloudDestinations(); return eventToPromise( CloudPrintInterfaceEventType.PRINTER_DONE, cloudPrintInterface.getEventTarget()); }) .then(function() { // FooDevice will be selected since it is the most recently used // printer, so the invalid certificate error should be shown. // The overlay must be visible for the message to be seen. assertFalse(overlayEl.classList.contains('invisible')); // Verify that the correct message is shown. assertTrue(messageEl.textContent!.includes(expectedMessageStart)); assertTrue(messageEl.textContent!.includes(expectedMessageEnd)); // Verify that the print button is disabled assertTrue(printButton.disabled); // Verify the state is invalid and that some settings sections are // also disabled, so there is no way to regenerate the preview. assertEquals(State.ERROR, page.state); assertTrue( layoutSettings.shadowRoot!.querySelector('select')!.disabled); assertTrue(scalingSettings.shadowRoot!.querySelector( 'cr-input')!.disabled); // The destination select dropdown should be enabled, so that the // user can select a new printer. assertFalse(destinationSettings.$.destinationSelect.disabled); // Reset nativeLayer.reset(); // Select a new, valid cloud destination. destinationSettings.getDestinationStoreForTest() .selectDestination(validPrinter); return nativeLayer.whenCalled('getPreview'); }) .then(function() { // Has active print button, indicating recovery from error state. assertFalse(printButton.disabled); assertEquals(State.READY, page.state); // Settings sections are now active. assertFalse( layoutSettings.shadowRoot!.querySelector('select')!.disabled); assertFalse(scalingSettings.shadowRoot!.querySelector( 'cr-input')!.disabled); // The destination select dropdown should still be enabled. assertFalse(destinationSettings.$.destinationSelect.disabled); // Message text should have changed and overlay should be // invisible. assertFalse( messageEl.textContent!.includes(expectedMessageStart)); assertTrue(overlayEl.classList.contains('invisible')); }); }); // Test that GCP invalid certificate printers disable the print preview when // selected and display an error and that the preview dialog can be // recovered by selecting a new destination. Tests that even if destination // was previously selected, the error is cleared. test( assert(invalid_settings_browsertest.TestNames .InvalidCertificateErrorReselectDestination), function() { const invalidPrinter = createDestinationWithCertificateStatus( 'FooDevice', 'FooName', true); const validPrinter = createDestinationWithCertificateStatus( 'BarDevice', 'BarName', false); setupInvalidCertificateTest([validPrinter, invalidPrinter]); // Get references to relevant elements. const previewAreaEl = page.$.previewArea; const overlayEl = previewAreaEl.shadowRoot!.querySelector( '.preview-area-overlay-layer')!; const sidebar = page.shadowRoot!.querySelector('print-preview-sidebar')!; let printButton: CrButtonElement; const destinationSettings = sidebar.shadowRoot!.querySelector( 'print-preview-destination-settings')!; return waitBeforeNextRender(page) .then(() => { const parentElement = sidebar.shadowRoot!.querySelector( 'print-preview-button-strip')!; printButton = parentElement.shadowRoot!.querySelector<CrButtonElement>( '.action-button')!; return Promise.all([ whenReady(), nativeLayer.whenCalled('getInitialSettings'), ]); }) .then(function() { // Start loading cloud destinations so that the printer // capabilities arrive. destinationSettings.getDestinationStoreForTest() .startLoadCloudDestinations(); return nativeLayer.whenCalled('getPreview'); }) .then(function() { // Has active print button. assertFalse(printButton.disabled); assertEquals(State.READY, page.state); // No error message. assertTrue(overlayEl.classList.contains('invisible')); // Select the invalid destination and wait for the event. const whenInvalid = eventToPromise( DestinationStoreEventType.ERROR, destinationSettings.getDestinationStoreForTest()); destinationSettings.getDestinationStoreForTest() .selectDestination(invalidPrinter); return whenInvalid; }) .then(function() { // Should have error message. assertFalse(overlayEl.classList.contains('invisible')); assertEquals(State.ERROR, page.state); // Reset nativeLayer.reset(); // Reselect the valid cloud destination. const whenSelected = eventToPromise( DestinationStoreEventType.DESTINATION_SELECT, destinationSettings.getDestinationStoreForTest()); destinationSettings.getDestinationStoreForTest() .selectDestination(validPrinter); return whenSelected; }) .then(function() { // Has active print button and no error message. assertFalse(printButton.disabled); assertTrue(overlayEl.classList.contains('invisible')); }); }); });
the_stack
import type { Route as _envoy_config_route_v3_Route, Route__Output as _envoy_config_route_v3_Route__Output } from '../../../../envoy/config/route/v3/Route'; import type { VirtualCluster as _envoy_config_route_v3_VirtualCluster, VirtualCluster__Output as _envoy_config_route_v3_VirtualCluster__Output } from '../../../../envoy/config/route/v3/VirtualCluster'; import type { RateLimit as _envoy_config_route_v3_RateLimit, RateLimit__Output as _envoy_config_route_v3_RateLimit__Output } from '../../../../envoy/config/route/v3/RateLimit'; import type { HeaderValueOption as _envoy_config_core_v3_HeaderValueOption, HeaderValueOption__Output as _envoy_config_core_v3_HeaderValueOption__Output } from '../../../../envoy/config/core/v3/HeaderValueOption'; import type { CorsPolicy as _envoy_config_route_v3_CorsPolicy, CorsPolicy__Output as _envoy_config_route_v3_CorsPolicy__Output } from '../../../../envoy/config/route/v3/CorsPolicy'; import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../../google/protobuf/Any'; import type { RetryPolicy as _envoy_config_route_v3_RetryPolicy, RetryPolicy__Output as _envoy_config_route_v3_RetryPolicy__Output } from '../../../../envoy/config/route/v3/RetryPolicy'; import type { HedgePolicy as _envoy_config_route_v3_HedgePolicy, HedgePolicy__Output as _envoy_config_route_v3_HedgePolicy__Output } from '../../../../envoy/config/route/v3/HedgePolicy'; import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from '../../../../google/protobuf/UInt32Value'; // Original file: deps/envoy-api/envoy/config/route/v3/route_components.proto export enum _envoy_config_route_v3_VirtualHost_TlsRequirementType { /** * No TLS requirement for the virtual host. */ NONE = 0, /** * External requests must use TLS. If a request is external and it is not * using TLS, a 301 redirect will be sent telling the client to use HTTPS. */ EXTERNAL_ONLY = 1, /** * All requests must use TLS. If a request is not using TLS, a 301 redirect * will be sent telling the client to use HTTPS. */ ALL = 2, } /** * The top level element in the routing configuration is a virtual host. Each virtual host has * a logical name as well as a set of domains that get routed to it based on the incoming request's * host header. This allows a single listener to service multiple top level domain path trees. Once * a virtual host is selected based on the domain, the routes are processed in order to see which * upstream cluster to route to or whether to perform a redirect. * [#next-free-field: 21] */ export interface VirtualHost { /** * The logical name of the virtual host. This is used when emitting certain * statistics but is not relevant for routing. */ 'name'?: (string); /** * A list of domains (host/authority header) that will be matched to this * virtual host. Wildcard hosts are supported in the suffix or prefix form. * * Domain search order: * 1. Exact domain names: ``www.foo.com``. * 2. Suffix domain wildcards: ``*.foo.com`` or ``*-bar.foo.com``. * 3. Prefix domain wildcards: ``foo.*`` or ``foo-*``. * 4. Special wildcard ``*`` matching any domain. * * .. note:: * * The wildcard will not match the empty string. * e.g. ``*-bar.foo.com`` will match ``baz-bar.foo.com`` but not ``-bar.foo.com``. * The longest wildcards match first. * Only a single virtual host in the entire route configuration can match on ``*``. A domain * must be unique across all virtual hosts or the config will fail to load. * * Domains cannot contain control characters. This is validated by the well_known_regex HTTP_HEADER_VALUE. */ 'domains'?: (string)[]; /** * The list of routes that will be matched, in order, for incoming requests. * The first route that matches will be used. */ 'routes'?: (_envoy_config_route_v3_Route)[]; /** * Specifies the type of TLS enforcement the virtual host expects. If this option is not * specified, there is no TLS requirement for the virtual host. */ 'require_tls'?: (_envoy_config_route_v3_VirtualHost_TlsRequirementType | keyof typeof _envoy_config_route_v3_VirtualHost_TlsRequirementType); /** * A list of virtual clusters defined for this virtual host. Virtual clusters * are used for additional statistics gathering. */ 'virtual_clusters'?: (_envoy_config_route_v3_VirtualCluster)[]; /** * Specifies a set of rate limit configurations that will be applied to the * virtual host. */ 'rate_limits'?: (_envoy_config_route_v3_RateLimit)[]; /** * Specifies a list of HTTP headers that should be added to each request * handled by this virtual host. Headers specified at this level are applied * after headers from enclosed :ref:`envoy_api_msg_config.route.v3.Route` and before headers from the * enclosing :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including * details on header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[]; /** * Indicates that the virtual host has a CORS policy. */ 'cors'?: (_envoy_config_route_v3_CorsPolicy | null); /** * Specifies a list of HTTP headers that should be added to each response * handled by this virtual host. Headers specified at this level are applied * after headers from enclosed :ref:`envoy_api_msg_config.route.v3.Route` and before headers from the * enclosing :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including * details on header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'response_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[]; /** * Specifies a list of HTTP headers that should be removed from each response * handled by this virtual host. */ 'response_headers_to_remove'?: (string)[]; /** * Specifies a list of HTTP headers that should be removed from each request * handled by this virtual host. */ 'request_headers_to_remove'?: (string)[]; /** * Decides whether the :ref:`x-envoy-attempt-count * <config_http_filters_router_x-envoy-attempt-count>` header should be included * in the upstream request. Setting this option will cause it to override any existing header * value, so in the case of two Envoys on the request path with this option enabled, the upstream * will see the attempt count as perceived by the second Envoy. Defaults to false. * This header is unaffected by the * :ref:`suppress_envoy_headers * <envoy_api_field_extensions.filters.http.router.v3.Router.suppress_envoy_headers>` flag. * * [#next-major-version: rename to include_attempt_count_in_request.] */ 'include_request_attempt_count'?: (boolean); /** * The per_filter_config field can be used to provide virtual host-specific * configurations for filters. The key should match the filter name, such as * *envoy.filters.http.buffer* for the HTTP buffer filter. Use of this field is filter * specific; see the :ref:`HTTP filter documentation <config_http_filters>` * for if and how it is utilized. * [#comment: An entry's value may be wrapped in a * :ref:`FilterConfig<envoy_api_msg_config.route.v3.FilterConfig>` * message to specify additional options.] */ 'typed_per_filter_config'?: ({[key: string]: _google_protobuf_Any}); /** * Indicates the retry policy for all routes in this virtual host. Note that setting a * route level entry will take precedence over this config and it'll be treated * independently (e.g.: values are not inherited). */ 'retry_policy'?: (_envoy_config_route_v3_RetryPolicy | null); /** * Indicates the hedge policy for all routes in this virtual host. Note that setting a * route level entry will take precedence over this config and it'll be treated * independently (e.g.: values are not inherited). */ 'hedge_policy'?: (_envoy_config_route_v3_HedgePolicy | null); /** * The maximum bytes which will be buffered for retries and shadowing. * If set and a route-specific limit is not set, the bytes actually buffered will be the minimum * value of this and the listener per_connection_buffer_limit_bytes. */ 'per_request_buffer_limit_bytes'?: (_google_protobuf_UInt32Value | null); /** * Decides whether the :ref:`x-envoy-attempt-count * <config_http_filters_router_x-envoy-attempt-count>` header should be included * in the downstream response. Setting this option will cause the router to override any existing header * value, so in the case of two Envoys on the request path with this option enabled, the downstream * will see the attempt count as perceived by the Envoy closest upstream from itself. Defaults to false. * This header is unaffected by the * :ref:`suppress_envoy_headers * <envoy_api_field_extensions.filters.http.router.v3.Router.suppress_envoy_headers>` flag. */ 'include_attempt_count_in_response'?: (boolean); /** * [#not-implemented-hide:] * Specifies the configuration for retry policy extension. Note that setting a route level entry * will take precedence over this config and it'll be treated independently (e.g.: values are not * inherited). :ref:`Retry policy <envoy_api_field_config.route.v3.VirtualHost.retry_policy>` should not be * set if this field is used. */ 'retry_policy_typed_config'?: (_google_protobuf_Any | null); } /** * The top level element in the routing configuration is a virtual host. Each virtual host has * a logical name as well as a set of domains that get routed to it based on the incoming request's * host header. This allows a single listener to service multiple top level domain path trees. Once * a virtual host is selected based on the domain, the routes are processed in order to see which * upstream cluster to route to or whether to perform a redirect. * [#next-free-field: 21] */ export interface VirtualHost__Output { /** * The logical name of the virtual host. This is used when emitting certain * statistics but is not relevant for routing. */ 'name': (string); /** * A list of domains (host/authority header) that will be matched to this * virtual host. Wildcard hosts are supported in the suffix or prefix form. * * Domain search order: * 1. Exact domain names: ``www.foo.com``. * 2. Suffix domain wildcards: ``*.foo.com`` or ``*-bar.foo.com``. * 3. Prefix domain wildcards: ``foo.*`` or ``foo-*``. * 4. Special wildcard ``*`` matching any domain. * * .. note:: * * The wildcard will not match the empty string. * e.g. ``*-bar.foo.com`` will match ``baz-bar.foo.com`` but not ``-bar.foo.com``. * The longest wildcards match first. * Only a single virtual host in the entire route configuration can match on ``*``. A domain * must be unique across all virtual hosts or the config will fail to load. * * Domains cannot contain control characters. This is validated by the well_known_regex HTTP_HEADER_VALUE. */ 'domains': (string)[]; /** * The list of routes that will be matched, in order, for incoming requests. * The first route that matches will be used. */ 'routes': (_envoy_config_route_v3_Route__Output)[]; /** * Specifies the type of TLS enforcement the virtual host expects. If this option is not * specified, there is no TLS requirement for the virtual host. */ 'require_tls': (keyof typeof _envoy_config_route_v3_VirtualHost_TlsRequirementType); /** * A list of virtual clusters defined for this virtual host. Virtual clusters * are used for additional statistics gathering. */ 'virtual_clusters': (_envoy_config_route_v3_VirtualCluster__Output)[]; /** * Specifies a set of rate limit configurations that will be applied to the * virtual host. */ 'rate_limits': (_envoy_config_route_v3_RateLimit__Output)[]; /** * Specifies a list of HTTP headers that should be added to each request * handled by this virtual host. Headers specified at this level are applied * after headers from enclosed :ref:`envoy_api_msg_config.route.v3.Route` and before headers from the * enclosing :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including * details on header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[]; /** * Indicates that the virtual host has a CORS policy. */ 'cors': (_envoy_config_route_v3_CorsPolicy__Output | null); /** * Specifies a list of HTTP headers that should be added to each response * handled by this virtual host. Headers specified at this level are applied * after headers from enclosed :ref:`envoy_api_msg_config.route.v3.Route` and before headers from the * enclosing :ref:`envoy_api_msg_config.route.v3.RouteConfiguration`. For more information, including * details on header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'response_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[]; /** * Specifies a list of HTTP headers that should be removed from each response * handled by this virtual host. */ 'response_headers_to_remove': (string)[]; /** * Specifies a list of HTTP headers that should be removed from each request * handled by this virtual host. */ 'request_headers_to_remove': (string)[]; /** * Decides whether the :ref:`x-envoy-attempt-count * <config_http_filters_router_x-envoy-attempt-count>` header should be included * in the upstream request. Setting this option will cause it to override any existing header * value, so in the case of two Envoys on the request path with this option enabled, the upstream * will see the attempt count as perceived by the second Envoy. Defaults to false. * This header is unaffected by the * :ref:`suppress_envoy_headers * <envoy_api_field_extensions.filters.http.router.v3.Router.suppress_envoy_headers>` flag. * * [#next-major-version: rename to include_attempt_count_in_request.] */ 'include_request_attempt_count': (boolean); /** * The per_filter_config field can be used to provide virtual host-specific * configurations for filters. The key should match the filter name, such as * *envoy.filters.http.buffer* for the HTTP buffer filter. Use of this field is filter * specific; see the :ref:`HTTP filter documentation <config_http_filters>` * for if and how it is utilized. * [#comment: An entry's value may be wrapped in a * :ref:`FilterConfig<envoy_api_msg_config.route.v3.FilterConfig>` * message to specify additional options.] */ 'typed_per_filter_config': ({[key: string]: _google_protobuf_Any__Output}); /** * Indicates the retry policy for all routes in this virtual host. Note that setting a * route level entry will take precedence over this config and it'll be treated * independently (e.g.: values are not inherited). */ 'retry_policy': (_envoy_config_route_v3_RetryPolicy__Output | null); /** * Indicates the hedge policy for all routes in this virtual host. Note that setting a * route level entry will take precedence over this config and it'll be treated * independently (e.g.: values are not inherited). */ 'hedge_policy': (_envoy_config_route_v3_HedgePolicy__Output | null); /** * The maximum bytes which will be buffered for retries and shadowing. * If set and a route-specific limit is not set, the bytes actually buffered will be the minimum * value of this and the listener per_connection_buffer_limit_bytes. */ 'per_request_buffer_limit_bytes': (_google_protobuf_UInt32Value__Output | null); /** * Decides whether the :ref:`x-envoy-attempt-count * <config_http_filters_router_x-envoy-attempt-count>` header should be included * in the downstream response. Setting this option will cause the router to override any existing header * value, so in the case of two Envoys on the request path with this option enabled, the downstream * will see the attempt count as perceived by the Envoy closest upstream from itself. Defaults to false. * This header is unaffected by the * :ref:`suppress_envoy_headers * <envoy_api_field_extensions.filters.http.router.v3.Router.suppress_envoy_headers>` flag. */ 'include_attempt_count_in_response': (boolean); /** * [#not-implemented-hide:] * Specifies the configuration for retry policy extension. Note that setting a route level entry * will take precedence over this config and it'll be treated independently (e.g.: values are not * inherited). :ref:`Retry policy <envoy_api_field_config.route.v3.VirtualHost.retry_policy>` should not be * set if this field is used. */ 'retry_policy_typed_config': (_google_protobuf_Any__Output | null); }
the_stack
import { pmBuild } from 'jest-prosemirror'; import { extensionValidityTest, renderEditor } from 'jest-remirror'; import { createCoreManager, ItalicExtension, MentionChangeHandler, MentionExtension, MentionOptions, } from 'remirror/extensions'; import { hideConsoleError } from 'testing'; import { htmlToProsemirrorNode, prosemirrorNodeToHtml } from '@remirror/core'; extensionValidityTest(MentionExtension, { matchers: [] }); describe('schema', () => { const { schema } = createCoreManager([ new MentionExtension({ matchers: [{ char: '@', name: 'at' }] }), ]); const attributes = { id: 'test', label: '@test', name: 'testing' }; const { mention, p, doc } = pmBuild(schema, { mention: { markType: 'mention', ...attributes }, }); it('creates the correct dom node', () => { expect(prosemirrorNodeToHtml(p(mention(attributes.label)))).toMatchInlineSnapshot(` <p> <a class="mention mention-testing" data-mention-id="test" data-mention-name="testing" > @test </a> </p> `); }); it('parses the dom structure and finds itself', () => { const node = htmlToProsemirrorNode({ schema, content: `<a class="mention mention-at" data-mention-id="${attributes.id}" data-mention-name="${attributes.name}">${attributes.label}</a>`, }); const expected = doc(p(mention(attributes.label))); expect(node).toEqualProsemirrorNode(expected); }); describe('extraAttributes', () => { const custom = 'test'; const { schema } = createCoreManager([ new MentionExtension({ matchers: [], extraAttributes: { 'data-custom': { default: null } }, }), ]); const { doc, p, mention } = pmBuild(schema, { mention: { markType: 'mention', ['data-custom']: custom, ...attributes }, }); it('parses the dom structure and finds itself with custom attributes', () => { const node = htmlToProsemirrorNode({ schema, content: `<a class="mention mention-at" data-custom="${custom}" data-mention-id="${attributes.id}" data-mention-name="${attributes.name}">${attributes.label}</a>`, }); const expected = doc(p(mention(attributes.label))); expect(node).toEqualProsemirrorNode(expected); }); }); }); /** * Create the mention extension with an optional `onChange` handler. */ function create(options: MentionOptions) { const extension = new MentionExtension({ ...options }); const editor = renderEditor([extension, new ItalicExtension()]); const { add, view, manager, commands } = editor; const { doc, p } = editor.nodes; const { mention } = editor.attributeMarks; return { add, doc, p, mention, view, manager, commands, editor, extension }; } describe('`createSuggesters`', () => { const options: MentionOptions = { matchers: [ { char: '#', name: 'tag', mentionClassName: 'custom' }, { char: '@', name: 'at', mentionClassName: 'custom' }, { char: '+', name: 'plus', mentionClassName: 'custom' }, ], }; const id = 'mention'; const label = `@${id}`; it('uses default noop callbacks and does nothing', () => { const noop = jest.fn(); const { add, doc, p, extension } = create(options); extension.addHandler('onChange', noop); add(doc(p('<cursor>'))) .insertText(`This ${label} `) .callback(({ state }) => { expect(state).toContainRemirrorDocument(p(`This ${label} `)); expect(noop).toHaveBeenCalledTimes(8); }); }); const change = jest.fn(); // The default `onChange` handler. Make sure to include this in future work. const onChange: MentionChangeHandler = jest.fn((props, command) => { if (props.exitReason) { command(); } if (props.changeReason) { change(); } }); const { add, doc, p, mention, view, editor, extension } = create(options); extension.addHandler('onChange', onChange); const mentionMark = mention({ id, label, name: 'at' }); it('should support exits', () => { add(doc(p('<cursor>'))).insertText(`${label} `); expect(view.state).toContainRemirrorDocument(p(mentionMark(label), ' ')); }); it('should handle joined text separated by space', () => { add(doc(p('hello <cursor>friend'))).insertText(`${label} `); expect(view.state).toContainRemirrorDocument(p('hello ', mentionMark(label), ' friend')); }); it('can split mentions', () => { const splitMention = mention({ id: '123', label: '@123', name: 'at' }); add(doc(p(splitMention('@1<cursor>23')))); editor.insertText(' '); expect(view.state).toContainRemirrorDocument( p(mention({ id: '1', label: '@1', name: 'at' })('@1'), ' 23'), ); }); it('removes invalid mentions', () => { const splitMention = mention({ id: '123', label: '@123', name: 'at' }); add(doc(p(splitMention('@<cursor>123')))).insertText(' '); expect(view.state).toContainRemirrorDocument(p('@ 123')); }); it('decorates split mentions', () => { add(doc(p('hello <cursor>friend'))).insertText(`${label}`); expect(view.dom.innerHTML).toMatchInlineSnapshot(` <p> hello <a class="suggest suggest-at"> @mentionfriend </a> </p> `); }); it('injects the mention at the correct place', () => { add(doc(p('<cursor>'))).insertText(`This ${label} `); expect(view.state).toContainRemirrorDocument(p('This ', mentionMark(label), ' ')); expect(change).toHaveBeenCalledTimes(id.length); }); it('supports deleting content', () => { add(doc(p('<cursor>'))) .insertText(`@1`) .dispatchCommand(({ state, dispatch }) => { if (dispatch) { dispatch(state.tr.delete(1, state.selection.head)); } return true; }) .callback(({ doc }) => { expect(doc).toMatchSnapshot(); }); }); it('supports multiple characters', () => { const labelFn = (char: string) => `${char}${id}`; const hashMark = mention({ id, label: labelFn('#'), name: 'tag' }); const plusMark = mention({ id, label: labelFn('+'), name: 'plus' }); const atMark = mention({ id, label: labelFn('@'), name: 'at' }); add(doc(p('<cursor>'))).insertText(`This ${labelFn('#')} `); expect(view.state).toContainRemirrorDocument(p('This ', hashMark(labelFn('#')), ' ')); add(doc(p('<cursor>'))).insertText(`This ${labelFn('+')} `); expect(view.state).toContainRemirrorDocument(p('This ', plusMark(labelFn('+')), ' ')); add(doc(p('<cursor>'))).insertText(`This ${labelFn('@')} `); expect(view.state).toContainRemirrorDocument(p('This ', atMark(labelFn('@')), ' ')); }); }); describe('pasteRules', () => { const options = { matchers: [ { char: '#', name: 'tag' }, { char: '@', name: 'at' }, { char: '+', name: 'plus' }, ], }; const { add, doc, p, mention } = create(options); it('supports pasted content', () => { add(doc(p('<cursor>'))) .paste(p('This is text @hello')) .callback(({ state }) => { const expectedMention = mention({ id: '@hello', name: 'at', label: '@hello' })('@hello'); const expected = p('This is text ', expectedMention); expect(state).toContainRemirrorDocument(expected); }); }); it('supports pasting multiple matchers', () => { const at = mention({ id: '@hello', name: 'at', label: '@hello' })('@hello'); const plus = mention({ id: '+awesome', name: 'plus', label: '+awesome' })('+awesome'); const tag = mention({ id: '#12', name: 'tag', label: '#12' })('#12'); add(doc(p('<cursor>'))) .paste(p('#12 +awesome @hello')) .callback((content) => { expect(content.state).toContainRemirrorDocument(p(tag, ' ', plus, ' ', at)); }); }); }); describe('commands', () => { const options = { matchers: [ { char: '#', name: 'tag' }, { char: '@', name: 'at' }, { char: '+', name: 'plus' }, ], }; const { add, doc, p, mention, view, commands } = create(options); const attributes = { id: 'test', label: '@test', name: 'at', appendText: '' }; describe('createMention', () => { hideConsoleError(true); it('replaces text at the current position by default', () => { add(doc(p('This is ', '<cursor>'))); commands.createMention(attributes); expect(view.state).toContainRemirrorDocument( p('This is ', mention(attributes)(attributes.label)), ); }); it('replaces text at the specified position', () => { add(doc(p('This is ', '<cursor>'))); commands.createMention({ ...attributes, range: { from: 1, to: 1, cursor: 1 } }); expect(view.state).toContainRemirrorDocument( p(mention(attributes)(attributes.label), 'This is '), ); }); it('throws when invalid config passed into the command', () => { add(doc(p('This is ', '<cursor>'))); // @ts-expect-error expect(() => commands.createMention()).toThrowErrorMatchingSnapshot(); // @ts-expect-error expect(() => commands.createMention({})).toThrowErrorMatchingSnapshot(); expect(() => commands.createMention({ ...attributes, id: '' }), ).toThrowErrorMatchingSnapshot(); expect(() => commands.createMention({ ...attributes, label: '' }), ).toThrowErrorMatchingSnapshot(); expect(() => commands.createMention({ ...attributes, name: 'invalid' }), ).toThrowErrorMatchingSnapshot(); expect(() => // @ts-expect-error commands.createMention({ ...attributes, name: undefined }), ).toThrowErrorMatchingSnapshot(); }); }); }); describe('interactions with input rules', () => { const options: MentionOptions = { matchers: [{ char: '@', name: 'at', mentionClassName: 'custom' }], }; const { add, doc, p, mention, view } = create(options); it('should skip input rules when mention active', () => { const mentionMark = mention({ id: 'mention', label: '@mention', name: 'at' }); const { state } = add(doc(p('123 ', mentionMark('@men_tion<cursor>')))).insertText('_ '); expect(state.doc).toEqualRemirrorDocument(doc(p('123 ', mentionMark('@men_tion'), '_ '))); }); it('should skip input rules when mention suggestion active', () => { add(doc(p('123 '))).insertText('@a_bc_ '); expect(view.dom.innerHTML).toMatchInlineSnapshot(` <p> 123 <a class="suggest suggest-at"> @a_bc_ </a> </p> `); }); it('should skip input for overlapping sections', () => { add(doc(p('_123 '))).insertText('@abc_ '); expect(view.dom.innerHTML).toMatchInlineSnapshot(` <p> _123 <a class="suggest suggest-at"> @abc_ </a> </p> `); }); it('should support longer matches', () => { add(doc(p('123 '))).insertText('@a_bc_ this should be preserved'); expect(view.dom.innerHTML).toMatchInlineSnapshot(` <p> 123 @a_bc_ this should be preserved </p> `); }); }); describe('forwardDeletes', () => { const options: MentionOptions = { matchers: [{ char: '@', name: 'at', mentionClassName: 'custom' }], }; const { add, doc, p, mention, view } = create(options); it('should support deleting forward', () => { const mentionMark = mention({ id: 'mention', label: '@mention', name: 'at' }); add(doc(p('abc <cursor>', mentionMark('@mention')))).forwardDelete(); expect(view.state.doc).toEqualRemirrorDocument(doc(p('abc mention'))); }); }); describe('onClick', () => { const options = { matchers: [ { char: '#', name: 'tag' }, { char: '@', name: 'at' }, { char: '+', name: 'plus' }, ], }; const { add, doc, p, mention, view, extension } = create(options); it('responds to clicks', () => { const clickHandler = jest.fn(() => true); extension.addHandler('onClick', clickHandler); const atMention = mention({ id: '@hello', name: 'at', label: '@hello' })('@hello'); const node = p('first ', atMention); add(doc(node)); view.someProp('handleClickOn', (fn) => fn(view, 10, node, 1, {}, false)); expect(clickHandler).toHaveBeenCalledTimes(1); expect(clickHandler).toHaveBeenCalledWith( {}, expect.objectContaining({ from: 7, to: 13, text: '@hello', mark: expect.any(Object), }), ); view.someProp('handleClick', (fn) => fn(view, 3, node, 1, {}, true)); expect(clickHandler).toHaveBeenCalledTimes(1); }); });
the_stack
import { Component, OnDestroy, OnInit, Input, ViewChild, ElementRef } from '@angular/core'; import { ActionSheetButton, IonRefresher } from '@ionic/angular'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreCourseCustomField, CoreCourseEnrolmentMethod, CoreCourses, CoreCourseSearchedData, CoreCoursesProvider, CoreEnrolledCourseData, } from '@features/courses/services/courses'; import { CoreCourseOptionsDelegate, CoreCourseOptionsMenuHandlerToDisplay, } from '@features/course/services/course-options-delegate'; import { CoreCourseHelper } from '@features/course/services/course-helper'; import { ActionSheetController, ModalController, NgZone, Platform, Translate } from '@singletons'; import { CoreCoursesSelfEnrolPasswordComponent } from '../../../courses/components/self-enrol-password/self-enrol-password'; import { CoreNavigator } from '@services/navigator'; import { CoreUtils } from '@services/utils/utils'; import { CoreCoursesHelper, CoreCourseWithImageAndColor } from '@features/courses/services/courses-helper'; import { Subscription } from 'rxjs'; import { CoreColors } from '@singletons/colors'; import { CoreText } from '@singletons/text'; import { CorePromisedValue } from '@classes/promised-value'; const ENROL_BROWSER_METHODS = ['fee', 'paypal']; /** * Page that shows the summary of a course including buttons to enrol and other available options. */ @Component({ selector: 'page-core-course-summary', templateUrl: 'course-summary.html', styleUrls: ['course-summary.scss'], }) export class CoreCourseSummaryPage implements OnInit, OnDestroy { @Input() course?: CoreCourseSummaryData; @Input() courseId = 0; @ViewChild('courseThumb') courseThumb?: ElementRef; isEnrolled = false; canAccessCourse = true; selfEnrolInstances: CoreCourseEnrolmentMethod[] = []; otherEnrolments = false; dataLoaded = false; isModal = false; contactsExpanded = false; courseUrl = ''; progress?: number; protected actionSheet?: HTMLIonActionSheetElement; courseMenuHandlers: CoreCourseOptionsMenuHandlerToDisplay[] = []; protected useGuestAccess = false; protected guestInstanceId = new CorePromisedValue<number | undefined>(); protected courseData = new CorePromisedValue<CoreCourseSummaryData | undefined>(); protected waitStart = 0; protected enrolUrl = ''; protected pageDestroyed = false; protected courseStatusObserver?: CoreEventObserver; protected appResumeSubscription: Subscription; protected waitingForBrowserEnrol = false; constructor() { // Refresh the view when the app is resumed. this.appResumeSubscription = Platform.resume.subscribe(() => { if (!this.waitingForBrowserEnrol || !this.dataLoaded) { return; } NgZone.run(async () => { this.waitingForBrowserEnrol = false; this.dataLoaded = false; await this.refreshData(); }); }); } /** * @inheritdoc */ async ngOnInit(): Promise<void> { if (!this.courseId) { // Opened as a page. try { this.courseId = CoreNavigator.getRequiredRouteNumberParam('courseId'); } catch (error) { CoreDomUtils.showErrorModal(error); CoreNavigator.back(); this.closeModal(); // Just in case. return; } this.course = CoreNavigator.getRouteParam('course'); } else { // Opened as a modal. this.isModal = true; } const currentSiteUrl = CoreSites.getRequiredCurrentSite().getURL(); this.enrolUrl = CoreText.concatenatePaths(currentSiteUrl, 'enrol/index.php?id=' + this.courseId); this.courseUrl = CoreText.concatenatePaths(currentSiteUrl, 'course/view.php?id=' + this.courseId); await this.getCourse(); } /** * Check if the user can access as guest. * * @return Promise resolved if can access as guest, rejected otherwise. Resolve param indicates if * password is required for guest access. */ protected async canAccessAsGuest(): Promise<boolean> { const guestInstanceId = await this.guestInstanceId; if (guestInstanceId === undefined) { return false; } const info = await CoreCourses.getCourseGuestEnrolmentInfo(guestInstanceId); // Guest access with password is not supported by the app. return !!info.status && !info.passwordrequired; } /** * Convenience function to get course. We use this to determine if a user can see the course or not. * * @param refresh If it's refreshing content. */ protected async getCourse(refresh = false): Promise<void> { this.otherEnrolments = false; try { await Promise.all([ this.getEnrolmentMethods(), this.getCourseData(), this.loadCourseExtraData(), ]); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error getting enrolment data'); } await this.setCourseColor(); if (!this.course || !('progress' in this.course) || typeof this.course.progress !== 'number' || this.course.progress < 0 || this.course.completionusertracked === false ) { this.progress = undefined; } else { this.progress = this.course.progress; } await this.loadMenuHandlers(refresh); this.dataLoaded = true; } /** * Get course enrolment methods. */ protected async getEnrolmentMethods(): Promise<void> { this.selfEnrolInstances = []; this.guestInstanceId.reset(); const enrolmentMethods = await CoreCourses.getCourseEnrolmentMethods(this.courseId); enrolmentMethods.forEach((method) => { if (!method.status) { return; } if (method.type === 'self') { this.selfEnrolInstances.push(method); } else if (method.type === 'guest') { this.guestInstanceId.resolve(method.id); } else { // Other enrolments that comes from that WS should need user action. this.otherEnrolments = true; } }); if (!this.guestInstanceId.isSettled()) { // No guest instance found. this.guestInstanceId.resolve(undefined); } } /** * Get course data. */ protected async getCourseData(): Promise<void> { try { // Check if user is enrolled in the course. try { this.course = await CoreCourses.getUserCourse(this.courseId); this.isEnrolled = true; } catch { // The user is not enrolled in the course. Use getCourses to see if it's an admin/manager and can see the course. this.isEnrolled = false; this.course = await CoreCourses.getCourse(this.courseId); } // Success retrieving the course, we can assume the user has permissions to view it. this.canAccessCourse = true; this.useGuestAccess = false; } catch { // The user is not an admin/manager. Check if we can provide guest access to the course. this.canAccessCourse = await this.canAccessAsGuest(); this.useGuestAccess = this.canAccessCourse; } this.courseData.resolve(this.course); } /** * Load some extra data for the course. */ protected async loadCourseExtraData(): Promise<void> { try { const courseByField = await CoreCourses.getCourseByField('id', this.courseId); const courseData = await this.courseData; if (courseData) { courseData.customfields = courseByField.customfields; courseData.contacts = courseByField.contacts; courseData.displayname = courseByField.displayname; courseData.categoryname = courseByField.categoryname; courseData.overviewfiles = courseByField.overviewfiles; } else { this.course = courseByField; this.courseData.resolve(courseByField); } // enrollmentmethods contains ALL enrolment methods including manual. if (!this.isEnrolled && courseByField.enrollmentmethods?.some((method) => ENROL_BROWSER_METHODS.includes(method))) { this.otherEnrolments = true; } } catch { // Ignore errors. } } /** * Load the course menu handlers. * * @param refresh If it's refreshing content. * @return Promise resolved when done. */ protected async loadMenuHandlers(refresh?: boolean): Promise<void> { if (!this.course) { return; } this.courseMenuHandlers = await CoreCourseOptionsDelegate.getMenuHandlersToDisplay(this.course, refresh, this.useGuestAccess); } /** * Open the course. * * @param replaceCurrentPage If current place should be replaced in the navigation stack. */ openCourse(replaceCurrentPage = false): void { if (!this.canAccessCourse || !this.course || this.isModal) { return; } CoreCourseHelper.openCourse(this.course, { params: { isGuest: this.useGuestAccess }, replace: replaceCurrentPage }); } /** * Enrol in browser. */ async browserEnrol(): Promise<void> { // Send user to browser to enrol. Warn the user first. try { await CoreDomUtils.showConfirm( Translate.instant('core.courses.browserenrolinstructions'), Translate.instant('core.courses.completeenrolmentbrowser'), Translate.instant('core.openinbrowser'), ); } catch { // User canceled. return; } this.waitingForBrowserEnrol = true; await CoreSites.getRequiredCurrentSite().openInBrowserWithAutoLogin( this.enrolUrl, undefined, { showBrowserWarning: false, }, ); } /** * Confirm user to Self enrol in course. * * @param enrolMethod The enrolment method. */ async selfEnrolConfirm(enrolMethod: CoreCourseEnrolmentMethod): Promise<void> { try { await CoreDomUtils.showConfirm(Translate.instant('core.courses.confirmselfenrol'), enrolMethod.name); this.selfEnrolInCourse(enrolMethod.id); } catch { // User cancelled. } } /** * Self enrol in a course. * * @param instanceId The instance ID. * @param password Password to use. * @return Promise resolved when self enrolled. */ async selfEnrolInCourse(instanceId: number, password = ''): Promise<void> { const modal = await CoreDomUtils.showModalLoading('core.loading', true); try { await CoreCourses.selfEnrol(this.courseId, password, instanceId); // Close modal and refresh data. this.isEnrolled = true; this.dataLoaded = false; // Sometimes the list of enrolled courses takes a while to be updated. Wait for it. await this.waitForEnrolled(true); await this.refreshData().finally(() => { // My courses have been updated, trigger event. CoreEvents.trigger(CoreCoursesProvider.EVENT_MY_COURSES_UPDATED, { courseId: this.courseId, course: this.course, action: CoreCoursesProvider.ACTION_ENROL, }, CoreSites.getCurrentSiteId()); }); this.openCourse(true); modal?.dismiss(); } catch (error) { modal?.dismiss(); if (error && error.errorcode === CoreCoursesProvider.ENROL_INVALID_KEY) { // Initialize the self enrol modal. // Invalid password, show the modal to enter the password. const modalData = await CoreDomUtils.openModal<string>( { component: CoreCoursesSelfEnrolPasswordComponent, componentProps: { password }, }, ); if (modalData !== undefined) { this.selfEnrolInCourse(instanceId, modalData); return; } if (!password) { // No password entered, don't show error. return; } } CoreDomUtils.showErrorModalDefault(error, 'core.courses.errorselfenrol', true); } } /** * Refresh the data. * * @param refresher The refresher if this was triggered by a Pull To Refresh. */ async refreshData(refresher?: IonRefresher): Promise<void> { const promises: Promise<void>[] = []; promises.push(CoreCourses.invalidateUserCourses()); promises.push(CoreCourses.invalidateCourse(this.courseId)); promises.push(CoreCourses.invalidateCourseEnrolmentMethods(this.courseId)); promises.push(CoreCourseOptionsDelegate.clearAndInvalidateCoursesOptions(this.courseId)); promises.push(CoreCourses.invalidateCoursesByField('id', this.courseId)); if (this.guestInstanceId.value) { promises.push(CoreCourses.invalidateCourseGuestEnrolmentInfo(this.guestInstanceId.value)); } await Promise.all(promises).finally(() => this.getCourse()).finally(() => { refresher?.complete(); }); } /** * Wait for the user to be enrolled in the course. * * @param first If it's the first call (true) or it's a recursive call (false). * @return Promise resolved when enrolled or timeout. */ protected async waitForEnrolled(first?: boolean): Promise<void> { if (first) { this.waitStart = Date.now(); } // Check if user is enrolled in the course. await CoreUtils.ignoreErrors(CoreCourses.invalidateUserCourses()); try { await CoreCourses.getUserCourse(this.courseId); } catch { // Not enrolled, wait a bit and try again. if (this.pageDestroyed || (Date.now() - this.waitStart > 60000)) { // Max time reached or the user left the view, stop. return; } return new Promise((resolve): void => { setTimeout(async () => { if (!this.pageDestroyed) { // Wait again. await this.waitForEnrolled(); } resolve(); }, 5000); }); } } /** * Opens a menu item registered to the delegate. * * @param item Item to open */ openMenuItem(item: CoreCourseOptionsMenuHandlerToDisplay): void { const params = Object.assign({ course: this.course }, item.data.pageParams); CoreNavigator.navigateToSitePath(item.data.page, { params }); } /** * Set course color. */ protected async setCourseColor(): Promise<void> { if (!this.course) { return; } await CoreCoursesHelper.loadCourseColorAndImage(this.course); if (!this.courseThumb) { return; } if (this.course.color) { this.courseThumb.nativeElement.style.setProperty('--course-color', this.course.color); const tint = CoreColors.lighter(this.course.color, 50); this.courseThumb.nativeElement.style.setProperty('--course-color-tint', tint); } else if(this.course.colorNumber !== undefined) { this.courseThumb.nativeElement.classList.add('course-color-' + this.course.colorNumber); } } /** * Open enrol action sheet. */ async enrolMe(): Promise<void> { if (this.selfEnrolInstances.length == 1 && !this.otherEnrolments) { this.selfEnrolConfirm(this.selfEnrolInstances[0]); return; } if (this.selfEnrolInstances.length == 0 && this.otherEnrolments) { this.browserEnrol(); return; } const buttons: ActionSheetButton[] = this.selfEnrolInstances.map((enrolMethod) => ({ text: enrolMethod.name, handler: (): void => { this.selfEnrolConfirm(enrolMethod); }, })); if (this.otherEnrolments) { buttons.push({ text: Translate.instant('core.courses.completeenrolmentbrowser'), handler: (): void => { this.browserEnrol(); }, }); } buttons.push({ text: Translate.instant('core.cancel'), role: 'cancel', }); this.actionSheet = await ActionSheetController.create({ header: Translate.instant('core.courses.enrolme'), buttons: buttons, }); await this.actionSheet.present(); } /** * Toggle list of contacts. */ toggleContacts(): void { this.contactsExpanded = !this.contactsExpanded; } /** * Close the modal. */ closeModal(): void { ModalController.dismiss(); } /** * @inheritdoc */ ngOnDestroy(): void { this.pageDestroyed = true; this.courseStatusObserver?.off(); this.appResumeSubscription.unsubscribe(); } } type CoreCourseSummaryData = CoreCourseWithImageAndColor & (CoreEnrolledCourseData | CoreCourseSearchedData) & { contacts?: { // Contact users. id: number; // Contact user id. fullname: string; // Contact user fullname. }[]; customfields?: CoreCourseCustomField[]; // Custom fields and associated values. categoryname?: string; // Category name. };
the_stack
import { Component, ViewEncapsulation } from '@angular/core'; import { ViewContainerRef } from '@angular/core'; import { OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { MdSnackBar } from '@angular/material'; import { MdSnackBarRef } from '@angular/material'; import { SimpleSnackBar } from '@angular/material'; import { MdDialogRef, MdDialog } from '@angular/material'; import { Router } from '@angular/router'; import { SlimLoadingBarService } from 'ng2-slim-loading-bar'; import { Subscription } from 'rxjs/Subscription'; import { AppState, Action } from './app.service'; import { ExaminationService } from './api/api/examination.service'; import { AttendanceService } from './api/api/attendance.service'; import { AppointmentService } from './api/api/appointment.service'; import { PatientService } from './api/api/patient.service'; import { RoomService } from './api/api/room.service'; import { CantyCTIService, IncomingCallState } from './cantyCti.service'; import { InsertTestExaminationsDialogComponent } from './insert-test-examinations.dialog'; /* * App Component * Top Level Component */ @Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.scss' ], templateUrl: './app.component.html' }) export class AppComponent implements OnInit { public url = 'https://twitter.com/AngularClass'; public primaryAction: Action; public isSubPage = false; public title = 'Medical Appointment Scheduling'; public actions: Action[]; private snackBarRef: MdSnackBarRef<SimpleSnackBar>; constructor( private _state: AppState, private _location: Location, private router: Router, private dialog: MdDialog, private slimLoadingBarService: SlimLoadingBarService, private attendanceService: AttendanceService, private appointmentService: AppointmentService, private examinationService: ExaminationService, private patientService: PatientService, private roomService: RoomService, private cantyCTIService: CantyCTIService, private snackBar: MdSnackBar, private viewContainerRef: ViewContainerRef) {} public ngOnInit() { console.log('Locale is %s', localStorage.getItem('locale')); // Listen for title changes this._state.title.subscribe( (title) => this.title = title, (error) => { this.title = 'Medical Appointment Scheduling'; console.log('Error getting title for activated route.'); }, () => console.log('Finished retrieving titles for activated route.') ); // Listen for toolbar icon changes this._state.isSubPage.subscribe( (isSubPage) => this.isSubPage = isSubPage, (error) => { this.isSubPage = false; console.log('Error getting isSubPage for activated route.'); }, () => console.log('Finished retrieving isSubPage for activated route.') ); // Listen for toolbar action changes this._state.actions.subscribe( (actions) => this.actions = actions, (error) => { this.actions = undefined; console.log('Error getting actions for activated route.'); }, () => console.log('Finished retrieving actions for activated route.') ); // Listen for toolbar action changes this._state.primaryAction.subscribe( (primaryAction) => this.primaryAction = primaryAction, (error) => { this.primaryAction = undefined; console.log('Error getting primary action for activated route.'); }, () => console.log('Finished retrieving primary action for activated route.') ); // Listen for CantyCTI events this.cantyCTIService.incomingCall.subscribe( (incomingCall) => { if (incomingCall.callState === IncomingCallState.RINGING) { const filter = { where: { phone: incomingCall.phoneNumber } }; this.patientService.patientFindOne(JSON.stringify(filter)) .subscribe( (patient) => { const message = localStorage.getItem('locale').startsWith('de') ? `Eingehender Anruf von ${patient.givenName} ${patient.surname}` : `Incoming call from ${patient.givenName} ${patient.surname}`; const action = localStorage.getItem('locale') .startsWith('de') ? 'Zum Patienten' : 'Open'; this.snackBarRef = this.snackBar.open(message, action); this.snackBarRef.onAction().subscribe( null, null, () => this.router.navigate(['appointment', 'patient', patient.id]) ); }, (err) => { this.snackBar.open( `Incoming call from ${incomingCall.phoneNumber}`, 'OK' ); } ); } else if (incomingCall.callState === IncomingCallState.OFFHOOK) { // Nothing to do here, just keep displaying the snack bar } else { // Hang up, IDLE this.snackBarRef.dismiss(); // No probleme here if already dismissed this.snackBarRef = null; } }, (err) => console.log(err), () => console.log('CantyCTI has finished broadcasting incoming calls.') ); } public actionsHandler(action: Action) { if (action) { if (action.clickHandler) { action.clickHandler(); } } } public navigateBack() { this._location.back(); } public deleteAllRooms() { this.slimLoadingBarService.start(); this.roomService.roomDeleteAllRooms() .subscribe( (x) => { this.snackBar.open(`Deleted ${x.deletedCount} rooms.`, null, { duration: 3000 }); console.log(`Deleted all ${x.deletedCount} rooms.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public deleteAllAppointments() { this.slimLoadingBarService.start(); this.appointmentService.appointmentDeleteAllAppointments() .subscribe( (x) => { this.snackBar.open(`Deleted ${x.deletedCount} appointments.`, null, { duration: 3000 }); console.log(`Deleted all ${x.deletedCount} appointments.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public deleteAllExaminations() { this.slimLoadingBarService.start(); this.examinationService.examinationDeleteAllExaminations() .subscribe( (x) => { this.snackBar.open(`Deleted ${x.deletedCount} examinations.`, null, { duration: 3000 }); console.log(`Deleted all ${x.deletedCount} examinations.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public deleteAllAttendances() { this.slimLoadingBarService.start(); this.attendanceService.attendanceDeleteAllAttendances() .subscribe( (x) => { this.snackBar.open(`Deleted ${x.deletedCount} attendances.`, null, { duration: 3000 }); console.log(`Deleted all ${x.deletedCount} attendances.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public deleteAllPatients() { this.slimLoadingBarService.start(); this.patientService.patientDeleteAllPatients() .subscribe( (x) => { this.snackBar.open(`Deleted ${x.deletedCount} patients.`, null, { duration: 3000 }); console.log(`Deleted all ${x.deletedCount} patients.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public insertTestPatients() { this.slimLoadingBarService.start(); this.patientService.patientInsertTestData(localStorage.getItem('locale')) .subscribe( (x) => { this.snackBar.open(`Inserted ${x.insertCount} test entries for patients.`, null, { duration: 3000 }); console.log(`Inserted ${x.insertCount} test entries for patients.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public insertTestExaminations() { this.dialog.open(InsertTestExaminationsDialogComponent).afterClosed().subscribe( (result) => { if (result) { this.slimLoadingBarService.start(); this.examinationService.examinationInsertTestData( result.sectionNumber, localStorage.getItem('locale') ) .subscribe( (x) => { this.snackBar.open( `Inserted ${x.insertCount} examinations from ${result.sectionTitle}.`, null, { duration: 3000 } ); console.log(`Inserted ${x.insertCount} examinations from ${result.sectionTitle}.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } } ); } public insertTestRooms() { this.slimLoadingBarService.start(); this.roomService.roomInsertTestData(localStorage.getItem('locale')) .subscribe( (x) => { this.snackBar.open(`Inserted ${x.insertCount} test entries for rooms.`, null, { duration: 3000 }); console.log(`Inserted ${x.insertCount} test entries for rooms.`); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public createRandomAppointments() { this.slimLoadingBarService.start(); this.appointmentService.appointmentGenerateRandomAppointments() .subscribe( (x) => { this.snackBar.open('Created random appointments.', null, { duration: 3000 }); console.log('Created random appointments.'); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } public createRandomAttendances() { this.slimLoadingBarService.start(); this.attendanceService.attendanceGenerateRandomAttendances() .subscribe( (x) => { this.snackBar.open('Created random attendances.', null, { duration: 3000 }); console.log('Created random attendances.'); this.slimLoadingBarService.complete(); }, (err) => { console.log(err); this.slimLoadingBarService.reset(); } ); } }
the_stack
import type {Mutable} from "@swim/util"; import {AnyItem, Item} from "./Item"; import {Field} from "./Field"; import {Attr} from "./Attr"; import {AnyValue, Value} from "./Value"; import {Record} from "./Record"; import {RecordMap} from "./RecordMap"; import {AnyNum, Num} from "./"; // forward import /** @internal */ export class RecordMapView extends Record { constructor(record: RecordMap, lower: number, upper: number) { super(); this.record = record; this.lower = lower; this.upper = upper; } /** @internal */ readonly record: RecordMap; /** @internal */ readonly lower: number; /** @internal */ readonly upper: number; override isEmpty(): boolean { return this.lower === this.upper; } override isArray(): boolean { const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { if (array![i] instanceof Field) { return false; } } return true; } override isObject(): boolean { const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { if (array![i] instanceof Value) { return false; } } return true; } override get length(): number { return this.upper - this.lower; } declare readonly fieldCount: number; // getter defined below to work around useDefineForClassFields lunacy override get valueCount(): number { let k = 0; const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { if (array![i] instanceof Value) { k += 1; } } return k; } override isConstant(): boolean { const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { if (!array![i]!.isConstant()) { return false; } } return true; } override get tag(): string | undefined { if (this.length > 0) { const item = this.record.array![this.lower]; if (item instanceof Attr) { return item.key.value; } } return void 0; } override get target(): Value { let value: Value | undefined; let record: Record | undefined; let modified = false; const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { const item = array![i]; if (item instanceof Attr) { modified = true; } else if (value === void 0 && item instanceof Value) { value = item; } else { if (record === void 0) { record = Record.create(); if (value !== void 0) { record.push(value); } } record.push(item); } } if (value === void 0) { return Value.extant(); } else if (record === void 0) { return value; } else if (modified) { return record; } else { return this; } } override head(): Item { if (this.length > 0) { return this.record.array![this.lower]!; } else { return Item.absent(); } } override tail(): Record { if (this.length > 0) { return new RecordMapView(this.record, this.lower + 1, this.upper); } else { return Record.empty(); } } override body(): Value { const n = this.length; if (n > 2) { return new RecordMapView(this.record, this.lower + 1, this.upper).branch(); } else if (n === 2) { const item = this.record.array![this.lower + 1]; if (item instanceof Value) { return item; } else { return Record.of(item); } } else { return Value.absent(); } } override indexOf(item: AnyItem, index: number = 0): number { item = Item.fromAny(item); const array = this.record.array; const n = this.length; if (index < 0) { index = Math.max(0, n + index); } index = this.lower + index; while (index < this.upper) { if (item.equals(array![index])) { return index - this.lower; } index += 1; } return -1; } override lastIndexOf(item: AnyItem, index?: number): number { item = Item.fromAny(item); const array = this.record.array; const n = this.length; if (index === void 0) { index = n - 1; } else if (index < 0) { index = n + index; } index = this.lower + Math.min(index, n - 1); while (index >= this.lower) { if (item.equals(array![index])) { return index - this.lower; } index -= 1; } return -1; } override getItem(index: AnyNum): Item { if (index instanceof Num) { index = index.value; } const n = this.length; if (index < 0) { index = n + index; } if (index >= 0 && index < n) { return this.record.array![this.lower + index]!; } else { return Item.absent(); } } override setItem(index: number, newItem: AnyItem): this { if ((this.record.flags & Record.ImmutableFlag) !== 0) { throw new Error("immutable"); } newItem = Item.fromAny(newItem); const n = this.length; if (index < 0) { index = n + index; } if (index < 0 || index > n) { throw new RangeError("" + index); } if ((this.record.flags & Record.AliasedFlag) !== 0) { this.setItemAliased(index, newItem); } else { this.setItemMutable(index, newItem); } return this; } /** @internal */ setItemAliased(index: number, newItem: Item): void { const record = this.record; const n = record.length; const oldArray = record.array; const newArray = new Array(Record.expand(n)); for (let i = 0; i < n; i += 1) { newArray[i] = oldArray![i]; } const oldItem = oldArray !== null ? oldArray[this.lower + index] : null; newArray[this.lower + index] = newItem; (record as Mutable<RecordMap>).array = newArray; (record as Mutable<RecordMap>).table = null; if (newItem instanceof Field) { if (!(oldItem instanceof Field)) { (record as Mutable<RecordMap>).fieldCount += 1; } } else if (oldItem instanceof Field) { (record as Mutable<RecordMap>).fieldCount -= 1; } (record as Mutable<RecordMap>).flags &= ~Record.AliasedFlag; } /** @internal */ setItemMutable(index: number, newItem: Item): void { const record = this.record; const array = record.array!; const oldItem = array[this.lower + index]; array[this.lower + index] = newItem; if (newItem instanceof Field) { (record as Mutable<RecordMap>).table = null; if (!(oldItem instanceof Field)) { (record as Mutable<RecordMap>).fieldCount += 1; } } else if (oldItem instanceof Field) { (record as Mutable<RecordMap>).table = null; (record as Mutable<RecordMap>).fieldCount -= 1; } } override push(...newItems: AnyItem[]): number { if ((this.record.flags & Record.ImmutableFlag) !== 0) { throw new Error("immutable"); } if ((this.record.flags & Record.AliasedFlag) !== 0) { this.pushAliased(...newItems); } else { this.pushMutable(...newItems); } return this.length; } /** @internal */ pushAliased(...newItems: AnyItem[]): void { const record = this.record; const k = newItems.length; let m = record.length; let n = record.fieldCount; const oldArray = record.array; const newArray = new Array(Record.expand(m + k)); if (oldArray !== null) { for (let i = 0; i < this.upper; i += 1) { newArray[i] = oldArray[i]; } for (let i = this.upper; i < m; i += 1) { newArray[i + k] = oldArray[i]; } } for (let i = 0; i < k; i += 1) { const newItem = Item.fromAny(newItems[i]); newArray[i + this.upper] = newItem; m += 1; if (newItem instanceof Field) { n += 1; } } (record as Mutable<RecordMap>).array = newArray; (record as Mutable<RecordMap>).table = null; (record as Mutable<RecordMap>).length = m; (record as Mutable<RecordMap>).fieldCount = n; (record as Mutable<RecordMap>).flags &= ~Record.AliasedFlag; (this as Mutable<this>).upper += k; } /** @internal */ pushMutable(...newItems: AnyItem[]): void { const record = this.record; const k = newItems.length; let m = record.length; let n = record.fieldCount; const oldArray = record.array!; let newArray; if (oldArray === null || m + k > oldArray.length) { newArray = new Array(Record.expand(m + k)); if (oldArray !== null) { for (let i = 0; i < this.upper; i += 1) { newArray[i] = oldArray[i]; } } } else { newArray = oldArray; } for (let i = m - 1; i >= this.upper; i -= 1) { newArray[i + k] = oldArray[i]; } for (let i = 0; i < k; i += 1) { const newItem = Item.fromAny(newItems[i]); newArray[i + this.upper] = newItem; m += 1; if (newItem instanceof Field) { n += 1; (record as Mutable<RecordMap>).table = null; } } (record as Mutable<RecordMap>).array = newArray; (record as Mutable<RecordMap>).length = m; (record as Mutable<RecordMap>).fieldCount = n; (this as Mutable<this>).upper += k; } override splice(start: number, deleteCount: number = 0, ...newItems: AnyItem[]): Item[] { if ((this.record.flags & Record.ImmutableFlag) !== 0) { throw new Error("immutable"); } const n = this.length; if (start < 0) { start = n + start; } start = Math.min(Math.max(0, start), n); deleteCount = Math.min(Math.max(0, deleteCount), n - start); let deleted; if ((this.record.flags & Record.AliasedFlag) !== 0) { deleted = this.record.spliceAliased(this.lower + start, deleteCount, ...newItems); } else { deleted = this.record.spliceMutable(this.lower + start, deleteCount, ...newItems); } (this as Mutable<this>).upper += newItems.length - deleted.length; return deleted; } override delete(key: AnyValue): Item { if ((this.record.flags & Record.ImmutableFlag) !== 0) { throw new Error("immutable"); } key = Value.fromAny(key); if ((this.record.flags & Record.AliasedFlag) !== 0) { return this.deleteAliased(key); } else { return this.deleteMutable(key); } } /** @internal */ deleteAliased(key: Value): Item { const record = this.record; const n = record.length; const oldArray = record.array; const newArray = new Array(Record.expand(n)); for (let i = this.lower; i < this.upper; i += 1) { const item = oldArray![i]; if (item instanceof Field && item.key.equals(key)) { for (let j = i + 1; j < n; j += 1, i += 1) { newArray[i] = oldArray![j]; } (record as Mutable<RecordMap>).array = newArray; (record as Mutable<RecordMap>).table = null; (record as Mutable<RecordMap>).length = n - 1; (record as Mutable<RecordMap>).fieldCount -= 1; (record as Mutable<RecordMap>).flags &= ~Record.AliasedFlag; (this as Mutable<this>).upper -= 1; return item; } newArray[i] = item; } return Item.absent(); } /** @internal */ deleteMutable(key: Value): Item { const record = this.record; const n = record.length; const array = record.array; for (let i = this.lower; i < this.upper; i += 1) { const item = array![i]!; if (item instanceof Field && item.key.equals(key)) { for (let j = i + 1; j < n; j += 1, i += 1) { array![i] = array![j]!; } array![n - 1] = void 0 as any; (record as Mutable<RecordMap>).table = null; (record as Mutable<RecordMap>).length = n - 1; (record as Mutable<RecordMap>).fieldCount -= 1; (this as Mutable<this>).upper -= 1; return item; } } return Item.absent(); } override clear(): void { if ((this.record.flags & Record.ImmutableFlag) !== 0) { throw new Error("immutable"); } if ((this.record.flags & Record.AliasedFlag) !== 0) { this.clearAliased(); } else { this.clearMutable(); } } /** @internal */ clearAliased(): void { const record = this.record; const m = record.length; let n = record.fieldCount; const l = m - this.length; const oldArray = record.array; const newArray = new Array(Record.expand(l)); let i = 0; while (i < this.lower) { newArray[i] = oldArray![i]; i += 1; } while (i < this.upper) { if (oldArray![i] instanceof Field) { n -= 1; } i += 1; } i = this.lower; let j = this.upper; while (j < m) { newArray[i] = oldArray![j]; i += 1; j += 1; } (record as Mutable<RecordMap>).array = newArray; (record as Mutable<RecordMap>).table = null; (record as Mutable<RecordMap>).length = l; (record as Mutable<RecordMap>).fieldCount = n; (record as Mutable<RecordMap>).flags &= ~Record.AliasedFlag; (this as Mutable<this>).upper = this.lower; } /** @internal */ clearMutable(): void { const record = this.record; const m = record.length; let n = record.fieldCount; const array = record.array; let i = this.lower; while (i < this.upper) { if (array![i] instanceof Field) { n -= 1; } i += 1; } i = this.lower; let j = this.upper; while (j < m) { const item = array![j]!; if (item instanceof Field) { (record as Mutable<RecordMap>).table = null; } array![i] = item; i += 1; j += 1; } (record as Mutable<RecordMap>).length = i; (record as Mutable<RecordMap>).fieldCount = n; while (i < m) { array![i] = void 0 as any; i += 1; } (this as Mutable<this>).upper = this.lower; } override isAliased(): boolean { return (this.record.flags & Record.AliasedFlag) !== 0; } override isMutable(): boolean { return (this.record.flags & Record.ImmutableFlag) === 0; } override alias(): void { (this.record as Mutable<RecordMap>).flags |= Record.AliasedFlag; } override branch(): RecordMap { const m = this.length; let n = 0; const oldArray = this.record.array; const newArray = new Array(Record.expand(m)); let i = this.lower; let j = 0; while (j < m) { const item = oldArray![i]; newArray[j] = item; if (item instanceof Field) { n += 1; } i += 1; j += 1; } return new RecordMap(newArray, null, m, n, 0); } override clone(): RecordMap { const m = this.length; let n = 0; const oldArray = this.record.array; const newArray = new Array(Record.expand(m)); let i = this.lower; let j = 0; while (j < m) { const item = oldArray![i]!; newArray[j] = item.clone(); if (item instanceof Field) { n += 1; } i += 1; j += 1; } return new RecordMap(newArray, null, m, n, 0); } override commit(): this { this.record.commit(); return this; } override subRecord(lower?: number, upper?: number): Record { const n = this.length; if (lower === void 0) { lower = 0; } else if (lower < 0) { lower = n + lower; } if (upper === void 0) { upper = n; } else if (upper < 0) { upper = n + upper; } if (lower < 0 || upper > n || lower > upper) { throw new RangeError(lower + ", " + upper); } return new RecordMapView(this.record, this.lower + lower, this.upper + upper); } override forEach<T>(callback: (item: Item, index: number) => T | void): T | undefined; override forEach<T, S>(callback: (this: S, item: Item, index: number) => T | void, thisArg?: S): T | undefined; override forEach<T, S>(callback: (this: S | undefined, item: Item, index: number) => T | void, thisArg?: S): T | undefined { const array = this.record.array; for (let i = this.lower, n = this.upper; i < n; i += 1) { const result = callback.call(thisArg, array![i]!, i); if (result !== void 0) { return result; } } return void 0; } } Object.defineProperty(RecordMapView.prototype, "fieldCount", { get(this: RecordMapView): number { const array = this.record.array; let k = 0; for (let i = this.lower, n = this.upper; i < n; i += 1) { if (array![i] instanceof Field) { k += 1; } } return k; }, configurable: true, });
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const releaseOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'release', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a release', }, { name: 'Delete', value: 'delete', description: 'Delete a release', }, { name: 'Get', value: 'get', description: 'Get release by version identifier', }, { name: 'Get All', value: 'getAll', description: 'Get all releases', }, { name: 'Update', value: 'update', description: 'Update a release', }, ], default: 'get', description: 'The operation to perform', }, ]; export const releaseFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* release:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Organization Slug', name: 'organizationSlug', type: 'options', typeOptions: { loadOptionsMethod: 'getOrganizations', }, default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'getAll', ], }, }, required: true, description: 'The slug of the organization the releases belong to.', }, { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'release', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'release', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 500, }, default: 100, description: 'How many results to return.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'release', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Query', name: 'query', type: 'string', default: '', description: 'This parameter can be used to create a “starts with” filter for the version.', }, ], }, /* -------------------------------------------------------------------------- */ /* release:get/delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Organization Slug', name: 'organizationSlug', type: 'options', typeOptions: { loadOptionsMethod: 'getOrganizations', }, default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'get', 'delete', ], }, }, required: true, description: 'The slug of the organization the release belongs to.', }, { displayName: 'Version', name: 'version', type: 'string', default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'get', 'delete', ], }, }, required: true, description: 'The version identifier of the release.', }, /* -------------------------------------------------------------------------- */ /* release:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Organization Slug', name: 'organizationSlug', type: 'options', typeOptions: { loadOptionsMethod: 'getOrganizations', }, default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'create', ], }, }, required: true, description: 'The slug of the organization the release belongs to.', }, { displayName: 'Version', name: 'version', type: 'string', default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'create', ], }, }, required: true, description: 'A version identifier for this release. Can be a version number, a commit hash etc.', }, { displayName: 'URL', name: 'url', type: 'string', default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'create', ], }, }, required: true, description: 'A URL that points to the release. This can be the path to an online interface to the sourcecode for instance.', }, { displayName: 'Projects', name: 'projects', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getProjects', }, default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'create', ], }, }, required: true, description: 'A list of project slugs that are involved in this release.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'release', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Date released', name: 'dateReleased', type: 'dateTime', default: '', description: 'An optional date that indicates when the release went live. If not provided the current time is assumed.', }, { displayName: 'Commits', name: 'commits', description: 'An optional list of commit data to be associated with the release.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'commitProperties', displayName: 'Commit Properties', values: [ { displayName: 'ID', name: 'id', type: 'string', default: '', description: 'The sha of the commit.', required: true, }, { displayName: 'Author Email', name: 'authorEmail', type: 'string', default: '', description: 'Authors email.', }, { displayName: 'Author Name', name: 'authorName', type: 'string', default: '', description: 'Name of author.', }, { displayName: 'Message', name: 'message', type: 'string', default: '', description: 'Message of commit.', }, { displayName: 'Patch Set', name: 'patchSet', description: 'A list of the files that have been changed in the commit. Specifying the patch_set is necessary to power suspect commits and suggested assignees.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'patchSetProperties', displayName: 'Patch Set Properties', values: [ { displayName: 'Path', name: 'path', type: 'string', default: '', description: 'The path to the file. Both forward and backward slashes are supported.', required: true, }, { displayName: 'Type', name: 'type', type: 'options', default: '', description: 'The types of changes that happend in that commit.', options: [ { name: 'Add', value: 'add', }, { name: 'Modify', value: 'modify', }, { name: 'Delete', value: 'delete', }, ], }, ], }, ], }, { displayName: 'Repository', name: 'repository', type: 'string', default: '', description: 'Repository name.', }, { displayName: 'Timestamp', name: 'timestamp', type: 'dateTime', default: '', description: 'Timestamp of commit.', }, ], }, ], }, { displayName: 'Refs', name: 'refs', description: 'An optional way to indicate the start and end commits for each repository included in a release.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'refProperties', displayName: 'Ref Properties', values: [ { displayName: 'Commit', name: 'commit', type: 'string', default: '', description: 'The head sha of the commit.', required: true, }, { displayName: 'Repository', name: 'repository', type: 'string', default: '', description: 'Repository name.', required: true, }, { displayName: 'Previous Commit', name: 'previousCommit', type: 'string', default: '', description: 'The sha of the HEAD of the previous release.', }, ], }, ], }, ], }, /* -------------------------------------------------------------------------- */ /* release:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Organization Slug', name: 'organizationSlug', type: 'options', typeOptions: { loadOptionsMethod: 'getOrganizations', }, default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'update', ], }, }, required: true, description: 'The slug of the organization the release belongs to.', }, { displayName: 'Version', name: 'version', type: 'string', default: '', displayOptions: { show: { resource: [ 'release', ], operation: [ 'update', ], }, }, required: true, description: 'A version identifier for this release. Can be a version number, a commit hash etc.', }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'release', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Commits', name: 'commits', description: 'An optional list of commit data to be associated with the release.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'commitProperties', displayName: 'Commit Properties', values: [ { displayName: 'ID', name: 'id', type: 'string', default: '', description: 'The sha of the commit.', required: true, }, { displayName: 'Author Email', name: 'authorEmail', type: 'string', default: '', description: 'Authors email.', }, { displayName: 'Author Name', name: 'authorName', type: 'string', default: '', description: 'Name of author.', }, { displayName: 'Message', name: 'message', type: 'string', default: '', description: 'Message of commit.', }, { displayName: 'Patch Set', name: 'patchSet', description: 'A list of the files that have been changed in the commit. Specifying the patch_set is necessary to power suspect commits and suggested assignees.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'patchSetProperties', displayName: 'Patch Set Properties', values: [ { displayName: 'Path', name: 'path', type: 'string', default: '', description: 'The path to the file. Both forward and backward slashes are supported.', required: true, }, { displayName: 'Type', name: 'type', type: 'options', default: '', description: 'The types of changes that happend in that commit.', options: [ { name: 'Add', value: 'add', }, { name: 'Modify', value: 'modify', }, { name: 'Delete', value: 'delete', }, ], }, ], }, ], }, { displayName: 'Repository', name: 'repository', type: 'string', default: '', description: 'Repository name.', }, { displayName: 'Timestamp', name: 'timestamp', type: 'dateTime', default: '', description: 'Timestamp of commit.', }, ], }, ], }, { displayName: 'Date released', name: 'dateReleased', type: 'dateTime', default: '', description: 'an optional date that indicates when the release went live. If not provided the current time is assumed.', }, { displayName: 'Ref', name: 'ref', type: 'string', default: '', description: 'A URL that points to the release. This can be the path to an online interface to the sourcecode for instance.', }, { displayName: 'Refs', name: 'refs', description: 'An optional way to indicate the start and end commits for each repository included in a release.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, default: {}, options: [ { name: 'refProperties', displayName: 'Ref Properties', values: [ { displayName: 'Commit', name: 'commit', type: 'string', default: '', description: 'The head sha of the commit.', required: true, }, { displayName: 'Repository', name: 'repository', type: 'string', default: '', description: 'Repository name.', required: true, }, { displayName: 'Previous Commit', name: 'previousCommit', type: 'string', default: '', description: 'The sha of the HEAD of the previous release.', }, ], }, ], }, { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'A URL that points to the release. This can be the path to an online interface to the sourcecode for instance.', }, ], }, ];
the_stack
import { Autowired } from '@opensumi/di'; import { IContextKeyService, ClientAppContribution, SlotLocation, SlotRendererContribution, SlotRendererRegistry, slotRendererRegistry, KeybindingRegistry, } from '@opensumi/ide-core-browser'; import { getIcon } from '@opensumi/ide-core-browser'; import { ComponentContribution, ComponentRegistry, TabBarToolbarContribution, ToolbarRegistry, } from '@opensumi/ide-core-browser/lib/layout'; import { LayoutState } from '@opensumi/ide-core-browser/lib/layout/layout-state'; import { IMenuRegistry, MenuCommandDesc, MenuContribution as MenuContribution, MenuId, } from '@opensumi/ide-core-browser/lib/menu/next'; import { Domain, IEventBus, ContributionProvider, localize, WithEventBus } from '@opensumi/ide-core-common'; import { CommandContribution, CommandRegistry, Command, CommandService } from '@opensumi/ide-core-common/lib/command'; import { IMainLayoutService } from '../common'; import { RightTabRenderer, LeftTabRenderer, NextBottomTabRenderer } from './tabbar/renderer.view'; // NOTE 左右侧面板的展开、折叠命令请使用组合命令 activity-bar.left.toggle,layout命令仅做折叠展开,不处理tab激活逻辑 export const HIDE_LEFT_PANEL_COMMAND: Command = { id: 'main-layout.left-panel.hide', label: '%main-layout.left-panel.hide%', }; export const WORKBENCH_ACTION_CLOSESIDECAR: Command = { id: 'workbench.action.closeSidebar', label: '%main-layout.sidebar.hide%', }; export const SHOW_LEFT_PANEL_COMMAND: Command = { id: 'main-layout.left-panel.show', label: '%main-layout.left-panel.show%', }; export const TOGGLE_LEFT_PANEL_COMMAND: MenuCommandDesc = { id: 'main-layout.left-panel.toggle', label: '%main-layout.left-panel.toggle%', }; export const HIDE_RIGHT_PANEL_COMMAND: Command = { id: 'main-layout.right-panel.hide', label: '%main-layout.right-panel.hide%', }; export const SHOW_RIGHT_PANEL_COMMAND: Command = { id: 'main-layout.right-panel.show', label: '%main-layout.right-panel.show%', }; export const TOGGLE_RIGHT_PANEL_COMMAND: MenuCommandDesc = { id: 'main-layout.right-panel.toggle', label: '%main-layout.right-panel.toggle%', }; export const HIDE_BOTTOM_PANEL_COMMAND: Command = { id: 'main-layout.bottom-panel.hide', label: '%main-layout.bottom-panel.hide%', }; export const WORKBENCH_ACTION_CLOSEPANEL: Command = { id: 'workbench.action.closePanel', delegate: HIDE_BOTTOM_PANEL_COMMAND.id, }; export const SHOW_BOTTOM_PANEL_COMMAND: Command = { id: 'main-layout.bottom-panel.show', label: '%main-layout.bottom-panel.show%', }; export const TOGGLE_BOTTOM_PANEL_COMMAND: Command = { id: 'main-layout.bottom-panel.toggle', iconClass: getIcon('minus'), label: localize('layout.tabbar.toggle'), }; export const IS_VISIBLE_BOTTOM_PANEL_COMMAND: Command = { id: 'main-layout.bottom-panel.is-visible', }; export const IS_VISIBLE_LEFT_PANEL_COMMAND: Command = { id: 'main-layout.left-panel.is-visible', }; export const IS_VISIBLE_RIGHT_PANEL_COMMAND: Command = { id: 'main-layout.right-panel.is-visible', }; export const SET_PANEL_SIZE_COMMAND: Command = { id: 'main-layout.panel.size.set', }; export const EXPAND_BOTTOM_PANEL: Command = { id: 'main-layout.bottom-panel.expand', label: localize('layout.tabbar.expand'), iconClass: getIcon('expand'), }; export const RETRACT_BOTTOM_PANEL: Command = { id: 'main-layout.bottom-panel.retract', label: localize('layout.tabbar.retract'), iconClass: getIcon('shrink'), }; @Domain(CommandContribution, ClientAppContribution, SlotRendererContribution, MenuContribution) export class MainLayoutModuleContribution extends WithEventBus implements CommandContribution, ClientAppContribution, SlotRendererContribution, MenuContribution { @Autowired(IMainLayoutService) private mainLayoutService: IMainLayoutService; @Autowired(IContextKeyService) contextKeyService: IContextKeyService; @Autowired(IEventBus) eventBus: IEventBus; @Autowired(ComponentContribution) contributionProvider: ContributionProvider<ComponentContribution>; @Autowired(SlotRendererContribution) rendererContributionProvider: ContributionProvider<SlotRendererContribution>; @Autowired(ComponentRegistry) componentRegistry: ComponentRegistry; @Autowired(CommandService) private commandService!: CommandService; @Autowired() private layoutState: LayoutState; @Autowired(TabBarToolbarContribution) protected readonly toolBarContributionProvider: ContributionProvider<TabBarToolbarContribution>; @Autowired() private toolBarRegistry: ToolbarRegistry; @Autowired(KeybindingRegistry) protected keybindingRegistry: KeybindingRegistry; async initialize() { // 全局只要初始化一次 await this.layoutState.initStorage(); const componentContributions = this.contributionProvider.getContributions(); for (const contribution of componentContributions) { if (contribution.registerComponent) { contribution.registerComponent(this.componentRegistry); } } const rendererContributions = this.rendererContributionProvider.getContributions(); for (const contribution of rendererContributions) { if (contribution.registerRenderer) { contribution.registerRenderer(slotRendererRegistry); } } const contributions = this.toolBarContributionProvider.getContributions(); for (const contribution of contributions) { if (contribution.registerToolbarItems) { contribution.registerToolbarItems(this.toolBarRegistry); } } } async onStart() { this.registerSideToggleKey(); } async onDidStart() { this.mainLayoutService.didMount(); } registerRenderer(registry: SlotRendererRegistry) { registry.registerSlotRenderer(SlotLocation.right, RightTabRenderer); registry.registerSlotRenderer(SlotLocation.left, LeftTabRenderer); registry.registerSlotRenderer(SlotLocation.bottom, NextBottomTabRenderer); } registerCommands(commands: CommandRegistry): void { // @deprecated commands.registerCommand(HIDE_LEFT_PANEL_COMMAND, { execute: () => { this.mainLayoutService.toggleSlot(SlotLocation.left, false); }, }); // @deprecated commands.registerCommand(SHOW_LEFT_PANEL_COMMAND, { execute: (size?: number) => { this.mainLayoutService.toggleSlot(SlotLocation.left, true, size); }, }); commands.registerCommand(TOGGLE_LEFT_PANEL_COMMAND, { execute: (show?: boolean, size?: number) => { this.mainLayoutService.toggleSlot(SlotLocation.left, show, size); }, }); // @deprecated commands.registerCommand(HIDE_RIGHT_PANEL_COMMAND, { execute: () => { this.mainLayoutService.toggleSlot(SlotLocation.right, false); }, }); // @deprecated commands.registerCommand(SHOW_RIGHT_PANEL_COMMAND, { execute: (size?: number) => { this.mainLayoutService.toggleSlot(SlotLocation.right, true, size); }, }); commands.registerCommand(TOGGLE_RIGHT_PANEL_COMMAND, { execute: (show?: boolean, size?: number) => { this.mainLayoutService.toggleSlot(SlotLocation.right, show, size); }, }); commands.registerCommand(WORKBENCH_ACTION_CLOSESIDECAR, { execute: () => Promise.all([ this.mainLayoutService.toggleSlot(SlotLocation.left, false), this.mainLayoutService.toggleSlot(SlotLocation.right, false), ]), }); commands.registerCommand(SHOW_BOTTOM_PANEL_COMMAND, { execute: () => { this.mainLayoutService.toggleSlot(SlotLocation.bottom, true); }, }); commands.registerCommand(HIDE_BOTTOM_PANEL_COMMAND, { execute: () => { this.mainLayoutService.toggleSlot(SlotLocation.bottom, false); }, }); commands.registerCommand(WORKBENCH_ACTION_CLOSEPANEL); commands.registerCommand(TOGGLE_BOTTOM_PANEL_COMMAND, { execute: (show?: boolean, size?: number) => { this.mainLayoutService.toggleSlot(SlotLocation.bottom, show, size); }, }); commands.registerCommand(IS_VISIBLE_BOTTOM_PANEL_COMMAND, { execute: () => this.mainLayoutService.getTabbarService('bottom').currentContainerId !== '', }); commands.registerCommand(IS_VISIBLE_LEFT_PANEL_COMMAND, { execute: () => this.mainLayoutService.isVisible(SlotLocation.left), }); commands.registerCommand(IS_VISIBLE_RIGHT_PANEL_COMMAND, { execute: () => this.mainLayoutService.isVisible(SlotLocation.left), }); commands.registerCommand(SET_PANEL_SIZE_COMMAND, { execute: (size: number) => { this.mainLayoutService.setFloatSize(size); }, }); commands.registerCommand(EXPAND_BOTTOM_PANEL, { execute: () => { this.mainLayoutService.expandBottom(true); }, }); commands.registerCommand(RETRACT_BOTTOM_PANEL, { execute: () => { this.mainLayoutService.expandBottom(false); }, }); commands.registerCommand( { id: 'view.outward.right-panel.hide', }, { execute: () => { this.commandService.executeCommand('main-layout.right-panel.toggle', false); }, }, ); commands.registerCommand( { id: 'view.outward.right-panel.show', }, { execute: (size?: number) => { this.commandService.executeCommand('main-layout.right-panel.toggle', true, size); }, }, ); commands.registerCommand( { id: 'view.outward.left-panel.hide', }, { execute: () => { this.commandService.executeCommand('main-layout.left-panel.toggle', false); }, }, ); commands.registerCommand( { id: 'view.outward.left-panel.show', }, { execute: (size?: number) => { this.commandService.executeCommand('main-layout.left-panel.toggle', true, size); }, }, ); } registerMenus(menus: IMenuRegistry) { menus.registerMenuItem(MenuId.ActivityBarExtra, { submenu: MenuId.SettingsIconMenu, iconClass: getIcon('setting'), label: localize('layout.tabbar.setting', '打开偏好设置'), order: 1, group: 'navigation', }); menus.registerMenuItem(MenuId.MenubarViewMenu, { command: TOGGLE_LEFT_PANEL_COMMAND, group: '5_panel', }); menus.registerMenuItem(MenuId.MenubarViewMenu, { command: TOGGLE_RIGHT_PANEL_COMMAND, group: '5_panel', }); } protected registerSideToggleKey() { this.keybindingRegistry.registerKeybinding({ keybinding: 'ctrlcmd+b', command: TOGGLE_LEFT_PANEL_COMMAND.id, }); this.keybindingRegistry.registerKeybinding({ keybinding: 'ctrlcmd+j', command: TOGGLE_BOTTOM_PANEL_COMMAND.id, }); this.keybindingRegistry.registerKeybinding({ keybinding: 'ctrlcmd+shift+j', command: EXPAND_BOTTOM_PANEL.id, when: '!bottomFullExpanded', }); this.keybindingRegistry.registerKeybinding({ keybinding: 'ctrlcmd+shift+j', command: RETRACT_BOTTOM_PANEL.id, when: 'bottomFullExpanded', }); } }
the_stack
namespace SchemeDesigner { /** * Scheme * @author Nikitchenko Sergey <nikitchenko.sergey@yandex.ru> */ export class Scheme { /** * Frame animation */ protected requestFrameAnimation: any; /** * Cancel animation */ protected cancelFrameAnimation: any; /** * Current number of rendering request */ protected renderingRequestId: number = 0; /** * Device Pixel Ratio */ protected devicePixelRatio: number = 1; /** * Event manager */ protected eventManager: EventManager; /** * Scroll manager */ protected scrollManager: ScrollManager; /** * Zoom manager */ protected zoomManager: ZoomManager; /** * Storage manager */ protected storageManager: StorageManager; /** * Map manager */ protected mapManager: MapManager; /** * Default cursor style */ protected defaultCursorStyle: string = 'default'; /** * Ratio for cache scheme */ protected cacheSchemeRatio: number = 2; /** * Bacground color */ protected background: string|null = null; /** * View */ protected view: View; /** * Cache view */ protected cacheView: View; /** * Changed objects */ protected changedObjects: SchemeObject[] = []; /** * Constructor * @param {HTMLCanvasElement} canvas * @param {Object} params */ constructor(canvas: HTMLCanvasElement, params?: any) { this.requestFrameAnimation = Polyfill.getRequestAnimationFrameFunction(); this.cancelFrameAnimation = Polyfill.getCancelAnimationFunction(); this.devicePixelRatio = Polyfill.getDevicePixelRatio(); if (params) { Tools.configure(this, params.options); } this.view = new View(canvas, this.background); /** * Managers */ this.scrollManager = new ScrollManager(this); this.zoomManager = new ZoomManager(this); this.eventManager = new EventManager(this); this.mapManager = new MapManager(this); this.storageManager = new StorageManager(this); /** * Configure */ if (params) { Tools.configure(this.scrollManager, params.scroll); Tools.configure(this.zoomManager, params.zoom); Tools.configure(this.mapManager, params.map); Tools.configure(this.storageManager, params.storage); Tools.configure(this.eventManager, params.event); } /** * Disable selections on canvas */ Tools.disableElementSelection(this.view.getCanvas()); /** * Set dimensions */ this.resize(); } /** * Resize canvas */ public resize(): void { this.view.resize(); this.mapManager.resize(); this.zoomManager.resetScale(); } /** * Get event manager * @returns {EventManager} */ public getEventManager(): EventManager { return this.eventManager; } /** * Get scroll manager * @returns {ScrollManager} */ public getScrollManager(): ScrollManager { return this.scrollManager; } /** * Get zoom manager * @returns {ZoomManager} */ public getZoomManager(): ZoomManager { return this.zoomManager; } /** * Get storage manager * @returns {StorageManager} */ public getStorageManager(): StorageManager { return this.storageManager; } /** * Get map manager * @returns {MapManager} */ public getMapManager(): MapManager { return this.mapManager; } /** * Get width * @returns {number} */ public getWidth(): number { return this.view.getWidth(); } /** * Get height * @returns {number} */ public getHeight(): number { return this.view.getHeight(); } /** * Request animation * @param animation * @returns {number} */ public requestFrameAnimationApply(animation: Function): number { return this.requestFrameAnimation.call(window, animation); } /** * Cancel animation * @param requestId */ public cancelAnimationFrameApply(requestId: number): void { return this.cancelFrameAnimation.call(window, requestId); } /** * Clear canvas context */ public clearContext(): this { let context = this.view.getContext(); context.save(); context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect( 0, 0, this.getWidth(), this.getHeight() ); context.restore(); return this; } /** * Request render all */ public requestRenderAll(): this { if (!this.renderingRequestId) { this.renderingRequestId = this.requestFrameAnimationApply(() => {this.renderAll()}); } return this; } /** * Render scheme */ public render(): void { /** * Create tree index */ this.storageManager.getTree(); /** * Set scheme to center with scale for all objects */ this.zoomManager.setScale(this.zoomManager.getScaleWithAllObjects()); this.scrollManager.toCenter(); this.updateCache(false); this.requestDrawFromCache(); } /** * Get visible bounding rect * @returns {{left: number, top: number, right: number, bottom: number}} */ public getVisibleBoundingRect(): BoundingRect { let scale = this.zoomManager.getScale(); let width = this.getWidth() / scale; let height = this.getHeight() / scale; let leftOffset = -this.scrollManager.getScrollLeft() / scale; let topOffset = -this.scrollManager.getScrollTop() / scale; return { left: leftOffset, top: topOffset, right: leftOffset + width, bottom: topOffset + height }; } /** * Render visible objects */ protected renderAll(): void { if (this.renderingRequestId) { this.cancelAnimationFrameApply(this.renderingRequestId); this.renderingRequestId = 0; } this.eventManager.sendEvent('beforeRenderAll'); this.clearContext(); this.view.drawBackground(); let visibleBoundingRect = this.getVisibleBoundingRect(); let nodes = this.storageManager.findNodesByBoundingRect(null, visibleBoundingRect); let layers = this.storageManager.getSortedLayers(); let renderedObjectIds: any = {}; for (let layer of layers) { for (let node of nodes) { for (let schemeObject of node.getObjectsByLayer(layer.getId())) { let objectId = schemeObject.getId(); if (typeof renderedObjectIds[objectId] !== 'undefined') { continue; } renderedObjectIds[objectId] = true; schemeObject.render(this, this.view); } } } this.mapManager.drawMap(); this.eventManager.sendEvent('afterRenderAll'); } /** * Add layer * @param layer */ public addLayer(layer: Layer): void { this.storageManager.addLayer(layer); } /** * Remove layer * @param layerId */ public removeLayer(layerId: string): void { this.storageManager.removeLayer(layerId); } /** * Canvas getter * @returns {HTMLCanvasElement} */ public getCanvas(): HTMLCanvasElement { return this.view.getCanvas(); } /** * Set cursor style * @param {string} cursor * @returns {SchemeDesigner} */ public setCursorStyle(cursor: string): this { this.view.getCanvas().style.cursor = cursor; return this; } /** * Get default cursor style * @returns {string} */ public getDefaultCursorStyle(): string { return this.defaultCursorStyle; } /** * Draw from cache * @returns {boolean} */ public drawFromCache(): boolean { if (!this.cacheView) { return false; } if (this.renderingRequestId) { this.cancelAnimationFrameApply(this.renderingRequestId); this.renderingRequestId = 0; } this.clearContext(); let boundingRect = this.storageManager.getObjectsBoundingRect(); this.view.drawBackground(); this.view.getContext().drawImage( this.cacheView.getCanvas(), 0, 0, boundingRect.right, boundingRect.bottom ); this.mapManager.drawMap(); return true; } /** * Request draw from cache * @returns {Scheme} */ public requestDrawFromCache(): this { if (!this.renderingRequestId) { this.renderingRequestId = this.requestFrameAnimationApply(() => { this.drawFromCache(); }); } return this; } /** * Update scheme cache * @param onlyChanged */ public updateCache(onlyChanged: boolean): void { if (!this.cacheView) { let storage = this.storageManager.getImageStorage('scheme-cache'); this.cacheView = new View(storage.getCanvas(), this.background); } if (onlyChanged) { for (let schemeObject of this.changedObjects) { let layer = this.storageManager.getLayerById(schemeObject.getLayerId()); if (layer instanceof Layer && layer.isVisible()) { schemeObject.clear(this, this.cacheView); schemeObject.render(this, this.cacheView); } } } else { let boundingRect = this.storageManager.getObjectsBoundingRect(); let scale = (1 / this.zoomManager.getScaleWithAllObjects()) * this.cacheSchemeRatio; let rectWidth = boundingRect.right * scale; let rectHeight = boundingRect.bottom * scale; this.cacheView.setDimensions({ width: rectWidth, height: rectHeight }); this.cacheView.getContext().scale(scale, scale); this.cacheView.drawBackground(); let layers = this.storageManager.getSortedLayers(); for (let layer of layers) { for (let schemeObject of layer.getObjects()) { schemeObject.render(this, this.cacheView); } } } this.changedObjects = []; } /** * Add changed object * @param schemeObject */ public addChangedObject(schemeObject: SchemeObject): void { this.changedObjects.push(schemeObject); } /** * Set cacheSchemeRatio * @param value */ public setCacheSchemeRatio(value: number): void { this.cacheSchemeRatio = value; } /** * get cacheSchemeRatio * @returns {number} */ public getCAcheSchemeRatio(): number { return this.cacheSchemeRatio; } /** * Use scheme from cache * @returns {boolean} */ public useSchemeCache(): boolean { let objectsDimensions = this.storageManager.getObjectsDimensions(); let ratio = (objectsDimensions.width * this.zoomManager.getScale()) / this.getWidth(); if (this.cacheSchemeRatio && ratio <= this.cacheSchemeRatio) { return true; } return false; } /** * Get view * @returns {View} */ public getView(): View { return this.view; } /** * Get cache view * @returns {View} */ public getCacheView(): View { return this.cacheView; } /** * Set background * @param value */ public setBackground(value: string|null): void { this.background = value; } /** * Get background * @returns {string|null} */ public getBackground(): string|null { return this.background; } } }
the_stack
import { detailedDiff, diff, } from 'deep-object-diff'; import { Client, Collection, Create, Expr, Get, Ref, Update, } from 'faunadb'; import { Subscription } from 'faunadb/src/types/Stream'; import isEqual from 'lodash.isequal'; import { setRecoilExternalState } from '../components/RecoilExternalStatePortal'; import { getClient } from '../lib/faunadb/faunadb'; import { canvasDatasetSelector } from '../states/canvasDatasetSelector'; import { UserSession } from '../types/auth/UserSession'; import { CanvasDataset } from '../types/CanvasDataset'; import { Canvas, UpdateCanvas, } from '../types/faunadb/Canvas'; import { CanvasDatasetResult } from '../types/faunadb/CanvasDatasetResult'; import { OnStreamedDocumentUpdate, OnStreamError, OnStreamInit, OnStreamStart, } from '../types/faunadb/CanvasStream'; import { FaunadbStreamVersionEvent } from '../types/faunadb/FaunadbStreamVersionEvent'; import { TypeOfRef } from '../types/faunadb/TypeOfRef'; const PUBLIC_SHARED_FAUNABD_TOKEN = process.env.NEXT_PUBLIC_SHARED_FAUNABD_TOKEN as string; const SHARED_CANVAS_DOCUMENT_ID = '1'; export const getUserClient = (user: Partial<UserSession>): Client => { const secret = user?.faunaDBToken || PUBLIC_SHARED_FAUNABD_TOKEN; return getClient(secret); }; /** * Starts the real-time stream between the browser and the FaunaDB database, on a specific record/document. * * @param user * @param onStart * @param onInit * @param onUpdate * * @param onError * @see https://docs.fauna.com/fauna/current/drivers/streaming.html#events */ export const initStream = async (user: Partial<UserSession>, onStart: OnStreamStart, onInit: OnStreamInit, onUpdate: OnStreamedDocumentUpdate, onError: OnStreamError) => { console.log('Init stream for user', user); const client: Client = getUserClient(user); const canvasRef: Expr | undefined = await findUserCanvasRef(user); if (canvasRef) { console.log('Working on Canvas document', canvasRef); let stream: Subscription; const _startStream = async () => { console.log(`Stream to FaunaDB is (re)starting for:`, canvasRef); stream = client.stream. // @ts-ignore document(canvasRef) .on('start', (at: number) => { console.log('[Streaming] Started at', at); onStart(stream, canvasRef as TypeOfRef, at); }) .on('snapshot', (snapshot: CanvasDatasetResult) => { console.log('[Streaming] "snapshot" event', snapshot); onInit(snapshot.data); }) .on('version', (version: FaunadbStreamVersionEvent) => { console.log('[Streaming] "version" event', version); if (version.action === 'update') { const canvasDatasetFromRemote: CanvasDatasetResult = version.document; if (canvasDatasetFromRemote?.data?.lastUpdatedBySessionEphemeralId !== user?.sessionEphemeralId) { console.log(`[Streaming] Update event received from different editor "${canvasDatasetFromRemote?.data?.lastUpdatedByUserName}" is being applied.`); onUpdate(canvasDatasetFromRemote?.data); } else { console.log('[Streaming] Update event received from same editor has been ignored.'); } } }) .on('error', async (error: any) => { console.error('[Streaming] "error" event:', error); // When receiving the "instance not found" error, automatically create a shared document of ID "1" if (error?.name === 'NotFound') { console.log('No record found, creating record...'); const canvasRef: Expr | undefined = await findUserCanvasRef(user); const defaultCanvasDataset: CanvasDataset = { nodes: [], edges: [], }; if (canvasRef) { const createDefaultRecord = Create(canvasRef, { data: defaultCanvasDataset, }); console.log('createDefaultRecord', createDefaultRecord); const result: CanvasDatasetResult = await client.query(createDefaultRecord); console.log('result', result); onInit(result?.data); } else { console.error(`[initStream] "canvasRef" is undefined, auto-creating shared document aborted.`, canvasRef); } } else { stream.close(); onError(error, _startStream); } }) // Not tested .on('history_rewrite', (error: any) => { console.log('Error:', error); stream.close(); onError(error, _startStream); }) .start(); }; _startStream(); } else { console.error(`[initStream] "canvasRef" is undefined, streaming aborted.`, canvasRef); } }; /** * Finds the user's canvas document. * * If the user is not authenticated, uses the shared canvas document instead. */ export const findUserCanvasRef = async (user: Partial<UserSession>): Promise<Expr | undefined> => { if (user?.isAuthenticated) { return await findOrCreateUserCanvas(user); } else { return Ref(Collection('Canvas'), SHARED_CANVAS_DOCUMENT_ID); } }; /** * Finds the canvas ref of the given user, creates it if doesn't exist. * * @param user */ export const findOrCreateUserCanvas = async (user: Partial<UserSession>): Promise<Expr | undefined> => { const client: Client = getUserClient(user); const canvasId = user?.activeProject?.canvas?.id; if (canvasId) { // If the user already has an existing canvas (taken from the active project), then simply return it return Ref(Collection('Canvas'), canvasId); } else { // Otherwise, the user doesn't have a Canvas document yet, so we create it // (this shouldn't happen anymore, because the canvas is automatically created when the project is created) try { const canvasDataset: CanvasDataset = { nodes: [], edges: [], }; const canvas: Canvas = { data: { ...canvasDataset, owner: Ref(Collection('Users'), user.id), // Indicating who's the editor who's made the change, so we can safely ignore the "version:update" event we'll soon receive // when the DB will notify all subscribed editors about the update lastUpdatedBySessionEphemeralId: user.sessionEphemeralId as string, lastUpdatedByUserName: user?.email || `Anonymous#${user?.sessionEphemeralId?.substring(0, 8)}`, }, }; const createUserCanvas = Create( Collection('Canvas'), canvas, ); try { const createUserCanvasResult = await client.query<Canvas>(createUserCanvas); console.log('createUserCanvasResult', createUserCanvasResult); return createUserCanvasResult?.ref; } catch (e) { console.error(`[findOrCreateUserCanvas] Error while creating canvas:`, e); } } catch (e) { console.error(`[findOrCreateUserCanvas] Error while fetching canvas:`, e); } } }; /** * Checks whether the canvas dataset should be updated in the database, by comparing the previous and new dataset. * * Ignores dataset changes if the dataset contains only: * - a start node with no edge * - OR a start node and an end node and one edge * - OR no node and no edge (it's temporary state until default nodes/edges are created) * * @param newCanvasDataset */ export const hasDatasetChanged = (newCanvasDataset: CanvasDataset): boolean => { const isEmptyDataset: boolean = newCanvasDataset?.nodes?.length === 0 && newCanvasDataset?.edges?.length === 0; if (isEmptyDataset) { return false; } const isDefaultDataset: boolean = newCanvasDataset?.nodes?.length === 1 && newCanvasDataset?.edges?.length === 0 && newCanvasDataset?.nodes[0]?.data?.type === 'start' || newCanvasDataset?.nodes?.length === 2 && newCanvasDataset?.edges?.length === 1 && newCanvasDataset?.nodes[0]?.data?.type === 'start' && newCanvasDataset?.nodes[1]?.data?.type === 'end'; return !isDefaultDataset; }; /** * Updates the user canvas document. * * Only update if the content has changed, to avoid infinite loop because this function is called when the CanvasContainer component renders (useEffect). * * If the user doesn't have the permissions to update the canvasRef, it'll fail. * The "Editor" role only allows the owner to edit its own documents. * * @param canvasRef Working canvas document reference that'll be modified * @param user * @param newCanvasDataset * @param previousCanvasDataset */ export const updateUserCanvas = async (canvasRef: TypeOfRef | undefined, user: Partial<UserSession>, newCanvasDataset: CanvasDataset, previousCanvasDataset: CanvasDataset | undefined): Promise<void> => { const client: Client = getUserClient(user); try { if (canvasRef) { console.info(`[updateUserCanvas] Update request triggered, checking if it should be done.`); // Checking if the local dataset has really changed if (hasDatasetChanged(newCanvasDataset)) { // Checking if the previous and new datasets (local) have changed helps avoiding unnecessary database updates const areLocalDatasetsDifferent = !isEqual(previousCanvasDataset, newCanvasDataset); // isEqual performs a deep comparison const localDiff = diff(previousCanvasDataset || {}, newCanvasDataset); const localDetailedDiff = detailedDiff(previousCanvasDataset || {}, newCanvasDataset); if (areLocalDatasetsDifferent) { // Even when the local dataset has changed, it might just be due to synchronizing from a remote change // In such case (which is frequent when there are several people working on the same doc), // checking the local vs remote dataset helps avoiding unnecessary updates, which in turn doesn't update all client // XXX This is very important in a real-time context, because if the remote DB is updated needlessly, // it'll in turn trigger a "version" event which will be received by ALL subscribed clients, // which in turn will update their own local dataset, which might not be up-to-date, which will trigger yet another update // It can get messy real quick and trigger infinite loops if not handled very carefully. const existingRemoteCanvasDatasetResult: CanvasDatasetResult = await client.query(Get(canvasRef)); const existingRemoteCanvasDataset: CanvasDataset = { // Consider only nodes/edges and ignore other fields to avoid false-positive difference that mustn't be taken into account nodes: existingRemoteCanvasDatasetResult.data?.nodes, edges: existingRemoteCanvasDatasetResult.data?.edges, }; const isRemoteDatasetsDifferent = !isEqual(existingRemoteCanvasDataset, newCanvasDataset); // isEqual performs a deep comparison const remoteDiff = diff(previousCanvasDataset || {}, newCanvasDataset); const remoteDetailedDiff = detailedDiff(previousCanvasDataset || {}, newCanvasDataset); if (isRemoteDatasetsDifferent) { console.debug('[updateUserCanvas] Updating canvas dataset in FaunaDB. Old:', previousCanvasDataset, 'new:', newCanvasDataset, 'diff:', remoteDiff, 'detailedDiff:', remoteDetailedDiff); try { const newCanvas: UpdateCanvas = { data: { ...newCanvasDataset, // Indicating who's the editor who's made the change, so we can safely ignore the "version:update" event we'll soon receive // when the DB will notify all subscribed editors about the update lastUpdatedBySessionEphemeralId: user.sessionEphemeralId as string, lastUpdatedByUserName: user?.email || `Anonymous#${user?.sessionEphemeralId?.substring(0, 8)}`, }, }; const updateCanvasDatasetResult: CanvasDatasetResult = await client.query<CanvasDatasetResult>(Update(canvasRef, newCanvas)); console.log('[updateUserCanvas] updateCanvasResult', updateCanvasDatasetResult); } catch (e) { console.error(`[updateUserCanvas] Error while updating canvas:`, e); // Handling concurrent updates errors by using the value from the remote // This makes sure we are up-to-date with the remote to avoid overwriting work done by other if (e?.message === 'contended transaction') { console.log('[updateUserCanvas] Concurrent update error detected, overwriting local state with remote state. Local:', newCanvasDataset, 'remote:', existingRemoteCanvasDataset); setRecoilExternalState(canvasDatasetSelector, existingRemoteCanvasDataset); } } } else { console.log(`[updateUserCanvas] Canvas remote dataset has not changed. Database update was aborted.`, 'diff:', remoteDiff, 'detailedDiff:', remoteDetailedDiff); } } else { console.log(`[updateUserCanvas] Canvas local dataset has not changed. Database update was aborted.`, 'diff:', localDiff, 'detailedDiff:', localDetailedDiff); } } else { console.log(`[updateUserCanvas] Canvas dataset has changed, although it's a default/empty dataset. Only non-default and non-empty changes are persisted to the DB (optimization). Database update was aborted.`); } } else { console.error(`[updateUserCanvas] "canvasRef" is undefined, update aborted.`, canvasRef); } } catch (e) { console.error(`[updateUserCanvas] Error while fetching canvas:`, e); } }; /** * Invoked when the streaming has been initialized, update the canvasDataset stored in Recoil. * * Due to this, we don't need to prefetch the dataset, as it is provided by the stream during initialization. * Will be called every time the stream is restarted. * * > The initial document when you start the stream. * > This event provides you with the current state of the document and will arrive after the start event and before other events. * * @param canvasDataset * * @see https://fauna.com/blog/live-ui-updates-with-faunas-real-time-document-streaming#defining-the-stream * @see https://docs.fauna.com/fauna/current/drivers/javascript.html */ export const onInit: OnStreamInit = (canvasDataset: CanvasDataset) => { // Starts the stream between the browser and the FaunaDB using the default canvas document console.log('onInit canvasDataset', canvasDataset); setRecoilExternalState(canvasDatasetSelector, canvasDataset); }; /** * Invoked when an update happens on the streamed document. * * We only care about the "update" event in this POC. Because "delete"/"create" events cannot happen. * * > When the data of the document changes, a new event will arrive that details the changes to the document. * * TODO Handle conflicts between changes from 3rd party (another editor) and current working document to avoid erasing the local document and losing changes * For another time, won't be part of the POC. * * @param canvasDatasetRemotelyUpdated * * @see https://fauna.com/blog/live-ui-updates-with-faunas-real-time-document-streaming#defining-the-stream * @see https://docs.fauna.com/fauna/current/drivers/javascript.html */ export const onUpdate: OnStreamedDocumentUpdate = (canvasDatasetRemotelyUpdated: CanvasDataset) => { setRecoilExternalState(canvasDatasetSelector, canvasDatasetRemotelyUpdated); };
the_stack
import {LocalActionBundle} from 'app/common/ActionBundle'; import {ActionGroup, MinimalActionGroup} from 'app/common/ActionGroup'; import {createEmptyActionSummary} from 'app/common/ActionSummary'; import {getSelectionDesc, UserAction} from 'app/common/DocActions'; import {DocState} from 'app/common/UserAPI'; import toPairs = require('lodash/toPairs'); import {summarizeAction} from './ActionSummary'; export interface ActionGroupOptions { // If set, inspect the action in detail in order to include a summary of // changes made within the action. Otherwise, the actionSummary returned is empty. summarize?: boolean; // The client for which the action group is being prepared, if known. clientId?: string; // Values returned by the action, if known. retValues?: any[]; // Set the 'internal' flag on the created actions, as inappropriate to undo. internal?: boolean; } /** * Metadata about an action that is needed for undo/redo stack. */ export interface ActionHistoryUndoInfoWithoutClient { otherId: number; linkId: number; rowIdHint: number; isUndo: boolean; } export interface ActionHistoryUndoInfo extends ActionHistoryUndoInfoWithoutClient { clientId: string; } export abstract class ActionHistory { /** * Initialize the ActionLog by reading the database. No other methods may be used until the * initialization completes. If used, their behavior is undefined. */ public abstract initialize(): Promise<void>; public abstract isInitialized(): boolean; /** Returns the actionNum of the next action we expect from the hub. */ public abstract getNextHubActionNum(): number; /** Returns the actionNum of the next local action should have. */ public abstract getNextLocalActionNum(): number; /** * Act as if we have already seen actionNum. getNextHubActionNum will return 1 plus this. * Only suitable for use if there are no unshared local actions. */ public abstract skipActionNum(actionNum: number): Promise<void>; /** Returns whether we have local unsent actions. */ public abstract haveLocalUnsent(): boolean; /** Returns whether we have any local actions that have been sent to the hub. */ public abstract haveLocalSent(): boolean; /** Returns whether we have any locally-applied actions. */ public abstract haveLocalActions(): boolean; /** Fetches and returns an array of all local unsent actions. */ public abstract fetchAllLocalUnsent(): Promise<LocalActionBundle[]>; /** Fetches and returns an array of all local actions (sent and unsent). */ public abstract fetchAllLocal(): Promise<LocalActionBundle[]>; /** Deletes all local-only actions, and resets the affected branch pointers. */ // TODO Should we actually delete, or be more git-like, only reset local branch pointer, and let // cleanup of unreferenced actions happen in a separate step? public abstract clearLocalActions(): Promise<void>; /** * Marks all actions returned from fetchAllLocalUnsent() as sent. Actions must be consecutive * starting with the the first local unsent action. */ public abstract markAsSent(actions: LocalActionBundle[]): Promise<void>; /** * Matches the action from the hub against the first sent local action. If it's the same action, * marks our action as "shared", i.e. accepted by the hub, and returns true. Else returns false. * If actionHash is null, accepts unconditionally. */ public abstract acceptNextSharedAction(actionHash: string|null): Promise<boolean>; /** Records a new local unsent action, after setting action.actionNum appropriately. */ public abstract recordNextLocalUnsent(action: LocalActionBundle): Promise<void>; /** Records a new action received from the hub, after setting action.actionNum appropriately. */ public abstract recordNextShared(action: LocalActionBundle): Promise<void>; /** * Get the most recent actions from the history. Results are ordered by * earliest actions first, later actions later. If `maxActions` is supplied, * at most that number of actions are returned. * * This method should be avoid in production, since it may convert and keep in memory many large * actions. (It has in the past led to exhausting memory and crashing node.) */ public abstract getRecentActions(maxActions?: number): Promise<LocalActionBundle[]>; /** * Same as getRecentActions, but converts each to an ActionGroup using asActionGroup with the * supplied options. */ public abstract getRecentActionGroups(maxActions: number, options: ActionGroupOptions): Promise<ActionGroup[]>; public abstract getRecentMinimalActionGroups(maxActions: number, clientId?: string): Promise<MinimalActionGroup[]>; /** * Get the most recent states from the history. States are just * actions without any content. Results are ordered by most recent * states first (careful, this is the opposite to getRecentActions). * If `maxStates` is supplied, at most that number of actions are * returned. */ public abstract getRecentStates(maxStates?: number): Promise<DocState[]>; /** * Get a list of actions, identified by their actionNum. Any actions that could not be * found are returned as undefined. */ public abstract getActions(actionNums: number[]): Promise<Array<LocalActionBundle|undefined>>; /** * Associates an action with a client. This association is expected to be transient, rather * than persistent. It should survive a client-side reload but not a server-side restart. */ public abstract setActionUndoInfo(actionHash: string, undoInfo: ActionHistoryUndoInfo): void; /** Check for any client associated with an action, identified by checksum */ public abstract getActionUndoInfo(actionHash: string): ActionHistoryUndoInfo | undefined; /** * Remove all stored actions except the last keepN and run the VACUUM command * to reduce the size of the SQLite file. * * @param {Int} keepN - The number of most recent actions to keep. The value must be at least 1, and * will default to 1 if not given. */ public abstract deleteActions(keepN: number): Promise<void>; } /** * Old helper to display the actionGroup in a human-readable way. Being maintained * to avoid having to change too much at once. */ export function humanDescription(actions: UserAction[]): string { const action = actions[0]; if (!action) { return ""; } let output = ''; // Common names for various action parameters const name = action[0]; const table = action[1]; const rows = action[2]; const colId = action[2]; const columns: any = action[3]; // TODO - better typing - but code may evaporate switch (name) { case 'UpdateRecord': case 'BulkUpdateRecord': case 'AddRecord': case 'BulkAddRecord': output = name + ' ' + getSelectionDesc(action, columns); break; case 'ApplyUndoActions': // Currently cannot display information about what action was undone, as the action comes // with the description of the "undo" message, which might be very different // Also, cannot currently properly log redos as they are not distinguished from others in any way // TODO: make an ApplyRedoActions type for redoing actions output = 'Undo Previous Action'; break; case 'InitNewDoc': output = 'Initialized new Document'; break; case 'AddColumn': output = 'Added column ' + colId + ' to ' + table; break; case 'RemoveColumn': output = 'Removed column ' + colId + ' from ' + table; break; case 'RemoveRecord': case 'BulkRemoveRecord': output = 'Removed record(s) ' + rows + ' from ' + table; break; case 'EvalCode': output = 'Evaluated Code ' + action[1]; break; case 'AddTable': output = 'Added table ' + table; break; case 'RemoveTable': output = 'Removed table ' + table; break; case 'ModifyColumn': // TODO: The Action Log currently only logs user actions, // But ModifyColumn/Rename Column are almost always triggered from the client // through a meta-table UpdateRecord. // so, this is a case where making use of explicit sandbox engine 'looged' actions // may be useful output = 'Modify column ' + colId + ", "; for (const [col, val] of toPairs(columns)) { output += col + ": " + val + ", "; } output += ' in table ' + table; break; case 'RenameColumn': { const newColId = action[3]; output = 'Renamed Column ' + colId + ' to ' + newColId + ' in ' + table; break; } default: output = name + ' [No Description]'; } // A period for good grammar output += '.'; return output; } /** * Convert an ActionBundle into an ActionGroup. ActionGroups are the representation of * actions on the client. * @param history: interface to action history * @param act: action to convert * @param options: options to construct the ActionGroup; see its documentation above. */ export function asActionGroup(history: ActionHistory, act: LocalActionBundle, options: ActionGroupOptions): ActionGroup { const {summarize, clientId} = options; const info = act.info[1]; const fromSelf = (act.actionHash && clientId) ? (history.getActionUndoInfo(act.actionHash)?.clientId === clientId) : false; const {extra: {primaryAction}, minimal: {rowIdHint, isUndo}} = getActionUndoInfoWithoutClient(act, options.retValues); return { actionNum: act.actionNum, actionHash: act.actionHash || "", desc: info.desc || humanDescription(act.userActions), actionSummary: summarize ? summarizeAction(act) : createEmptyActionSummary(), fromSelf, linkId: info.linkId, otherId: info.otherId, time: info.time, user: info.user, rowIdHint, primaryAction, isUndo, internal: options.internal || false, }; } export function asMinimalActionGroup(history: ActionHistory, act: {actionHash: string, actionNum: number}, clientId?: string): MinimalActionGroup { const undoInfo = act.actionHash ? history.getActionUndoInfo(act.actionHash) : undefined; const fromSelf = clientId ? (undoInfo?.clientId === clientId) : false; return { actionNum: act.actionNum, actionHash: act.actionHash || "", fromSelf, linkId: undoInfo?.linkId || 0, otherId: undoInfo?.otherId || 0, rowIdHint: undoInfo?.rowIdHint || 0, isUndo: undoInfo?.isUndo || false, }; } export function getActionUndoInfo(act: LocalActionBundle, clientId: string, retValues: any[]): ActionHistoryUndoInfo { return { ...getActionUndoInfoWithoutClient(act, retValues).minimal, clientId, }; } /** * Compute undo information from an action bundle and return values if available. * Results are returned as {minimal, extra} where core has information needed for minimal * action groups, and extra has information only needed for full action groups. */ function getActionUndoInfoWithoutClient(act: LocalActionBundle, retValues?: any[]) { let rowIdHint = 0; if (retValues) { // A hint for cursor position. This logic used to live on the client, but now trying to // limit how much the client looks at the internals of userActions. // In case of AddRecord, the returned value is rowId, which is the best cursorPos for Redo. for (let i = 0; i < act.userActions.length; i++) { const name = act.userActions[i][0]; const retValue = retValues[i]; if (name === 'AddRecord') { rowIdHint = retValue; break; } else if (name === 'BulkAddRecord') { rowIdHint = retValue[0]; break; } } } const info = act.info[1]; const primaryAction: string = String((act.userActions[0] || [""])[0]); const isUndo = primaryAction === 'ApplyUndoActions'; return { minimal: { rowIdHint, otherId: info.otherId, linkId: info.linkId, isUndo, }, extra: { primaryAction, }, }; }
the_stack
import path from 'path'; import * as constants from '../constants'; import { SchemaReference } from '../generate'; import { SchemaPostProcessor, ScopeType } from '../models'; import { saveAutoGeneratedSchemaRefs } from '../generate'; import { safeMkdir, writeJsonFile } from '../utils'; export const postProcessor: SchemaPostProcessor = async (namespace: string, apiVersion: string, schema: any) => { const extensionsDefinitions = extensionsDefinition(apiVersion); const references: SchemaReference[] = []; // Set schema.resourceDefinitions.virtualMachines_extensions.properties.properties = $extensionsProperties if (schema.resourceDefinitions?.virtualMachines_extensions?.properties?.properties) { schema.resourceDefinitions.virtualMachines_extensions.properties.properties = extensionsProperties(apiVersion); // set extensionsDefinitions.resourceDefinitions.virtualMachines_extensions = schema.resourceDefinitions.virtualMachines_extensions (extensionsDefinitions.resourceDefinitions as any).virtualMachines_extensions = schema.resourceDefinitions.virtualMachines_extensions; // remove schema.resourceDefinitions.virtualMachines_extensions delete schema.resourceDefinitions.virtualMachines_extensions; references.push({ scope: ScopeType.ResourceGroup, type: 'Microsoft.Compute/virtualMachines/extensions', reference: 'resourceDefinitions/virtualMachines_extensions', }); } // Set schema.resourceDefinitions.virtualMachineScaleSets_extensions.properties.properties = $extensionsProperties if (schema.resourceDefinitions?.virtualMachineScaleSets_extensions?.properties?.properties) { schema.resourceDefinitions.virtualMachineScaleSets_extensions.properties.properties = extensionsProperties(apiVersion); // set extensionsDefinitions.resourceDefinitions.virtualMachineScaleSets_extensions = schema.resourceDefinitions.virtualMachineScaleSets_extensions (extensionsDefinitions.resourceDefinitions as any).virtualMachineScaleSets_extensions = schema.resourceDefinitions.virtualMachineScaleSets_extensions; // remove schema.resourceDefinitions.virtualMachineScaleSets_extensions delete schema.resourceDefinitions.virtualMachineScaleSets_extensions references.push({ scope: ScopeType.ResourceGroup, type: 'Microsoft.Compute/virtualMachineScaleSets/extensions', reference: 'resourceDefinitions/virtualMachineScaleSets_extensions', }); } // Set schema.definitions.virtualMachines_extensions_childResource.properties.properties = $extensionsProperties if (schema.definitions.virtualMachines_extensions_childResource?.properties?.properties) { schema.definitions.virtualMachines_extensions_childResource.properties.properties = extensionsProperties(apiVersion); } // Set schema.definitions.VirtualMachineScaleSetExtension.properties.properties = $extensionsProperties if (schema.definitions.VirtualMachineScaleSetExtension?.properties?.properties) { schema.definitions.VirtualMachineScaleSetExtension.properties.properties = extensionsProperties(apiVersion); } // save extensionsDefinitions as Microsoft.Compute.Extensions.json const relativePath = `${apiVersion}/Microsoft.Compute.Extensions.json`; const extensionFile = path.join(constants.schemasBasePath, relativePath); await safeMkdir(path.dirname(extensionFile)); await writeJsonFile(extensionFile, extensionsDefinitions); await saveAutoGeneratedSchemaRefs([{ relativePath, references, }]); } const extensionsDefinition = (apiVersion: string) => ( { "id": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#`, "$schema": "http://json-schema.org/draft-04/schema#", "title": "Microsoft.Compute.Extensions", "description": "Microsoft Compute Extensions Resource Types", "resourceDefinitions": {}, "definitions": { "genericExtension": { "type": "object", "properties": { "publisher": { "type": "string", "minLength": 1, "description": "Microsoft.Compute/extensions - Publisher" }, "type": { "type": "string", "minLength": 1, "description": "Microsoft.Compute/extensions - Type" }, "typeHandlerVersion": { "type": "string", "minLength": 1, "description": "Microsoft.Compute/extensions - Type handler version" }, "settings": { "oneOf": [ { "type": "object" }, { "$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression" } ], "description": "Microsoft.Compute/extensions - Settings" } }, "required": [ "publisher", "type", "typeHandlerVersion", "settings" ] }, "iaaSDiagnostics": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.Diagnostics" ] }, "type": { "enum": [ "IaaSDiagnostics" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "xmlCfg": { "type": "string" }, "StorageAccount": { "type": "string" } }, "required": [ "xmlCfg", "StorageAccount" ] }, "protectedSettings": { "type": "object", "properties": { "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" }, "storageAccountEndPoint": { "type": "string" } }, "required": [ "storageAccountName", "storageAccountKey", "storageAccountEndPoint" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "iaaSAntimalware": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.Security" ] }, "type": { "enum": [ "IaaSAntimalware" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "AntimalwareEnabled": { "type": "boolean" }, "Exclusions": { "type": "object", "properties": { "Paths": { "type": "string" }, "Extensions": { "type": "string" }, "Processes": { "type": "string" } }, "required": [ "Paths", "Extensions", "Processes" ] }, "RealtimeProtectionEnabled": { "enum": [ "true", "false" ] }, "ScheduledScanSettings": { "type": "object", "properties": { "isEnabled": { "enum": [ "true", "false" ] }, "scanType": { "type": "string" }, "day": { "type": "string" }, "time": { "type": "string" } }, "required": [ "isEnabled", "scanType", "day", "time" ] } }, "required": [ "AntimalwareEnabled", "Exclusions", "RealtimeProtectionEnabled", "ScheduledScanSettings" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "customScriptExtension": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Compute" ] }, "type": { "enum": [ "CustomScriptExtension" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "fileUris": { "type": "array", "items": { "type": "string" } }, "commandToExecute": { "type": "string" } }, "required": [ "commandToExecute" ] }, "protectedSettings": { "type": "object", "properties": { "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" } } } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "customScriptForLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.OSTCExtensions" ] }, "type": { "enum": [ "CustomScriptForLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "fileUris": { "type": "array", "items": { "type": "string" } } } }, "protectedSettings": { "type": "object", "properties": { "commandToExecute": { "type": "string" }, "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" } }, "required": [ "commandToExecute" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "linuxDiagnostic": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.OSTCExtensions" ] }, "type": { "enum": [ "LinuxDiagnostic" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "enableSyslog": { "type": "string" }, "mdsdHttpProxy": { "type": "string" }, "perCfg": { "type": "array" }, "fileCfg": { "type": "array" }, "xmlCfg": { "type": "string" }, "ladCfg": { "type": "object" }, "syslogCfg": { "type": "string" }, "eventVolume": { "type": "string" }, "mdsdCfg": { "type": "string" } } }, "protectedSettings": { "type": "object", "properties": { "mdsdHttpProxy": { "type": "string" }, "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" }, "storageAccountEndPoint": { "type": "string" } }, "required": [ "storageAccountName", "storageAccountKey" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "vmAccessForLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.OSTCExtensions" ] }, "type": { "enum": [ "VMAccessForLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "check_disk": { "type": "boolean" }, "repair_disk": { "type": "boolean" } } }, "protectedSettings": { "type": "object", "properties": { "username": { "type": "string" }, "password": { "type": "string" }, "ssh_key": { "type": "string" }, "reset_ssh": { "type": "string" }, "remove_user": { "type": "string" }, "expiration": { "type": "string" } }, "required": [ "username", "password", "ssh_key", "reset_ssh", "remove_user", "expiration" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "bgInfo": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Compute" ] }, "type": { "enum": [ "bginfo" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion" ] }, "vmAccessAgent": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Compute" ] }, "type": { "enum": [ "VMAccessAgent" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "username": { "type": "string" } } }, "protectedSettings": { "type": "object", "properties": { "password": { "type": "string" } } } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "dscExtension": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Powershell" ] }, "type": { "enum": [ "DSC" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "modulesUrl": { "type": "string" }, "configurationFunction": { "type": "string" }, "properties": { "type": "string" }, "wmfVersion": { "type": "string" }, "privacy": { "type": "object", "properties": { "dataCollection": { "type": "string" } } } }, "required": [ "modulesUrl", "configurationFunction" ] }, "protectedSettings": { "type": "object", "properties": { "dataBlobUri": { "type": "string" } } } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "acronisBackupLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Acronis.Backup" ] }, "type": { "enum": [ "AcronisBackupLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "absURL": { "type": "string" } }, "required": [ "absURL" ] }, "protectedSettings": { "type": "object", "properties": { "userLogin": { "type": "string" }, "userPassword": { "type": "string" } }, "required": [ "userLogin", "userPassword" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "acronisBackup": { "type": "object", "properties": { "publisher": { "enum": [ "Acronis.Backup" ] }, "type": { "enum": [ "AcronisBackup" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "absURL": { "type": "string" } }, "required": [ "absURL" ] }, "protectedSettings": { "type": "object", "properties": { "userLogin": { "type": "string" }, "userPassword": { "type": "string" } }, "required": [ "userLogin", "userPassword" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "linuxChefClient": { "type": "object", "properties": { "publisher": { "enum": [ "Chef.Bootstrap.WindowsAzure" ] }, "type": { "enum": [ "LinuxChefClient" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "bootstrap_version": { "type": "string" }, "bootstrap_options": { "type": "object", "properties": { "chef_node_name": { "type": "string" }, "chef_server_url": { "type": "string" }, "validation_client_name": { "type": "string" }, "node_ssl_verify_mode": { "type": "string" }, "environment": { "type": "string" } }, "required": [ "chef_node_name", "chef_server_url", "validation_client_name", "node_ssl_verify_mode", "environment" ] }, "runlist": { "type": "string" }, "client_rb": { "type": "string" } } }, "protectedSettings": { "type": "object", "properties": { "validation_key": { "type": "string" }, "chef_server_crt": { "type": "string" }, "secret": { "type": "string" } }, "required": [ "validation_key", "chef_server_crt", "secret" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "chefClient": { "type": "object", "properties": { "publisher": { "enum": [ "Chef.Bootstrap.WindowsAzure" ] }, "type": { "enum": [ "ChefClient" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "bootstrap_options": { "type": "object", "properties": { "chef_node_name": { "type": "string" }, "chef_server_url": { "type": "string" }, "validation_client_name": { "type": "string" }, "node_ssl_verify_mode": { "type": "string" }, "environment": { "type": "string" } }, "required": [ "chef_node_name", "chef_server_url", "validation_client_name", "node_ssl_verify_mode", "environment" ] }, "runlist": { "type": "string" }, "client_rb": { "type": "string" } } }, "protectedSettings": { "type": "object", "properties": { "validation_key": { "type": "string" }, "chef_server_crt": { "type": "string" }, "secret": { "type": "string" } }, "required": [ "validation_key", "chef_server_crt", "secret" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "datadogLinuxAgent": { "type": "object", "properties": { "publisher": { "enum": [ "Datadog.Agent" ] }, "type": { "enum": [ "DatadogLinuxAgent" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "api_key": { "type": "string" } }, "required": [ "api_key" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "datadogWindowsAgent": { "type": "object", "properties": { "publisher": { "enum": [ "Datadog.Agent" ] }, "type": { "enum": [ "DatadogWindowsAgent" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "api_key": { "type": "string" } }, "required": [ "api_key" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "dockerExtension": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.Extensions" ] }, "type": { "enum": [ "DockerExtension" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "docker": { "type": "object", "properties": { "port": { "type": "string" } }, "required": [ "port" ] } }, "required": [ "docker" ] }, "protectedSettings": { "type": "object", "properties": { "certs": { "type": "object", "properties": { "ca": { "type": "string" }, "cert": { "type": "string" }, "key": { "type": "string" } }, "required": [ "ca", "cert", "key" ] } }, "required": [ "certs" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "dynatraceLinux": { "type": "object", "properties": { "publisher": { "enum": [ "dynatrace.ruxit" ] }, "type": { "enum": [ "ruxitAgentLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "tenantId": { "type": "string" }, "token": { "type": "string" } }, "required": [ "tenantId", "token" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "dynatraceWindows": { "type": "object", "properties": { "publisher": { "enum": [ "dynatrace.ruxit" ] }, "type": { "enum": [ "ruxitAgentWindows" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "tenantId": { "type": "string" }, "token": { "type": "string" } }, "required": [ "tenantId", "token" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "eset": { "type": "object", "properties": { "publisher": { "enum": [ "ESET" ] }, "type": { "enum": [ "FileSecurity" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "LicenseKey": { "type": "string" }, "Install-RealtimeProtection": { "type": "boolean" }, "Install-ProtocolFiltering": { "type": "boolean" }, "Install-DeviceControl": { "type": "boolean" }, "Enable-Cloud": { "type": "boolean" }, "Enable-PUA": { "type": "boolean" }, "ERAAgentCfgUrl": { "type": "string" } }, "required": [ "LicenseKey", "Install-RealtimeProtection", "Install-ProtocolFiltering", "Install-DeviceControl", "Enable-Cloud", "Enable-PUA", "ERAAgentCfgUrl" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "hpeSecurityApplicationDefender": { "type": "object", "properties": { "publisher": { "enum": [ "HPE.Security.ApplicationDefender" ] }, "type": { "enum": [ "DotnetAgent" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "protectedSettings": { "type": "object", "properties": { "key": { "type": "string" }, "serverURL": { "type": "string" } }, "required": [ "key", "serverURL" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "protectedSettings" ] }, "puppetAgent": { "type": "object", "properties": { "publisher": { "enum": [ "Puppet" ] }, "type": { "enum": [ "PuppetAgent" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "protectedSettings": { "type": "object", "properties": { "PUPPET_MASTER_SERVER": { "type": "string" } }, "required": [ "PUPPET_MASTER_SERVER" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "protectedSettings" ] }, "site24x7LinuxServerExtn": { "type": "object", "properties": { "publisher": { "enum": [ "Site24x7" ] }, "type": { "enum": [ "Site24x7LinuxServerExtn" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "site24x7AgentType": { "enum": [ "azurevmextnlinuxserver" ] } } }, "protectedSettings": { "type": "object", "properties": { "site24x7LicenseKey": { "type": "string" } }, "required": [ "site24x7LicenseKey" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "site24x7WindowsServerExtn": { "type": "object", "properties": { "publisher": { "enum": [ "Site24x7" ] }, "type": { "enum": [ "Site24x7WindowsServerExtn" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "site24x7AgentType": { "enum": [ "azurevmextnwindowsserver" ] } } }, "protectedSettings": { "type": "object", "properties": { "site24x7LicenseKey": { "type": "string" } }, "required": [ "site24x7LicenseKey" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "site24x7ApmInsightExtn": { "type": "object", "properties": { "publisher": { "enum": [ "Site24x7" ] }, "type": { "enum": [ "Site24x7ApmInsightExtn" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "site24x7AgentType": { "enum": [ "azurevmextnapminsightclassic" ] } } }, "protectedSettings": { "type": "object", "properties": { "site24x7LicenseKey": { "type": "string" } }, "required": [ "site24x7LicenseKey" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "trendMicroDSALinux": { "type": "object", "properties": { "publisher": { "enum": [ "TrendMicro.DeepSecurity" ] }, "type": { "enum": [ "TrendMicroDSALinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "DSMname": { "type": "string" }, "DSMport": { "type": "string" }, "policyNameorID": { "type": "string" } }, "required": [ "DSMname", "DSMport" ] }, "protectedSettings": { "type": "object", "properties": { "tenantID": { "type": "string" }, "tenantPassword": { "type": "string" } }, "required": [ "tenantID", "tenantPassword" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "trendMicroDSA": { "type": "object", "properties": { "publisher": { "enum": [ "TrendMicro.DeepSecurity" ] }, "type": { "enum": [ "TrendMicroDSA" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "DSMname": { "type": "string" }, "DSMport": { "type": "string" }, "policyNameorID": { "type": "string" } }, "required": [ "DSMname", "DSMport" ] }, "protectedSettings": { "type": "object", "properties": { "tenantID": { "type": "string" }, "tenantPassword": { "type": "string" } }, "required": [ "tenantID", "tenantPassword" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "bmcCtmAgentLinux": { "type": "object", "properties": { "publisher": { "enum": [ "ctm.bmc.com" ] }, "type": { "enum": [ "BmcCtmAgentLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "Control-M Server Name": { "type": "string" }, "Agent Port": { "type": "string" }, "Host Group": { "type": "string" }, "User Account": { "type": "string" } }, "required": [ "Control-M Server Name", "Agent Port", "Host Group", "User Account" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "bmcCtmAgentWindows": { "type": "object", "properties": { "publisher": { "enum": [ "bmc.ctm" ] }, "type": { "enum": [ "AgentWinExt" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "Control-M Server Name": { "type": "string" }, "Agent Port": { "type": "string" }, "Host Group": { "type": "string" } }, "required": [ "Control-M Server Name", "Agent Port", "Host Group" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "OSPatchingForLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.OSTCExtensions" ] }, "type": { "enum": [ "OSPatchingForLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "disabled": { "type": "boolean" }, "stop": { "type": "boolean" }, "installDuration": { "type": "string" }, "intervalOfWeeks": { "type": "number" }, "dayOfWeek": { "type": "string" }, "startTime": { "type": "string" }, "rebootAfterPatch": { "type": "string" }, "category": { "type": "string" }, "oneoff": { "type": "boolean" }, "local": { "type": "boolean" }, "idleTestScript": { "type": "string" }, "healthyTestScript": { "type": "string" }, "distUpgradeList": { "type": "string" }, "distUpgradeAll": { "type": "boolean" }, "vmStatusTest": { "type": "object" } }, "required": [ "disabled", "stop" ] }, "protectedSettings": { "type": "object", "properties": { "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" } } } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "VMSnapshot": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.RecoveryServices" ] }, "type": { "enum": [ "VMSnapshot" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "locale": { "type": "string" }, "taskId": { "type": "string" }, "commandToExecute": { "type": "string" }, "objectStr": { "type": "string" }, "logsBlobUri": { "type": "string" }, "statusBlobUri": { "type": "string" }, "commandStartTimeUTCTicks": { "type": "string" }, "vmType": { "type": "string" } }, "required": [ "locale", "taskId", "commandToExecute", "objectStr", "logsBlobUri", "statusBlobUri", "commandStartTimeUTCTicks", "vmType" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "VMSnapshotLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.RecoveryServices" ] }, "type": { "enum": [ "VMSnapshotLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "locale": { "type": "string" }, "taskId": { "type": "string" }, "commandToExecute": { "type": "string" }, "objectStr": { "type": "string" }, "logsBlobUri": { "type": "string" }, "statusBlobUri": { "type": "string" }, "commandStartTimeUTCTicks": { "type": "string" }, "vmType": { "type": "string" } }, "required": [ "locale", "taskId", "commandToExecute", "objectStr", "logsBlobUri", "statusBlobUri", "commandStartTimeUTCTicks", "vmType" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings" ] }, "customScript": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.Extensions" ] }, "type": { "enum": [ "CustomScript" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" }, "settings": { "type": "object", "properties": { "fileUris": { "type": "array", "items": { "type": "string" } } }, "required": [ "fileUris" ] }, "protectedSettings": { "type": "object", "properties": { "storageAccountName": { "type": "string" }, "storageAccountKey": { "type": "string" }, "commandToExecute": { "type": "string" } }, "required": [ "storageAccountName", "storageAccountKey", "commandToExecute" ] } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion", "settings", "protectedSettings" ] }, "networkWatcherAgentWindows": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.NetworkWatcher" ] }, "type": { "enum": [ "NetworkWatcherAgentWindows" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion" ] }, "networkWatcherAgentLinux": { "type": "object", "properties": { "publisher": { "enum": [ "Microsoft.Azure.NetworkWatcher" ] }, "type": { "enum": [ "NetworkWatcherAgentLinux" ] }, "typeHandlerVersion": { "type": "string", "minLength": 1 }, "autoUpgradeMinorVersion": { "type": "boolean" } }, "required": [ "publisher", "type", "typeHandlerVersion", "autoUpgradeMinorVersion" ] } } } ); const extensionsProperties = (apiVersion: string) => ( { "anyOf": [ { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/genericExtension` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/iaaSDiagnostics` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/iaaSAntimalware` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/customScriptExtension` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/customScriptForLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/linuxDiagnostic` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/vmAccessForLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/bgInfo` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/vmAccessAgent` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/dscExtension` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/acronisBackupLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/acronisBackup` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/linuxChefClient` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/chefClient` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/datadogLinuxAgent` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/datadogWindowsAgent` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/dockerExtension` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/dynatraceLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/dynatraceWindows` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/eset` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/hpeSecurityApplicationDefender` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/puppetAgent` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/site24x7LinuxServerExtn` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/site24x7WindowsServerExtn` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/site24x7ApmInsightExtn` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/trendMicroDSALinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/trendMicroDSA` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/bmcCtmAgentLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/bmcCtmAgentWindows` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/OSPatchingForLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/VMSnapshot` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/VMSnapshotLinux` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/customScript` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/networkWatcherAgentWindows` }, { "$ref": `https://schema.management.azure.com/schemas/${apiVersion}/Microsoft.Compute.Extensions.json#/definitions/networkWatcherAgentLinux` } ] });
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 IoTTwinMaker extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: IoTTwinMaker.Types.ClientConfiguration) config: Config & IoTTwinMaker.Types.ClientConfiguration; /** * Sets values for multiple time series properties. */ batchPutPropertyValues(params: IoTTwinMaker.Types.BatchPutPropertyValuesRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.BatchPutPropertyValuesResponse) => void): Request<IoTTwinMaker.Types.BatchPutPropertyValuesResponse, AWSError>; /** * Sets values for multiple time series properties. */ batchPutPropertyValues(callback?: (err: AWSError, data: IoTTwinMaker.Types.BatchPutPropertyValuesResponse) => void): Request<IoTTwinMaker.Types.BatchPutPropertyValuesResponse, AWSError>; /** * Creates a component type. TwinMaker is in public preview and is subject to change. */ createComponentType(params: IoTTwinMaker.Types.CreateComponentTypeRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateComponentTypeResponse) => void): Request<IoTTwinMaker.Types.CreateComponentTypeResponse, AWSError>; /** * Creates a component type. TwinMaker is in public preview and is subject to change. */ createComponentType(callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateComponentTypeResponse) => void): Request<IoTTwinMaker.Types.CreateComponentTypeResponse, AWSError>; /** * Creates an entity. */ createEntity(params: IoTTwinMaker.Types.CreateEntityRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateEntityResponse) => void): Request<IoTTwinMaker.Types.CreateEntityResponse, AWSError>; /** * Creates an entity. */ createEntity(callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateEntityResponse) => void): Request<IoTTwinMaker.Types.CreateEntityResponse, AWSError>; /** * Creates a scene. */ createScene(params: IoTTwinMaker.Types.CreateSceneRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateSceneResponse) => void): Request<IoTTwinMaker.Types.CreateSceneResponse, AWSError>; /** * Creates a scene. */ createScene(callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateSceneResponse) => void): Request<IoTTwinMaker.Types.CreateSceneResponse, AWSError>; /** * Creates a workplace. */ createWorkspace(params: IoTTwinMaker.Types.CreateWorkspaceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateWorkspaceResponse) => void): Request<IoTTwinMaker.Types.CreateWorkspaceResponse, AWSError>; /** * Creates a workplace. */ createWorkspace(callback?: (err: AWSError, data: IoTTwinMaker.Types.CreateWorkspaceResponse) => void): Request<IoTTwinMaker.Types.CreateWorkspaceResponse, AWSError>; /** * Deletes a component type. */ deleteComponentType(params: IoTTwinMaker.Types.DeleteComponentTypeRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteComponentTypeResponse) => void): Request<IoTTwinMaker.Types.DeleteComponentTypeResponse, AWSError>; /** * Deletes a component type. */ deleteComponentType(callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteComponentTypeResponse) => void): Request<IoTTwinMaker.Types.DeleteComponentTypeResponse, AWSError>; /** * Deletes an entity. */ deleteEntity(params: IoTTwinMaker.Types.DeleteEntityRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteEntityResponse) => void): Request<IoTTwinMaker.Types.DeleteEntityResponse, AWSError>; /** * Deletes an entity. */ deleteEntity(callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteEntityResponse) => void): Request<IoTTwinMaker.Types.DeleteEntityResponse, AWSError>; /** * Deletes a scene. */ deleteScene(params: IoTTwinMaker.Types.DeleteSceneRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteSceneResponse) => void): Request<IoTTwinMaker.Types.DeleteSceneResponse, AWSError>; /** * Deletes a scene. */ deleteScene(callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteSceneResponse) => void): Request<IoTTwinMaker.Types.DeleteSceneResponse, AWSError>; /** * Deletes a workspace. */ deleteWorkspace(params: IoTTwinMaker.Types.DeleteWorkspaceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteWorkspaceResponse) => void): Request<IoTTwinMaker.Types.DeleteWorkspaceResponse, AWSError>; /** * Deletes a workspace. */ deleteWorkspace(callback?: (err: AWSError, data: IoTTwinMaker.Types.DeleteWorkspaceResponse) => void): Request<IoTTwinMaker.Types.DeleteWorkspaceResponse, AWSError>; /** * Retrieves information about a component type. */ getComponentType(params: IoTTwinMaker.Types.GetComponentTypeRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetComponentTypeResponse) => void): Request<IoTTwinMaker.Types.GetComponentTypeResponse, AWSError>; /** * Retrieves information about a component type. */ getComponentType(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetComponentTypeResponse) => void): Request<IoTTwinMaker.Types.GetComponentTypeResponse, AWSError>; /** * Retrieves information about an entity. */ getEntity(params: IoTTwinMaker.Types.GetEntityRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetEntityResponse) => void): Request<IoTTwinMaker.Types.GetEntityResponse, AWSError>; /** * Retrieves information about an entity. */ getEntity(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetEntityResponse) => void): Request<IoTTwinMaker.Types.GetEntityResponse, AWSError>; /** * Gets the property values for a component, component type, entity, or workspace. You must specify a value for either componentName, componentTypeId, entityId, or workspaceId. */ getPropertyValue(params: IoTTwinMaker.Types.GetPropertyValueRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetPropertyValueResponse) => void): Request<IoTTwinMaker.Types.GetPropertyValueResponse, AWSError>; /** * Gets the property values for a component, component type, entity, or workspace. You must specify a value for either componentName, componentTypeId, entityId, or workspaceId. */ getPropertyValue(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetPropertyValueResponse) => void): Request<IoTTwinMaker.Types.GetPropertyValueResponse, AWSError>; /** * Retrieves information about the history of a time series property value for a component, component type, entity, or workspace. You must specify a value for workspaceId. For entity-specific queries, specify values for componentName and entityId. For cross-entity quries, specify a value for componentTypeId. */ getPropertyValueHistory(params: IoTTwinMaker.Types.GetPropertyValueHistoryRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetPropertyValueHistoryResponse) => void): Request<IoTTwinMaker.Types.GetPropertyValueHistoryResponse, AWSError>; /** * Retrieves information about the history of a time series property value for a component, component type, entity, or workspace. You must specify a value for workspaceId. For entity-specific queries, specify values for componentName and entityId. For cross-entity quries, specify a value for componentTypeId. */ getPropertyValueHistory(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetPropertyValueHistoryResponse) => void): Request<IoTTwinMaker.Types.GetPropertyValueHistoryResponse, AWSError>; /** * Retrieves information about a scene. */ getScene(params: IoTTwinMaker.Types.GetSceneRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetSceneResponse) => void): Request<IoTTwinMaker.Types.GetSceneResponse, AWSError>; /** * Retrieves information about a scene. */ getScene(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetSceneResponse) => void): Request<IoTTwinMaker.Types.GetSceneResponse, AWSError>; /** * Retrieves information about a workspace. */ getWorkspace(params: IoTTwinMaker.Types.GetWorkspaceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.GetWorkspaceResponse) => void): Request<IoTTwinMaker.Types.GetWorkspaceResponse, AWSError>; /** * Retrieves information about a workspace. */ getWorkspace(callback?: (err: AWSError, data: IoTTwinMaker.Types.GetWorkspaceResponse) => void): Request<IoTTwinMaker.Types.GetWorkspaceResponse, AWSError>; /** * Lists all component types in a workspace. */ listComponentTypes(params: IoTTwinMaker.Types.ListComponentTypesRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.ListComponentTypesResponse) => void): Request<IoTTwinMaker.Types.ListComponentTypesResponse, AWSError>; /** * Lists all component types in a workspace. */ listComponentTypes(callback?: (err: AWSError, data: IoTTwinMaker.Types.ListComponentTypesResponse) => void): Request<IoTTwinMaker.Types.ListComponentTypesResponse, AWSError>; /** * Lists all entities in a workspace. */ listEntities(params: IoTTwinMaker.Types.ListEntitiesRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.ListEntitiesResponse) => void): Request<IoTTwinMaker.Types.ListEntitiesResponse, AWSError>; /** * Lists all entities in a workspace. */ listEntities(callback?: (err: AWSError, data: IoTTwinMaker.Types.ListEntitiesResponse) => void): Request<IoTTwinMaker.Types.ListEntitiesResponse, AWSError>; /** * Lists all scenes in a workspace. */ listScenes(params: IoTTwinMaker.Types.ListScenesRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.ListScenesResponse) => void): Request<IoTTwinMaker.Types.ListScenesResponse, AWSError>; /** * Lists all scenes in a workspace. */ listScenes(callback?: (err: AWSError, data: IoTTwinMaker.Types.ListScenesResponse) => void): Request<IoTTwinMaker.Types.ListScenesResponse, AWSError>; /** * Lists all tags associated with a resource. */ listTagsForResource(params: IoTTwinMaker.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.ListTagsForResourceResponse) => void): Request<IoTTwinMaker.Types.ListTagsForResourceResponse, AWSError>; /** * Lists all tags associated with a resource. */ listTagsForResource(callback?: (err: AWSError, data: IoTTwinMaker.Types.ListTagsForResourceResponse) => void): Request<IoTTwinMaker.Types.ListTagsForResourceResponse, AWSError>; /** * Retrieves information about workspaces in the current account. */ listWorkspaces(params: IoTTwinMaker.Types.ListWorkspacesRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.ListWorkspacesResponse) => void): Request<IoTTwinMaker.Types.ListWorkspacesResponse, AWSError>; /** * Retrieves information about workspaces in the current account. */ listWorkspaces(callback?: (err: AWSError, data: IoTTwinMaker.Types.ListWorkspacesResponse) => void): Request<IoTTwinMaker.Types.ListWorkspacesResponse, AWSError>; /** * Adds tags to a resource. */ tagResource(params: IoTTwinMaker.Types.TagResourceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.TagResourceResponse) => void): Request<IoTTwinMaker.Types.TagResourceResponse, AWSError>; /** * Adds tags to a resource. */ tagResource(callback?: (err: AWSError, data: IoTTwinMaker.Types.TagResourceResponse) => void): Request<IoTTwinMaker.Types.TagResourceResponse, AWSError>; /** * Removes tags from a resource. */ untagResource(params: IoTTwinMaker.Types.UntagResourceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.UntagResourceResponse) => void): Request<IoTTwinMaker.Types.UntagResourceResponse, AWSError>; /** * Removes tags from a resource. */ untagResource(callback?: (err: AWSError, data: IoTTwinMaker.Types.UntagResourceResponse) => void): Request<IoTTwinMaker.Types.UntagResourceResponse, AWSError>; /** * Updates information in a component type. */ updateComponentType(params: IoTTwinMaker.Types.UpdateComponentTypeRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateComponentTypeResponse) => void): Request<IoTTwinMaker.Types.UpdateComponentTypeResponse, AWSError>; /** * Updates information in a component type. */ updateComponentType(callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateComponentTypeResponse) => void): Request<IoTTwinMaker.Types.UpdateComponentTypeResponse, AWSError>; /** * Updates an entity. */ updateEntity(params: IoTTwinMaker.Types.UpdateEntityRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateEntityResponse) => void): Request<IoTTwinMaker.Types.UpdateEntityResponse, AWSError>; /** * Updates an entity. */ updateEntity(callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateEntityResponse) => void): Request<IoTTwinMaker.Types.UpdateEntityResponse, AWSError>; /** * Updates a scene. */ updateScene(params: IoTTwinMaker.Types.UpdateSceneRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateSceneResponse) => void): Request<IoTTwinMaker.Types.UpdateSceneResponse, AWSError>; /** * Updates a scene. */ updateScene(callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateSceneResponse) => void): Request<IoTTwinMaker.Types.UpdateSceneResponse, AWSError>; /** * Updates a workspace. */ updateWorkspace(params: IoTTwinMaker.Types.UpdateWorkspaceRequest, callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateWorkspaceResponse) => void): Request<IoTTwinMaker.Types.UpdateWorkspaceResponse, AWSError>; /** * Updates a workspace. */ updateWorkspace(callback?: (err: AWSError, data: IoTTwinMaker.Types.UpdateWorkspaceResponse) => void): Request<IoTTwinMaker.Types.UpdateWorkspaceResponse, AWSError>; } declare namespace IoTTwinMaker { export interface BatchPutPropertyError { /** * An object that contains information about errors returned by the BatchPutProperty action. */ entry: PropertyValueEntry; /** * The error code. */ errorCode: String; /** * The error message. */ errorMessage: String; } export interface BatchPutPropertyErrorEntry { /** * A list of objects that contain information about errors returned by the BatchPutProperty action. */ errors: Errors; } export interface BatchPutPropertyValuesRequest { /** * An object that maps strings to the property value entries to set. Each string in the mapping must be unique to this object. */ entries: Entries; /** * The ID of the workspace that contains the properties to set. */ workspaceId: Id; } export interface BatchPutPropertyValuesResponse { /** * Entries that caused errors in the batch put operation. */ errorEntries: ErrorEntries; } export type Boolean = boolean; export interface ComponentRequest { /** * The ID of the component type. */ componentTypeId?: ComponentTypeId; /** * The description of the component request. */ description?: Description; /** * An object that maps strings to the properties to set in the component type. Each string in the mapping must be unique to this object. */ properties?: PropertyRequests; } export interface ComponentResponse { /** * The name of the component. */ componentName?: Name; /** * The ID of the component type. */ componentTypeId?: ComponentTypeId; /** * The name of the property definition set in the request. */ definedIn?: String; /** * The description of the component type. */ description?: Description; /** * An object that maps strings to the properties to set in the component type. Each string in the mapping must be unique to this object. */ properties?: PropertyResponses; /** * The status of the component type. */ status?: Status; } export type ComponentTypeId = string; export type ComponentTypeSummaries = ComponentTypeSummary[]; export interface ComponentTypeSummary { /** * The ARN of the component type. */ arn: TwinMakerArn; /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The date and time when the component type was created. */ creationDateTime: Timestamp; /** * The description of the component type. */ description?: Description; /** * The current status of the component type. */ status?: Status; /** * The date and time when the component type was last updated. */ updateDateTime: Timestamp; } export interface ComponentUpdateRequest { /** * The ID of the component type. */ componentTypeId?: ComponentTypeId; /** * The description of the component type. */ description?: Description; /** * An object that maps strings to the properties to set in the component type update. Each string in the mapping must be unique to this object. */ propertyUpdates?: PropertyRequests; /** * The update type of the component update request. */ updateType?: ComponentUpdateType; } export type ComponentUpdateType = "CREATE"|"UPDATE"|"DELETE"|string; export type ComponentUpdatesMapRequest = {[key: string]: ComponentUpdateRequest}; export type ComponentsMap = {[key: string]: ComponentResponse}; export type ComponentsMapRequest = {[key: string]: ComponentRequest}; export type Configuration = {[key: string]: Value}; export interface CreateComponentTypeRequest { /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The description of the component type. */ description?: Description; /** * Specifies the parent component type to extend. */ extendsFrom?: ExtendsFrom; /** * An object that maps strings to the functions in the component type. Each string in the mapping must be unique to this object. */ functions?: FunctionsRequest; /** * A Boolean value that specifies whether an entity can have more than one component of this type. */ isSingleton?: Boolean; /** * An object that maps strings to the property definitions in the component type. Each string in the mapping must be unique to this object. */ propertyDefinitions?: PropertyDefinitionsRequest; /** * Metadata that you can use to manage the component type. */ tags?: TagMap; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface CreateComponentTypeResponse { /** * The ARN of the component type. */ arn: TwinMakerArn; /** * The date and time when the entity was created. */ creationDateTime: Timestamp; /** * The current state of the component type. */ state: State; } export interface CreateEntityRequest { /** * An object that maps strings to the components in the entity. Each string in the mapping must be unique to this object. */ components?: ComponentsMapRequest; /** * The description of the entity. */ description?: Description; /** * The ID of the entity. */ entityId?: EntityId; /** * The name of the entity. */ entityName: EntityName; /** * The ID of the entity's parent entity. */ parentEntityId?: ParentEntityId; /** * Metadata that you can use to manage the entity. */ tags?: TagMap; /** * The ID of the workspace that contains the entity. */ workspaceId: Id; } export interface CreateEntityResponse { /** * The ARN of the entity. */ arn: TwinMakerArn; /** * The date and time when the entity was created. */ creationDateTime: Timestamp; /** * The ID of the entity. */ entityId: EntityId; /** * The current state of the entity. */ state: State; } export interface CreateSceneRequest { /** * A list of capabilities that the scene uses to render itself. */ capabilities?: SceneCapabilities; /** * The relative path that specifies the location of the content definition file. */ contentLocation: S3Url; /** * The description for this scene. */ description?: Description; /** * The ID of the scene. */ sceneId: Id; /** * Metadata that you can use to manage the scene. */ tags?: TagMap; /** * The ID of the workspace that contains the scene. */ workspaceId: Id; } export interface CreateSceneResponse { /** * The ARN of the scene. */ arn: TwinMakerArn; /** * The date and time when the scene was created. */ creationDateTime: Timestamp; } export interface CreateWorkspaceRequest { /** * The description of the workspace. */ description?: Description; /** * The ARN of the execution role associated with the workspace. */ role: RoleArn; /** * The ARN of the S3 bucket where resources associated with the workspace are stored. */ s3Location: S3Location; /** * Metadata that you can use to manage the workspace */ tags?: TagMap; /** * The ID of the workspace. */ workspaceId: Id; } export interface CreateWorkspaceResponse { /** * The ARN of the workspace. */ arn: TwinMakerArn; /** * The date and time when the workspace was created. */ creationDateTime: Timestamp; } export interface DataConnector { /** * A Boolean value that specifies whether the data connector is native to TwinMaker. */ isNative?: Boolean; /** * The Lambda function associated with this data connector. */ lambda?: LambdaFunction; } export interface DataType { /** * The allowed values for this data type. */ allowedValues?: DataValueList; /** * The nested type in the data type. */ nestedType?: DataType; /** * A relationship that associates a component with another component. */ relationship?: Relationship; /** * The underlying type of the data type. */ type: Type; /** * The unit of measure used in this data type. */ unitOfMeasure?: String; } export interface DataValue { /** * A Boolean value. */ booleanValue?: Boolean; /** * A double value. */ doubleValue?: Double; /** * An expression that produces the value. */ expression?: Expression; /** * An integer value. */ integerValue?: Integer; /** * A list of multiple values. */ listValue?: DataValueList; /** * A long value. */ longValue?: Long; /** * An object that maps strings to multiple DataValue objects. */ mapValue?: DataValueMap; /** * A value that relates a component to another component. */ relationshipValue?: RelationshipValue; /** * A string value. */ stringValue?: String; } export type DataValueList = DataValue[]; export type DataValueMap = {[key: string]: DataValue}; export interface DeleteComponentTypeRequest { /** * The ID of the component type to delete. */ componentTypeId: ComponentTypeId; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface DeleteComponentTypeResponse { /** * The current state of the component type to be deleted. */ state: State; } export interface DeleteEntityRequest { /** * The ID of the entity to delete. */ entityId: EntityId; /** * A Boolean value that specifies whether the operation deletes child entities. */ isRecursive?: Boolean; /** * The ID of the workspace that contains the entity to delete. */ workspaceId: Id; } export interface DeleteEntityResponse { /** * The current state of the deleted entity. */ state: State; } export interface DeleteSceneRequest { /** * The ID of the scene to delete. */ sceneId: Id; /** * The ID of the workspace. */ workspaceId: Id; } export interface DeleteSceneResponse { } export interface DeleteWorkspaceRequest { /** * The ID of the workspace to delete. */ workspaceId: Id; } export interface DeleteWorkspaceResponse { } export type Description = string; export type Double = number; export type EntityId = string; export type EntityName = string; export interface EntityPropertyReference { /** * The name of the component. */ componentName?: Name; /** * The ID of the entity. */ entityId?: EntityId; /** * A mapping of external IDs to property names. External IDs uniquely identify properties from external data stores. */ externalIdProperty?: ExternalIdProperty; /** * The name of the property. */ propertyName: Name; } export type EntitySummaries = EntitySummary[]; export interface EntitySummary { /** * The ARN of the entity. */ arn: TwinMakerArn; /** * The date and time when the entity was created. */ creationDateTime: Timestamp; /** * The description of the entity. */ description?: Description; /** * The ID of the entity. */ entityId: EntityId; /** * The name of the entity. */ entityName: EntityName; /** * A Boolean value that specifies whether the entity has child entities or not. */ hasChildEntities?: Boolean; /** * The ID of the parent entity. */ parentEntityId?: ParentEntityId; /** * The current status of the entity. */ status: Status; /** * The last date and time when the entity was updated. */ updateDateTime: Timestamp; } export type Entries = PropertyValueEntry[]; export type ErrorCode = "VALIDATION_ERROR"|"INTERNAL_FAILURE"|string; export interface ErrorDetails { /** * The error code. */ code?: ErrorCode; /** * The error message. */ message?: ErrorMessage; } export type ErrorEntries = BatchPutPropertyErrorEntry[]; export type ErrorMessage = string; export type Errors = BatchPutPropertyError[]; export type Expression = string; export type ExtendsFrom = ComponentTypeId[]; export type ExternalIdProperty = {[key: string]: String}; export interface FunctionRequest { /** * The data connector. */ implementedBy?: DataConnector; /** * The required properties of the function. */ requiredProperties?: RequiredProperties; /** * The scope of the function. */ scope?: Scope; } export interface FunctionResponse { /** * The data connector. */ implementedBy?: DataConnector; /** * Indicates whether this function is inherited. */ isInherited?: Boolean; /** * The required properties of the function. */ requiredProperties?: RequiredProperties; /** * The scope of the function. */ scope?: Scope; } export type FunctionsRequest = {[key: string]: FunctionRequest}; export type FunctionsResponse = {[key: string]: FunctionResponse}; export interface GetComponentTypeRequest { /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface GetComponentTypeResponse { /** * The ARN of the component type. */ arn: TwinMakerArn; /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The date and time when the component type was created. */ creationDateTime: Timestamp; /** * The description of the component type. */ description?: Description; /** * The name of the parent component type that this component type extends. */ extendsFrom?: ExtendsFrom; /** * An object that maps strings to the functions in the component type. Each string in the mapping must be unique to this object. */ functions?: FunctionsResponse; /** * A Boolean value that specifies whether the component type is abstract. */ isAbstract?: Boolean; /** * A Boolean value that specifies whether the component type has a schema initializer and that the schema initializer has run. */ isSchemaInitialized?: Boolean; /** * A Boolean value that specifies whether an entity can have more than one component of this type. */ isSingleton?: Boolean; /** * An object that maps strings to the property definitions in the component type. Each string in the mapping must be unique to this object. */ propertyDefinitions?: PropertyDefinitionsResponse; /** * The current status of the component type. */ status?: Status; /** * The date and time when the component was last updated. */ updateDateTime: Timestamp; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface GetEntityRequest { /** * The ID of the entity. */ entityId: EntityId; /** * The ID of the workspace. */ workspaceId: Id; } export interface GetEntityResponse { /** * The ARN of the entity. */ arn: TwinMakerArn; /** * An object that maps strings to the components in the entity. Each string in the mapping must be unique to this object. */ components?: ComponentsMap; /** * The date and time when the entity was created. */ creationDateTime: Timestamp; /** * The description of the entity. */ description?: Description; /** * The ID of the entity. */ entityId: EntityId; /** * The name of the entity. */ entityName: EntityName; /** * A Boolean value that specifies whether the entity has associated child entities. */ hasChildEntities: Boolean; /** * The ID of the parent entity for this entity. */ parentEntityId: ParentEntityId; /** * The current status of the entity. */ status: Status; /** * The date and time when the entity was last updated. */ updateDateTime: Timestamp; /** * The ID of the workspace. */ workspaceId: Id; } export interface GetPropertyValueHistoryRequest { /** * The name of the component. */ componentName?: Name; /** * The ID of the component type. */ componentTypeId?: ComponentTypeId; /** * The date and time of the latest property value to return. */ endDateTime: Timestamp; /** * The ID of the entity. */ entityId?: EntityId; /** * An object that specifies the interpolation type and the interval over which to interpolate data. */ interpolation?: InterpolationParameters; /** * The maximum number of results to return. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The time direction to use in the result order. */ orderByTime?: OrderByTime; /** * A list of objects that filter the property value history request. */ propertyFilters?: PropertyFilters; /** * A list of properties whose value histories the request retrieves. */ selectedProperties: SelectedPropertyList; /** * The date and time of the earliest property value to return. */ startDateTime: Timestamp; /** * The ID of the workspace. */ workspaceId: Id; } export interface GetPropertyValueHistoryResponse { /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * An object that maps strings to the property definitions in the component type. Each string in the mapping must be unique to this object. */ propertyValues: PropertyValueList; } export interface GetPropertyValueRequest { /** * The name of the component whose property values the operation returns. */ componentName?: Name; /** * The ID of the component type whose property values the operation returns. */ componentTypeId?: ComponentTypeId; /** * The ID of the entity whose property values the operation returns. */ entityId?: EntityId; /** * The properties whose values the operation returns. */ selectedProperties: SelectedPropertyList; /** * The ID of the workspace whose values the operation returns. */ workspaceId: Id; } export interface GetPropertyValueResponse { /** * An object that maps strings to the properties and latest property values in the response. Each string in the mapping must be unique to this object. */ propertyValues: PropertyLatestValueMap; } export interface GetSceneRequest { /** * The ID of the scene. */ sceneId: Id; /** * The ID of the workspace that contains the scene. */ workspaceId: Id; } export interface GetSceneResponse { /** * The ARN of the scene. */ arn: TwinMakerArn; /** * A list of capabilities that the scene uses to render. */ capabilities?: SceneCapabilities; /** * The relative path that specifies the location of the content definition file. */ contentLocation: S3Url; /** * The date and time when the scene was created. */ creationDateTime: Timestamp; /** * The description of the scene. */ description?: Description; /** * The ID of the scene. */ sceneId: Id; /** * The date and time when the scene was last updated. */ updateDateTime: Timestamp; /** * The ID of the workspace that contains the scene. */ workspaceId: Id; } export interface GetWorkspaceRequest { /** * The ID of the workspace. */ workspaceId: IdOrArn; } export interface GetWorkspaceResponse { /** * The ARN of the workspace. */ arn: TwinMakerArn; /** * The date and time when the workspace was created. */ creationDateTime: Timestamp; /** * The description of the workspace. */ description?: Description; /** * The ARN of the execution role associated with the workspace. */ role: RoleArn; /** * The ARN of the S3 bucket where resources associated with the workspace are stored. */ s3Location: S3Location; /** * The date and time when the workspace was last updated. */ updateDateTime: Timestamp; /** * The ID of the workspace. */ workspaceId: Id; } export type Id = string; export type IdOrArn = string; export type Integer = number; export interface InterpolationParameters { /** * The interpolation type. */ interpolationType?: InterpolationType; /** * The interpolation time interval in seconds. */ intervalInSeconds?: IntervalInSeconds; } export type InterpolationType = "LINEAR"|string; export type IntervalInSeconds = number; export type LambdaArn = string; export interface LambdaFunction { /** * The ARN of the Lambda function. */ arn: LambdaArn; } export interface ListComponentTypesFilter { /** * The component type that the component types in the list extend. */ extendsFrom?: ComponentTypeId; /** * A Boolean value that specifies whether the component types in the list are abstract. */ isAbstract?: Boolean; /** * The namespace to which the component types in the list belong. */ namespace?: String; } export type ListComponentTypesFilters = ListComponentTypesFilter[]; export interface ListComponentTypesRequest { /** * A list of objects that filter the request. */ filters?: ListComponentTypesFilters; /** * The maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The ID of the workspace. */ workspaceId: Id; } export interface ListComponentTypesResponse { /** * A list of objects that contain information about the component types. */ componentTypeSummaries: ComponentTypeSummaries; /** * Specifies the maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The ID of the workspace. */ workspaceId: Id; } export interface ListEntitiesFilter { /** * The ID of the component type in the entities in the list. */ componentTypeId?: ComponentTypeId; /** * The parent of the entities in the list. */ parentEntityId?: ParentEntityId; } export type ListEntitiesFilters = ListEntitiesFilter[]; export interface ListEntitiesRequest { /** * A list of objects that filter the request. */ filters?: ListEntitiesFilters; /** * The maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The ID of the workspace. */ workspaceId: Id; } export interface ListEntitiesResponse { /** * A list of objects that contain information about the entities. */ entitySummaries?: EntitySummaries; /** * The string that specifies the next page of results. */ nextToken?: NextToken; } export interface ListScenesRequest { /** * Specifies the maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The ID of the workspace that contains the scenes. */ workspaceId: Id; } export interface ListScenesResponse { /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * A list of objects that contain information about the scenes. */ sceneSummaries?: SceneSummaries; } export interface ListTagsForResourceRequest { /** * The maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * The ARN of the resource. */ resourceARN: TwinMakerArn; } export interface ListTagsForResourceResponse { /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * Metadata that you can use to manage a resource. */ tags?: TagMap; } export interface ListWorkspacesRequest { /** * The maximum number of results to display. */ maxResults?: MaxResults; /** * The string that specifies the next page of results. */ nextToken?: NextToken; } export interface ListWorkspacesResponse { /** * The string that specifies the next page of results. */ nextToken?: NextToken; /** * A list of objects that contain information about the workspaces. */ workspaceSummaries?: WorkspaceSummaries; } export type Long = number; export type MaxResults = number; export type Name = string; export type NextToken = string; export type OrderByTime = "ASCENDING"|"DESCENDING"|string; export type ParentEntityId = string; export interface ParentEntityUpdateRequest { /** * The ID of the parent entity. */ parentEntityId?: ParentEntityId; /** * The type of the update. */ updateType: ParentEntityUpdateType; } export type ParentEntityUpdateType = "UPDATE"|"DELETE"|string; export interface PropertyDefinitionRequest { /** * A mapping that specifies configuration information about the property. Use this field to specify information that you read from and write to an external source. */ configuration?: Configuration; /** * An object that contains information about the data type. */ dataType?: DataType; /** * An object that contains the default value. */ defaultValue?: DataValue; /** * A Boolean value that specifies whether the property ID comes from an external data store. */ isExternalId?: Boolean; /** * A Boolean value that specifies whether the property is required. */ isRequiredInEntity?: Boolean; /** * A Boolean value that specifies whether the property is stored externally. */ isStoredExternally?: Boolean; /** * A Boolean value that specifies whether the property consists of time series data. */ isTimeSeries?: Boolean; } export interface PropertyDefinitionResponse { /** * A mapping that specifies configuration information about the property. */ configuration?: Configuration; /** * An object that contains information about the data type. */ dataType: DataType; /** * An object that contains the default value. */ defaultValue?: DataValue; /** * A Boolean value that specifies whether the property ID comes from an external data store. */ isExternalId: Boolean; /** * A Boolean value that specifies whether the property definition can be updated. */ isFinal: Boolean; /** * A Boolean value that specifies whether the property definition is imported from an external data store. */ isImported: Boolean; /** * A Boolean value that specifies whether the property definition is inherited from a parent entity. */ isInherited: Boolean; /** * A Boolean value that specifies whether the property is required in an entity. */ isRequiredInEntity: Boolean; /** * A Boolean value that specifies whether the property is stored externally. */ isStoredExternally: Boolean; /** * A Boolean value that specifies whether the property consists of time series data. */ isTimeSeries: Boolean; } export type PropertyDefinitionsRequest = {[key: string]: PropertyDefinitionRequest}; export type PropertyDefinitionsResponse = {[key: string]: PropertyDefinitionResponse}; export interface PropertyFilter { /** * The operator associated with this property filter. */ operator?: String; /** * The property name associated with this property filter. */ propertyName?: String; /** * The value associated with this property filter. */ value?: DataValue; } export type PropertyFilters = PropertyFilter[]; export interface PropertyLatestValue { /** * An object that specifies information about a property.&gt; */ propertyReference: EntityPropertyReference; /** * The value of the property. */ propertyValue?: DataValue; } export type PropertyLatestValueMap = {[key: string]: PropertyLatestValue}; export interface PropertyRequest { /** * An object that specifies information about a property. */ definition?: PropertyDefinitionRequest; /** * The update type of the update property request. */ updateType?: PropertyUpdateType; /** * The value of the property. */ value?: DataValue; } export type PropertyRequests = {[key: string]: PropertyRequest}; export interface PropertyResponse { /** * An object that specifies information about a property. */ definition?: PropertyDefinitionResponse; /** * The value of the property. */ value?: DataValue; } export type PropertyResponses = {[key: string]: PropertyResponse}; export type PropertyUpdateType = "UPDATE"|"DELETE"|string; export interface PropertyValue { /** * The timestamp of a value for a time series property. */ timestamp: Timestamp; /** * An object that specifies a value for a time series property. */ value: DataValue; } export interface PropertyValueEntry { /** * An object that contains information about the entity that has the property. */ entityPropertyReference: EntityPropertyReference; /** * A list of objects that specify time series property values. */ propertyValues?: PropertyValues; } export interface PropertyValueHistory { /** * An object that uniquely identifies an entity property. */ entityPropertyReference: EntityPropertyReference; /** * A list of objects that contain information about the values in the history of a time series property. */ values?: Values; } export type PropertyValueList = PropertyValueHistory[]; export type PropertyValues = PropertyValue[]; export interface Relationship { /** * The type of the relationship. */ relationshipType?: String; /** * The ID of the target component type associated with this relationship. */ targetComponentTypeId?: ComponentTypeId; } export interface RelationshipValue { /** * The name of the target component associated with the relationship value. */ targetComponentName?: Name; /** * The ID of the target entity associated with this relationship value. */ targetEntityId?: EntityId; } export type RequiredProperties = Name[]; export type RoleArn = string; export type S3Location = string; export type S3Url = string; export type SceneCapabilities = SceneCapability[]; export type SceneCapability = string; export type SceneSummaries = SceneSummary[]; export interface SceneSummary { /** * The ARN of the scene. */ arn: TwinMakerArn; /** * The relative path that specifies the location of the content definition file. */ contentLocation: S3Url; /** * The date and time when the scene was created. */ creationDateTime: Timestamp; /** * The scene description. */ description?: Description; /** * The ID of the scene. */ sceneId: Id; /** * The date and time when the scene was last updated. */ updateDateTime: Timestamp; } export type Scope = "ENTITY"|"WORKSPACE"|string; export type SelectedPropertyList = String[]; export type State = "CREATING"|"UPDATING"|"DELETING"|"ACTIVE"|"ERROR"|string; export interface Status { /** * The error message. */ error?: ErrorDetails; /** * The current state of the entity, component, component type, or workspace. */ state?: State; } export type String = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The ARN of the resource. */ resourceARN: TwinMakerArn; /** * Metadata to add to this resource. */ tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type Timestamp = Date; export type TwinMakerArn = string; export type Type = "RELATIONSHIP"|"STRING"|"LONG"|"BOOLEAN"|"INTEGER"|"DOUBLE"|"LIST"|"MAP"|string; export interface UntagResourceRequest { /** * The ARN of the resource. */ resourceARN: TwinMakerArn; /** * A list of tag key names to remove from the resource. You don't specify the value. Both the key and its associated value are removed. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateComponentTypeRequest { /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The description of the component type. */ description?: Description; /** * Specifies the component type that this component type extends. */ extendsFrom?: ExtendsFrom; /** * An object that maps strings to the functions in the component type. Each string in the mapping must be unique to this object. */ functions?: FunctionsRequest; /** * A Boolean value that specifies whether an entity can have more than one component of this type. */ isSingleton?: Boolean; /** * An object that maps strings to the property definitions in the component type. Each string in the mapping must be unique to this object. */ propertyDefinitions?: PropertyDefinitionsRequest; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface UpdateComponentTypeResponse { /** * The ARN of the component type. */ arn: TwinMakerArn; /** * The ID of the component type. */ componentTypeId: ComponentTypeId; /** * The current state of the component type. */ state: State; /** * The ID of the workspace that contains the component type. */ workspaceId: Id; } export interface UpdateEntityRequest { /** * An object that maps strings to the component updates in the request. Each string in the mapping must be unique to this object. */ componentUpdates?: ComponentUpdatesMapRequest; /** * The description of the entity. */ description?: Description; /** * The ID of the entity. */ entityId: EntityId; /** * The name of the entity. */ entityName?: EntityName; /** * An object that describes the update request for a parent entity. */ parentEntityUpdate?: ParentEntityUpdateRequest; /** * The ID of the workspace that contains the entity. */ workspaceId: Id; } export interface UpdateEntityResponse { /** * The current state of the entity update. */ state: State; /** * The date and time when the entity was last updated. */ updateDateTime: Timestamp; } export interface UpdateSceneRequest { /** * A list of capabilities that the scene uses to render. */ capabilities?: SceneCapabilities; /** * The relative path that specifies the location of the content definition file. */ contentLocation?: S3Url; /** * The description of this scene. */ description?: Description; /** * The ID of the scene. */ sceneId: Id; /** * The ID of the workspace that contains the scene. */ workspaceId: Id; } export interface UpdateSceneResponse { /** * The date and time when the scene was last updated. */ updateDateTime: Timestamp; } export interface UpdateWorkspaceRequest { /** * The description of the workspace. */ description?: Description; /** * The ARN of the execution role associated with the workspace. */ role?: RoleArn; /** * The ID of the workspace. */ workspaceId: Id; } export interface UpdateWorkspaceResponse { /** * The date and time of the current update. */ updateDateTime: Timestamp; } export type Value = string; export type Values = PropertyValue[]; export type WorkspaceSummaries = WorkspaceSummary[]; export interface WorkspaceSummary { /** * The ARN of the workspace. */ arn: TwinMakerArn; /** * The date and time when the workspace was created. */ creationDateTime: Timestamp; /** * The description of the workspace. */ description?: Description; /** * The date and time when the workspace was last updated. */ updateDateTime: Timestamp; /** * The ID of the workspace. */ workspaceId: Id; } /** * 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 = "2021-11-29"|"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 IoTTwinMaker client. */ export import Types = IoTTwinMaker; } export = IoTTwinMaker;
the_stack
import * as express from 'express'; import { RosaeContext, RenderedBundle, RenderOptionsOutput, RosaeContextsManager, S3RosaeContextsManager, S3Conf, DiskRosaeContextsManager, RosaeContextsManagerParams, MemoryRosaeContextsManager, } from 'rosaenlg-server-toolkit'; import { RosaeNlgFeatures /*, PackagedTemplate */ } from 'rosaenlg-packager'; import winston = require('winston'); import { performance } from 'perf_hooks'; import CloudWatchTransport = require('winston-aws-cloudwatch'); import { createHash } from 'crypto'; import { compileFileClient, getRosaeNlgVersion, NlgLib } from 'rosaenlg'; interface RenderResponseAbstract { renderedText: string; renderOptions: RenderOptionsOutput; outputData: any; ms: number; } interface DirectRenderResponse extends RenderResponseAbstract { status: 'EXISTED' | 'CREATED'; } interface ClassicRenderResponse extends RenderResponseAbstract { templateSha1: string; } interface CloudWatchParams { logGroupName: string | undefined; logStreamName: string | undefined; accessKeyId: string | undefined; secretAccessKey: string | undefined; region: string | undefined; } interface Behavior { lazyStartup: boolean; forgetTemplates: boolean; cacheTtl?: number; checkPeriod?: number; } export interface ServerParams { templatesPath?: string | undefined; sharedTemplatesPath?: string | undefined; sharedTemplatesUser: string | undefined; s3conf: S3Conf; cloudwatch: CloudWatchParams; behavior: Behavior; userIdHeader?: string; } interface PackagedExisting { type: 'existing'; which: string; } // type contentInBackend = PackagedTemplate | PackagedExisting; export default class TemplatesController { private readonly path = '/templates'; private rosaeContextsManager: RosaeContextsManager; // eslint-disable-next-line new-cap public router = express.Router(); private readonly defaultUser = 'DEFAULT_USER'; private userIdHeader: string; initializeRoutes(): void { this.router.get(this.path, this.listTemplates); this.router.get(`${this.path}/:templateId`, this.getTemplate); this.router.get(`/health`, this.getHealth); this.router.get(`/version`, this.getVersion); this.router.post(this.path, this.createTemplate).put(this.path, this.createTemplate); this.router.post(`${this.path}/render`, this.directRender); this.router.post(`${this.path}/:templateId/:templateSha1/render`, this.renderTemplate); this.router.delete(`${this.path}/:templateId`, this.deleteTemplate); } constructor(serverParams: ServerParams) { // cloudwatch logging. done first to get logs asap /* istanbul ignore next */ if ( serverParams && serverParams.cloudwatch && serverParams.cloudwatch.logGroupName && serverParams.cloudwatch.accessKeyId && serverParams.cloudwatch.secretAccessKey ) { winston.info({ action: 'startup', message: `starting to configure cloudwatch logging...` }); const cwt = new CloudWatchTransport({ logGroupName: serverParams.cloudwatch.logGroupName, logStreamName: serverParams.cloudwatch.logStreamName, createLogGroup: false, createLogStream: false, submissionInterval: 2000, submissionRetryCount: 1, batchSize: 20, awsConfig: { accessKeyId: serverParams.cloudwatch.accessKeyId, secretAccessKey: serverParams.cloudwatch.secretAccessKey, region: serverParams.cloudwatch.region, }, //formatLog: item => `${item.level}: ${item.message}`, }); winston.add(cwt); } if (serverParams && serverParams.userIdHeader) { this.userIdHeader = serverParams.userIdHeader; winston.info({ action: 'startup', message: `user id header is ${this.userIdHeader}`, }); } // forget templates let forgetTemplates = false; if (serverParams && serverParams.behavior && serverParams.behavior.forgetTemplates) { if (!serverParams.s3conf && !serverParams.templatesPath) { winston.error({ action: 'startup', message: 'asked to forget templates, but no backend: parameter is ignored', }); } else { forgetTemplates = true; } } // specific ttl and checkPeriod for tests purposes let ttl: number = null; if (serverParams && serverParams.behavior && serverParams.behavior.cacheTtl) { ttl = serverParams.behavior.cacheTtl; winston.info({ action: 'startup', message: `using specific ttl: ${ttl}`, }); } let checkPeriod: number = null; if (serverParams && serverParams.behavior && serverParams.behavior.checkPeriod) { checkPeriod = serverParams.behavior.checkPeriod; winston.info({ action: 'startup', message: `using specific check period: ${checkPeriod}`, }); } const rosaeNlgFeatures: RosaeNlgFeatures = { NlgLib: NlgLib, getRosaeNlgVersion: getRosaeNlgVersion, compileFileClient: compileFileClient, }; // shared templates? // has to be done before RosaeContextsManagerParams creation if (serverParams && serverParams.sharedTemplatesUser != null && serverParams.sharedTemplatesUser != '') { winston.info({ action: 'startup', message: `shared templates as the user "${serverParams.sharedTemplatesUser}"`, }); } const rosaeContextsManagerParams: RosaeContextsManagerParams = { forgetTemplates: forgetTemplates, specificTtl: ttl, specificCheckPeriod: checkPeriod, enableCache: true, }; if (serverParams && serverParams.sharedTemplatesUser) { rosaeContextsManagerParams.sharedTemplatesUser = serverParams.sharedTemplatesUser; } if (serverParams && serverParams.sharedTemplatesPath) { rosaeContextsManagerParams.sharedTemplatesPath = serverParams.sharedTemplatesPath; } if (serverParams && serverParams.s3conf && serverParams.s3conf.bucket) { // if S3 this.rosaeContextsManager = new S3RosaeContextsManager( serverParams.s3conf, rosaeNlgFeatures, rosaeContextsManagerParams, ); winston.info({ action: 'startup', message: `trying to use s3 ${serverParams.s3conf.bucket}`, }); } else if (serverParams && serverParams.templatesPath) { this.rosaeContextsManager = new DiskRosaeContextsManager( serverParams.templatesPath, rosaeNlgFeatures, rosaeContextsManagerParams, ); winston.info({ action: 'startup', message: `trying to use disk ${serverParams.templatesPath}`, }); } else { this.rosaeContextsManager = new MemoryRosaeContextsManager(rosaeNlgFeatures, rosaeContextsManagerParams); winston.info({ action: 'startup', message: `trying to use only memory`, }); } // reload existing templates for the user if (this.rosaeContextsManager.hasBackend()) { if (serverParams && serverParams.behavior && serverParams.behavior.lazyStartup) { winston.info({ action: 'startup', message: `lazy startup: we don't reload`, }); } else { winston.info({ action: 'startup', message: `reloading all templates...`, }); this.rosaeContextsManager.reloadAllFiles((err) => { if (err) { winston.warn({ action: 'startup', message: `reloadAllFiles failed: ${err}`, }); } }); } } this.initializeRoutes(); } deleteTemplate = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { const templateId: string = request.params.templateId; winston.info({ user: user, templateId: templateId, action: 'delete', message: `start delete...` }); this.rosaeContextsManager.deleteFromCacheAndBackend(user, templateId, (err) => { if (err) { response.status(204).send(err.message); return; } else { response.status(204).send('ok'); // deleted OK return; } }); }); }; listTemplates = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { winston.info({ user: user, action: 'list' }); if (this.rosaeContextsManager.hasBackend()) { this.rosaeContextsManager.getIdsFromBackend(user, (err, templates) => { if (err) { winston.error({ user: user, action: 'list', message: `error listing templates: ${err}` }); response.status(500).send(`error listing templates: ${err}`); } else { winston.info({ user: user, action: 'list', message: `templates: ${templates}` }); response.status(200).send({ ids: templates, }); } }); } else { // just what we have in cache const ids = this.rosaeContextsManager.getIdsInCache(user); winston.info({ user: user, action: 'list', message: `templates: ${ids}` }); response.status(200).send({ ids: ids, }); return; } }); }; getHealth = (request: express.Request, response: express.Response): void => { this.rosaeContextsManager.checkHealth((err) => { if (err) { winston.error({ action: 'health', message: `health failed: ${err}`, }); response.status(503).send(`health failed`); } else { response.sendStatus(200); } }); }; getVersion = (request: express.Request, response: express.Response): void => { try { const version = this.rosaeContextsManager.getVersion(); response.status(200).send({ version: version }); return; } catch (e) /* istanbul ignore next */ { response.status(500).send(e.message); } }; getUser = (request: express.Request, response: express.Response, cb: (user: string) => void): void => { let user: string; // jwt // istanbul ignore if if (request['user']) { // istanbul ignore next user = request['user'].sub; } else if (this.userIdHeader) { user = request.header(this.userIdHeader); } if (!user) { cb(this.defaultUser); } else { if (user.indexOf('#') > -1) { response.status(400).send(`invalid user name: contains #`); } else { cb(user.replace(/\|/g, '_')); // as user in auth0 is auth0|..., and | is invalid in a file name } } }; getTemplate = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { const templateId: string = request.params.templateId; winston.info({ user: user, templateId: templateId, action: 'get', message: `get original package` }); if (this.rosaeContextsManager.hasBackend()) { // we force read even if it might be in the cache this.rosaeContextsManager.readTemplateOnBackend(user, templateId, (err, templateContent) => { if (err) { response.status(parseInt(err.name)).send(err.message); winston.info({ user: user, templateId: templateId, message: err.message }); return; } else { if ((templateContent as PackagedExisting).type == 'existing') { response.status(200).send({ templateContent: templateContent, }); return; } else { this.rosaeContextsManager.compSaveAndLoad( templateContent, false, (loadErr, templateSha1, rosaeContext) => { if (loadErr) { response.status(parseInt(loadErr.name)).send(loadErr.message); winston.info({ user: user, templateId: templateId, message: loadErr.message }); return; } else { response.status(200).send({ templateSha1: templateSha1, templateContent: rosaeContext.getFullTemplate(), }); return; } }, ); } } }); } else { // we try from cache when no backend const cacheValue = this.rosaeContextsManager.getFromCache(user, templateId); if (!cacheValue) { response.status(404).send('template not found'); winston.info({ user: user, templateId: templateId, message: 'template not found' }); return; } else { response.status(200).send({ templateSha1: cacheValue.templateSha1, templateContent: cacheValue.rosaeContext.getFullTemplate(), }); return; } } }); }; createTemplate = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { const start = performance.now(); winston.info({ user: user, action: 'create', message: `creating or updating a template` }); const templateContent = request.body; // we have to save it for persistency and reload templateContent.user = user; /* if (templateContent.type != null && templateContent.type == 'existing') { const templateId = templateContent.templateId; const filename = this.rosaeContextsManager.getFilename(user, templateId); this.rosaeContextsManager.saveOnBackend(filename, JSON.stringify(templateContent), (err) => { if (err) { response.status(500).send(`could not save to backend: ${err.message}`); } else { const ms = performance.now() - start; response.status(201).send({ templateId: templateId, ms: ms, }); winston.info({ user: user, templateId: templateId, action: 'create', ms: Math.round(ms), message: `created, points to an existing: ${templateContent.which}`, }); } }); } else { */ this.rosaeContextsManager.compSaveAndLoad(templateContent, true, (err, templateSha1, rosaeContext) => { if (err) { response.status(parseInt(err.name)).send(err.message); } else { const ms = performance.now() - start; response.status(201).send({ templateId: rosaeContext.getTemplateId(), templateSha1: templateSha1, ms: ms, }); winston.info({ user: user, templateId: rosaeContext.getTemplateId(), action: 'create', sha1: templateSha1, ms: Math.round(ms), message: `created`, }); } }); //} }); }; directRender = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { const start = performance.now(); winston.info({ user: user, action: 'directRender', message: `direct rendering of a template...` }); const templateWithData = request.body; // const template = requestContent.template; const data = templateWithData.data; if (!templateWithData.src) { response.status(400).send(`no template src`); winston.info({ user: user, action: 'directRender', message: `no template src`, }); return; } if (!data) { response.status(400).send(`no data`); winston.info({ user: user, action: 'directRender', message: `no data`, }); return; } // key is based solely on the template src part; it does not contain any pre compiled code const templateCalculatedId = createHash('sha1').update(JSON.stringify(templateWithData.src)).digest('hex'); const alreadyHere = this.rosaeContextsManager.isInCache(user, templateCalculatedId); if (!alreadyHere) { templateWithData.templateId = templateCalculatedId; templateWithData.user = user; try { this.rosaeContextsManager.setInCache( user, templateCalculatedId, { templateSha1: templateCalculatedId, rosaeContext: new RosaeContext(templateWithData, { NlgLib: NlgLib, compileFileClient: compileFileClient, getRosaeNlgVersion: getRosaeNlgVersion, }), }, true, ); } catch (e) { response.status(400).send(`error creating template: ${e.message}`); winston.info({ user: user, action: 'directRender', message: `error creating template: ${e.message}`, }); return; } } const rosaeContext: RosaeContext = this.rosaeContextsManager.getFromCache(user, templateCalculatedId) .rosaeContext; try { const renderedBundle: RenderedBundle = rosaeContext.render(data); const status = alreadyHere ? 'EXISTED' : 'CREATED'; const ms = performance.now() - start; const resp: DirectRenderResponse = { status: status, renderedText: renderedBundle.text, outputData: renderedBundle.outputData, renderOptions: renderedBundle.renderOptions, ms: ms, }; response.status(200).send(resp); winston.info({ user: user, action: 'directRender', ms: Math.round(ms), message: `rendered ${templateCalculatedId}, ${status}`, }); } catch (e) { response.status(400).send(`rendering error: ${e.toString()}`); winston.info({ user: user, action: 'directRender', message: `rendering error: ${e.toString()}`, }); return; } }); }; renderTemplate = (request: express.Request, response: express.Response): void => { this.getUser(request, response, (user) => { const start = performance.now(); const templateId: string = request.params.templateId; const templateSha1: string = request.params.templateSha1; winston.info({ user: user, templateId: templateId, sha1: templateSha1, action: 'render', message: `start rendering a template...`, }); this.rosaeContextsManager.getFromCacheOrLoad(user, templateId, templateSha1, (err, cacheValue) => { if (err) { if (err.name === 'WRONG_SHA1') { const targetSha1 = err.message.match(/<(.*)>/)[1]; response.redirect(308, `../${targetSha1}/render`); // 308 and not 301 when POST redirect winston.info({ user: user, templateId: templateId, action: 'get', message: `${err.message} => redirect`, }); return; } else { response.status(parseInt(err.name)).send(err.message); winston.info({ user: user, templateId: templateId, message: err.message }); return; } } else { try { const renderedBundle: RenderedBundle = cacheValue.rosaeContext.render(request.body); const ms = performance.now() - start; const resp: ClassicRenderResponse = { renderedText: renderedBundle.text, renderOptions: renderedBundle.renderOptions, outputData: renderedBundle.outputData, templateSha1: templateSha1, ms: ms, }; response.status(200).send(resp); winston.info({ user: user, templateId: templateId, sha1: templateSha1, action: 'render', ms: Math.round(ms), message: `done`, }); } catch (e) { response.status(400).send(`rendering error: ${e.toString()}`); winston.info({ user: user, templateId: templateId, sha1: templateSha1, action: 'render', message: `rendering error: ${e.toString()}`, }); return; } } }); }); }; }
the_stack
namespace ts { export function transformTypeScriptPlus(context: TransformationContext) { const compilerOptions = context.getCompilerOptions(); const compilerDefines = getCompilerDefines(compilerOptions.defines!); const typeChecker = compilerOptions.emitReflection || compilerDefines ? context.getEmitHost().getTypeChecker() : null; const previousOnSubstituteNode = context.onSubstituteNode; if (compilerDefines) { context.onSubstituteNode = onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); } return chainBundle(transformSourceFile); function transformSourceFile(node: SourceFile) { if (!compilerOptions.emitReflection) { return node; } let visited = updateSourceFileNode(node, visitNodes(node.statements, visitStatement, isStatement)); addEmitHelpers(visited, context.readEmitHelpers()); return visited; } function visitStatement(node: Node): VisitResult<Node> { if (hasModifier(node, ModifierFlags.Ambient)) { return node; } if (node.kind === SyntaxKind.ClassDeclaration) { return visitClassDeclaration(<ClassDeclaration>node); } if (node.kind === SyntaxKind.ModuleDeclaration) { return visitModule(<NamespaceDeclaration>node); } return node; } function visitModule(node: NamespaceDeclaration): NamespaceDeclaration { if (node.body.kind === SyntaxKind.ModuleDeclaration) { return updateModuleDeclaration(node, visitModule(<NamespaceDeclaration>node.body)); } if (node.body.kind === SyntaxKind.ModuleBlock) { const body = updateModuleBlock(node.body, visitNodes( (<ModuleBlock>node.body).statements, visitStatement, isStatement)); return updateModuleDeclaration(node, body); } return node; } function updateModuleDeclaration(node: NamespaceDeclaration, body: ModuleBody) { if (node.body !== body) { let updated = getMutableClone(node); updated.body = <ModuleBlock>body; return updateNode(updated, node); } return node } function updateModuleBlock(node: ModuleBlock, statements: NodeArray<Statement>) { if (node.statements !== statements) { let updated = getMutableClone(node); updated.statements = createNodeArray(statements); return updateNode(updated, node); } return node; } function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> { const classStatement = getMutableClone(node); const statements: Statement[] = [classStatement]; let interfaceMap: any = {}; getImplementedInterfaces(node, interfaceMap); let allInterfaces: string[] = Object.keys(interfaceMap); let interfaces: string[]; let superTypes = getSuperClassTypes(node); if (superTypes) { interfaces = []; for (let type of allInterfaces) { if (superTypes.indexOf(type) === -1) { interfaces.push(type); } } } else { interfaces = allInterfaces; } node.typeNames = interfaces; let fullClassName = typeChecker!.getFullyQualifiedName(node.symbol); const expression = createReflectHelper(context, node.name!, fullClassName, interfaces); setSourceMapRange(expression, createRange(node.name!.pos, node.end)); const statement = createStatement(expression); setSourceMapRange(statement, createRange(-1, node.end)); statements.push(statement); return statements; } function getImplementedInterfaces(node: Node, result: any) { let superInterfaces: NodeArray<any> | undefined = undefined; if (node.kind === SyntaxKind.ClassDeclaration) { superInterfaces = getClassImplementsHeritageClauseElements(<ClassLikeDeclaration>node); } else { superInterfaces = getInterfaceBaseTypeNodes(<InterfaceDeclaration>node); } if (superInterfaces) { superInterfaces.forEach(superInterface => { let type = typeChecker!.getTypeAtLocation(superInterface) if (type && type.symbol && type.symbol.flags & SymbolFlags.Interface) { let symbol = type.symbol; let fullName = typeChecker!.getFullyQualifiedName(symbol); result[fullName] = true; const declaration = ts.getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (declaration) { getImplementedInterfaces(declaration, result); } } }); } } function getSuperClassTypes(node: ClassLikeDeclaration): string[] | undefined { let superClass = getClassExtendsHeritageElement(node); if (!superClass) { return undefined; } let type = typeChecker!.getTypeAtLocation(superClass); if (!type || !type.symbol) { return undefined; } let declaration = <ClassLikeDeclaration>ts.getDeclarationOfKind(type.symbol, SyntaxKind.ClassDeclaration); return declaration ? declaration.typeNames : undefined; } function getCompilerDefines(defines: MapLike<any>): MapLike<string> | null { if (!defines) { return null; } let compilerDefines: MapLike<string> = {}; let keys = Object.keys(defines); for (let key of keys) { let value = defines[key]; let type = typeof value; switch (type) { case "boolean": case "number": compilerDefines[key] = value.toString(); break; case "string": compilerDefines[key] = "\"" + value + "\""; break; } } if (Object.keys(compilerDefines).length == 0) { return null; } return compilerDefines; } function isDefinedConstant(node: Identifier): boolean { let nodeText = ts.getTextOfIdentifierOrLiteral(node); if (compilerDefines![nodeText] === undefined) { return false; } if (!node.parent) { return false } if (node.parent.kind === SyntaxKind.VariableDeclaration && (<VariableDeclaration>node.parent).name === node) { return false; } if (node.parent.kind === SyntaxKind.BinaryExpression) { let parent = <BinaryExpression>node.parent; if (parent.left === node && parent.operatorToken.kind === SyntaxKind.EqualsToken) { return false; } } let symbol = typeChecker!.getSymbolAtLocation(node); if (!symbol || !symbol.declarations) { return false; } let declaration = symbol.declarations[0]; if (!declaration) { return false; } if (declaration.kind !== SyntaxKind.VariableDeclaration) { return false; } let statement = declaration.parent.parent; return (statement.parent.kind === SyntaxKind.SourceFile); } /** * Hooks node substitutions. * @param emitContext The context for the emitter. * @param node The node to substitute. */ function onSubstituteNode(hint: EmitHint, node: Node) { node = previousOnSubstituteNode(hint, node); if (isIdentifier(node) && isDefinedConstant(node)) { let nodeText = ts.getTextOfIdentifierOrLiteral(node); return createIdentifier(compilerDefines![nodeText]); } return node; } } const reflectHelper: EmitHelper = { name: "typescript:reflect", scoped: false, priority: 0, text: ` var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; };` }; function createReflectHelper(context: TransformationContext, name: Identifier, fullClassName: string, interfaces: string[]) { context.requestEmitHelper(reflectHelper); let argumentsArray: Expression[] = [ createPropertyAccess(name, createIdentifier("prototype")), createLiteral(fullClassName) ]; if (interfaces.length) { let elements: Expression[] = []; for (let value of interfaces) { elements.push(createLiteral(value)); } argumentsArray.push(createArrayLiteral(elements)); } return createCall( getHelperName("__reflect"), /*typeArguments*/ undefined, argumentsArray ); } }
the_stack
"use strict"; import { Classic } from "./classic"; import { ClassicPlayer } from "./classicPlayer"; import { Player } from "../../core/player"; import { Colors } from "../../core/utils"; export enum Alignment { town = "town", mafia = "mafia", neutral = "neutral", undefined = "undefined", } export enum Passives { //cannot be killed at night nightImmune = "nightImmune", roleblockImmune = "roleblockImmune", speakWithDead = "hearDeadChat", } type WinCondition = (player: ClassicPlayer, game: Classic) => boolean; type GameEndCondition = (game: Classic) => boolean; export type Ability = { readonly condition: ( targetPlayer: ClassicPlayer, game: Classic, player?: Player, ) => boolean | undefined; readonly action: ( targetPlayer: ClassicPlayer, game: Classic, player?: ClassicPlayer, ) => void; }; export interface Role { readonly roleName: string; readonly alignment: Alignment; readonly winCondition: WinCondition; abilities: Readonly<Array<Readonly<{ ability: Ability; uses?: number }>>>; readonly passives: Array<Passives>; readonly color?: Colors; readonly backgroundColor?: Colors; }; export namespace GameEndConditions { //town wins if no mafia remain export const townWin: GameEndCondition = (game: Classic) => { for (let player of game.players) { if (player.alignment == Alignment.mafia && player.alive) { return false; } } return true; }; //mafia wins if there are more mafia then town, or there is just 1 town and 1 mafia (which would otherwise cause stalemate) export const mafiaWin: GameEndCondition = (game: Classic) => { let townCount = 0; let mafiaCount = 0; let alive = 0; for (let player of game.players) { if (player.alignment == Alignment.town && player.alive) { townCount += 1; } if (player.alignment == Alignment.mafia && player.alive) { mafiaCount += 1; } if (player.alive) { alive += 1; } } return ( townCount < mafiaCount || (townCount == 1 && mafiaCount == 1 && alive == 2) ); }; } export namespace WinConditions { export const town: WinCondition = (player: ClassicPlayer, game: Classic) => { return GameEndConditions.townWin(game); }; export const mafia: WinCondition = (player: ClassicPlayer, game: Classic) => { return GameEndConditions.mafiaWin(game); }; export const lynchTarget: WinCondition = ( player: ClassicPlayer, game: Classic, ) => { if (player.winLynchTarget) { return player.winLynchTarget.hanged; } else { console.log("Error: executioner was not given lynch target"); return false; } }; export const survive: WinCondition = ( player: ClassicPlayer, game: Classic, ) => { return player.alive; }; export const hanged: WinCondition = ( player: ClassicPlayer, game: Classic, ) => { return player.hanged; }; //last one standing excludes survivors, jesters and executioners export const lastOneStanding: WinCondition = ( player: ClassicPlayer, game: Classic, ) => { let aliveCount = 0; for (let player of game.players) { if ( player.alive && player.role != Roles.survivor && player.role != Roles.jester && player.role != Roles.executioner ) { aliveCount += 1; } } return player.alive && aliveCount <= 2; }; export const undefined: WinCondition = ( player: ClassicPlayer, game: Classic, ) => { return false; }; } namespace Conditions { export const alwaysTrue = (targetPlayer: ClassicPlayer, game: Classic) => { return true; }; } namespace Abilities { export const kill: Ability = { condition: ( targetPlayer: ClassicPlayer, game: Classic, player?: Player, ) => { if (targetPlayer.healed && player) { player.user.send("Your target was healed!"); } return !targetPlayer.healed; }, action: (targetPlayer: ClassicPlayer, game: Classic) => { game.kill(targetPlayer); }, }; export const mafiaKill: Ability = { condition: ( targetPlayer: ClassicPlayer, game: Classic, player?: Player, ) => { if (player) { game.mafiachat.broadcast( `${player.user.username} attacked ${targetPlayer.user.username}.`, ); if (targetPlayer.healed) { game.mafiachat.broadcast( `The target was healed and so survived the attack.`, ); } return !targetPlayer.healed; } else { console.log("Err: mafia killer not passed into mafiaKill"); return false; } }, action: Abilities.kill.action, }; export const godfatherOrder: Ability = { condition: ( targetPlayer: ClassicPlayer, game: Classic, player?: Player, ) => { return ( !game.players.find( player => player.role == Roles.mafioso && !player.roleBlocked && game.getPlayer(player.target) !== undefined, ) && Abilities.mafiaKill.condition(targetPlayer, game, player as Player) ); }, action: Abilities.kill.action, }; export const mafiosoKill: Ability = { condition: Conditions.alwaysTrue, action: ( targetPlayer: ClassicPlayer, game: Classic, player?: ClassicPlayer, ) => { if (player) { let godfather = game.players.find(elem => elem.role == Roles.godfather); if (godfather) { let godfatherTarget = game.getPlayer(godfather.target); if (godfatherTarget) { if (Abilities.mafiaKill.condition(godfatherTarget, game, player)) { Abilities.kill.action(godfatherTarget, game, player); } return; } } if (Abilities.mafiaKill.condition(targetPlayer, game, player)) { Abilities.kill.action(targetPlayer, game, player); } } }, }; export const heal: Ability = { condition: Conditions.alwaysTrue, action: (targetPlayer: ClassicPlayer, game: Classic) => { targetPlayer.healed = true; }, }; export const getAlignment: Ability = { condition: Conditions.alwaysTrue, action: ( targetPlayer: ClassicPlayer, game: Classic, player?: ClassicPlayer, ) => { if (player) { player.user.send("You investigated your target:"); player.user.send( targetPlayer.user.username + " is a " + targetPlayer.alignment, ); } }, }; export const roleBlock: Ability = { condition: Conditions.alwaysTrue, action: (targetPlayer: ClassicPlayer, game: Classic) => { targetPlayer.roleBlocked = true; }, }; export const revive: Ability = { condition: Conditions.alwaysTrue, action: (targetPlayer: ClassicPlayer, game: Classic) => { if (!targetPlayer.alive) { game.revive(targetPlayer); } }, }; export const sendMessage: Ability = { condition: Conditions.alwaysTrue, action: (targetPlayer: ClassicPlayer, game: Classic) => { targetPlayer.user.send("You received some fruit!"); }, }; } export function getRoleColor(role: Role): Colors { if (role.alignment == Alignment.town) { return Colors.brightGreen; } else if (role.alignment == Alignment.mafia) { return Colors.brightRed; } else { return <Colors>role.color; } } export function getRoleBackgroundColor(role: Role): Colors { if (role.alignment == Alignment.town) { return Colors.green; } else if (role.alignment == Alignment.mafia) { return Colors.red; } else { return role.backgroundColor ? role.backgroundColor : (role.color as Colors); } } function mafia(role: Role) { return { roleName: "mafia " + role.roleName, alignment: Alignment.mafia, winCondition: WinConditions.mafia, abilities: role.abilities, passives: role.passives, }; } export namespace Roles { export const vigilante: Role = { roleName: "vigilante", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.kill, uses: 2 }], passives: [], }; export const mafiaVanilla: Role = { roleName: "mafia(vanilla)", alignment: Alignment.mafia, winCondition: WinConditions.mafia, abilities: [], passives: [], }; export const mafioso: Role = { roleName: "mafioso", alignment: Alignment.mafia, winCondition: WinConditions.mafia, abilities: [{ ability: Abilities.mafiosoKill }], passives: [], }; export const godfather: Role = { roleName: "godfather", alignment: Alignment.mafia, winCondition: WinConditions.mafia, abilities: [{ ability: Abilities.godfatherOrder }], passives: [Passives.nightImmune], }; export const doctor: Role = { roleName: "doctor", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.heal }], passives: [], }; export const sherrif: Role = { roleName: "sherrif", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.getAlignment }], passives: [], }; export const townie: Role = { roleName: "townie", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [], passives: [], }; export const escort: Role = { roleName: "escort", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.roleBlock }], passives: [Passives.roleblockImmune], }; export const consort: Role = mafia(escort); export const survivor: Role = { roleName: "survivor", alignment: Alignment.neutral, winCondition: WinConditions.survive, color: Colors.brightYellow, backgroundColor: Colors.yellow, abilities: [], passives: [], }; export const medium: Role = { roleName: "medium", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [], passives: [Passives.speakWithDead], }; export const jester: Role = { roleName: "jester", alignment: Alignment.neutral, winCondition: WinConditions.hanged, color: Colors.magenta, abilities: [], passives: [], }; export const executioner: Role = { roleName: "executioner", alignment: Alignment.neutral, winCondition: WinConditions.lynchTarget, color: Colors.grey, abilities: [], passives: [], }; export const retributionist: Role = { roleName: "retributionist", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.revive, uses: 1 }], passives: [], }; export const fruitVendor: Role = { roleName: "fruit vendor", alignment: Alignment.town, winCondition: WinConditions.town, abilities: [{ ability: Abilities.sendMessage }], passives: [], }; export const serialKiller: Role = { roleName: "serial killer", alignment: Alignment.neutral, winCondition: WinConditions.lastOneStanding, color: Colors.darkBlue, abilities: [{ ability: Abilities.kill }], passives: [], }; export const anyTown: Role = { roleName: "Any Town", alignment: Alignment.town, winCondition: WinConditions.undefined, abilities: [], passives: [], }; export const any: Role = { roleName: "Any", alignment: Alignment.undefined, winCondition: WinConditions.undefined, abilities: [], passives: [], }; } export const priorities = [ Roles.consort, Roles.escort, Roles.fruitVendor, Roles.retributionist, Roles.doctor, Roles.godfather, Roles.mafioso, Roles.vigilante, Roles.sherrif, Roles.mafiaVanilla, Roles.townie, Roles.medium, Roles.survivor, Roles.jester, Roles.executioner, ];
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * EndpointKeys * __NOTE__: An instance of this class is automatically created for an * instance of the QnAMakerClient. */ export interface EndpointKeys { /** * @summary Gets endpoint keys for an endpoint * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EndpointKeysDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getKeysWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EndpointKeysDTO>>; /** * @summary Gets endpoint keys for an endpoint * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EndpointKeysDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EndpointKeysDTO} [result] - The deserialized result object if an error did not occur. * See {@link EndpointKeysDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getKeys(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EndpointKeysDTO>; getKeys(callback: ServiceCallback<models.EndpointKeysDTO>): void; getKeys(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EndpointKeysDTO>): void; /** * @summary Re-generates an endpoint key. * * @param {string} keyType Type of Key * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EndpointKeysDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ refreshKeysWithHttpOperationResponse(keyType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.EndpointKeysDTO>>; /** * @summary Re-generates an endpoint key. * * @param {string} keyType Type of Key * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {EndpointKeysDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {EndpointKeysDTO} [result] - The deserialized result object if an error did not occur. * See {@link EndpointKeysDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ refreshKeys(keyType: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.EndpointKeysDTO>; refreshKeys(keyType: string, callback: ServiceCallback<models.EndpointKeysDTO>): void; refreshKeys(keyType: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.EndpointKeysDTO>): void; } /** * @class * Alterations * __NOTE__: An instance of this class is automatically created for an * instance of the QnAMakerClient. */ export interface Alterations { /** * @summary Download alterations from runtime. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<WordAlterationsDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WordAlterationsDTO>>; /** * @summary Download alterations from runtime. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {WordAlterationsDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {WordAlterationsDTO} [result] - The deserialized result object if an error did not occur. * See {@link WordAlterationsDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WordAlterationsDTO>; get(callback: ServiceCallback<models.WordAlterationsDTO>): void; get(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WordAlterationsDTO>): void; /** * @summary Replace alterations data. * * @param {object} wordAlterations New alterations data. * * @param {array} wordAlterations.wordAlterations Collection of word * alterations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ replaceWithHttpOperationResponse(wordAlterations: models.WordAlterationsDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Replace alterations data. * * @param {object} wordAlterations New alterations data. * * @param {array} wordAlterations.wordAlterations Collection of word * alterations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ replace(wordAlterations: models.WordAlterationsDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; replace(wordAlterations: models.WordAlterationsDTO, callback: ServiceCallback<void>): void; replace(wordAlterations: models.WordAlterationsDTO, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Knowledgebase * __NOTE__: An instance of this class is automatically created for an * instance of the QnAMakerClient. */ export interface Knowledgebase { /** * @summary Gets all knowledgebases for a user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<KnowledgebasesDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listAllWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.KnowledgebasesDTO>>; /** * @summary Gets all knowledgebases for a user. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {KnowledgebasesDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {KnowledgebasesDTO} [result] - The deserialized result object if an error did not occur. * See {@link KnowledgebasesDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listAll(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.KnowledgebasesDTO>; listAll(callback: ServiceCallback<models.KnowledgebasesDTO>): void; listAll(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.KnowledgebasesDTO>): void; /** * @summary Gets details of a specific knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<KnowledgebaseDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDetailsWithHttpOperationResponse(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.KnowledgebaseDTO>>; /** * @summary Gets details of a specific knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {KnowledgebaseDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {KnowledgebaseDTO} [result] - The deserialized result object if an error did not occur. * See {@link KnowledgebaseDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDetails(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.KnowledgebaseDTO>; getDetails(kbId: string, callback: ServiceCallback<models.KnowledgebaseDTO>): void; getDetails(kbId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.KnowledgebaseDTO>): void; /** * @summary Deletes the knowledgebase and all its data. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the knowledgebase and all its data. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(kbId: string, callback: ServiceCallback<void>): void; deleteMethod(kbId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Publishes all changes in test index of a knowledgebase to its prod * index. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ publishWithHttpOperationResponse(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Publishes all changes in test index of a knowledgebase to its prod * index. * * @param {string} kbId Knowledgebase id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ publish(kbId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; publish(kbId: string, callback: ServiceCallback<void>): void; publish(kbId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Replace knowledgebase contents. * * @param {string} kbId Knowledgebase id. * * @param {object} replaceKb An instance of ReplaceKbDTO which contains list of * qnas to be uploaded * * @param {array} replaceKb.qnAList List of Q-A (QnADTO) to be added to the * knowledgebase. Q-A Ids are assigned by the service and should be omitted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ replaceWithHttpOperationResponse(kbId: string, replaceKb: models.ReplaceKbDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Replace knowledgebase contents. * * @param {string} kbId Knowledgebase id. * * @param {object} replaceKb An instance of ReplaceKbDTO which contains list of * qnas to be uploaded * * @param {array} replaceKb.qnAList List of Q-A (QnADTO) to be added to the * knowledgebase. Q-A Ids are assigned by the service and should be omitted. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ replace(kbId: string, replaceKb: models.ReplaceKbDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; replace(kbId: string, replaceKb: models.ReplaceKbDTO, callback: ServiceCallback<void>): void; replace(kbId: string, replaceKb: models.ReplaceKbDTO, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Asynchronous operation to modify a knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {object} updateKb Post body of the request. * * @param {object} [updateKb.add] An instance of CreateKbInputDTO for add * operation * * @param {array} [updateKb.add.qnaList] List of QNA to be added to the index. * Ids are generated by the service and should be omitted. * * @param {array} [updateKb.add.urls] List of URLs to be added to * knowledgebase. * * @param {array} [updateKb.add.files] List of files to be added to * knowledgebase. * * @param {object} [updateKb.deleteProperty] An instance of DeleteKbContentsDTO * for delete Operation * * @param {array} [updateKb.deleteProperty.ids] List of Qna Ids to be deleted * * @param {array} [updateKb.deleteProperty.sources] List of sources to be * deleted from knowledgebase. * * @param {object} [updateKb.update] An instance of UpdateKbContentsDTO for * Update Operation * * @param {string} [updateKb.update.name] Friendly name for the knowledgebase. * * @param {array} [updateKb.update.qnaList] List of Q-A (UpdateQnaDTO) to be * added to the knowledgebase. * * @param {array} [updateKb.update.urls] List of existing URLs to be refreshed. * The content will be extracted again and re-indexed. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Operation>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(kbId: string, updateKb: models.UpdateKbOperationDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Operation>>; /** * @summary Asynchronous operation to modify a knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {object} updateKb Post body of the request. * * @param {object} [updateKb.add] An instance of CreateKbInputDTO for add * operation * * @param {array} [updateKb.add.qnaList] List of QNA to be added to the index. * Ids are generated by the service and should be omitted. * * @param {array} [updateKb.add.urls] List of URLs to be added to * knowledgebase. * * @param {array} [updateKb.add.files] List of files to be added to * knowledgebase. * * @param {object} [updateKb.deleteProperty] An instance of DeleteKbContentsDTO * for delete Operation * * @param {array} [updateKb.deleteProperty.ids] List of Qna Ids to be deleted * * @param {array} [updateKb.deleteProperty.sources] List of sources to be * deleted from knowledgebase. * * @param {object} [updateKb.update] An instance of UpdateKbContentsDTO for * Update Operation * * @param {string} [updateKb.update.name] Friendly name for the knowledgebase. * * @param {array} [updateKb.update.qnaList] List of Q-A (UpdateQnaDTO) to be * added to the knowledgebase. * * @param {array} [updateKb.update.urls] List of existing URLs to be refreshed. * The content will be extracted again and re-indexed. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Operation} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Operation} [result] - The deserialized result object if an error did not occur. * See {@link Operation} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(kbId: string, updateKb: models.UpdateKbOperationDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Operation>; update(kbId: string, updateKb: models.UpdateKbOperationDTO, callback: ServiceCallback<models.Operation>): void; update(kbId: string, updateKb: models.UpdateKbOperationDTO, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Operation>): void; /** * @summary Asynchronous operation to create a new knowledgebase. * * @param {object} createKbPayload Post body of the request. * * @param {string} createKbPayload.name Friendly name for the knowledgebase. * * @param {array} [createKbPayload.qnaList] List of Q-A (QnADTO) to be added to * the knowledgebase. Q-A Ids are assigned by the service and should be * omitted. * * @param {array} [createKbPayload.urls] List of URLs to be used for extracting * Q-A. * * @param {array} [createKbPayload.files] List of files from which to Extract * Q-A. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Operation>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(createKbPayload: models.CreateKbDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Operation>>; /** * @summary Asynchronous operation to create a new knowledgebase. * * @param {object} createKbPayload Post body of the request. * * @param {string} createKbPayload.name Friendly name for the knowledgebase. * * @param {array} [createKbPayload.qnaList] List of Q-A (QnADTO) to be added to * the knowledgebase. Q-A Ids are assigned by the service and should be * omitted. * * @param {array} [createKbPayload.urls] List of URLs to be used for extracting * Q-A. * * @param {array} [createKbPayload.files] List of files from which to Extract * Q-A. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Operation} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Operation} [result] - The deserialized result object if an error did not occur. * See {@link Operation} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(createKbPayload: models.CreateKbDTO, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Operation>; create(createKbPayload: models.CreateKbDTO, callback: ServiceCallback<models.Operation>): void; create(createKbPayload: models.CreateKbDTO, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Operation>): void; /** * @summary Download the knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {string} environment Specifies whether environment is Test or Prod. * Possible values include: 'Prod', 'Test' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<QnADocumentsDTO>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ downloadWithHttpOperationResponse(kbId: string, environment: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.QnADocumentsDTO>>; /** * @summary Download the knowledgebase. * * @param {string} kbId Knowledgebase id. * * @param {string} environment Specifies whether environment is Test or Prod. * Possible values include: 'Prod', 'Test' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {QnADocumentsDTO} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {QnADocumentsDTO} [result] - The deserialized result object if an error did not occur. * See {@link QnADocumentsDTO} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ download(kbId: string, environment: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.QnADocumentsDTO>; download(kbId: string, environment: string, callback: ServiceCallback<models.QnADocumentsDTO>): void; download(kbId: string, environment: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.QnADocumentsDTO>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the QnAMakerClient. */ export interface Operations { /** * @summary Gets details of a specific long running operation. * * @param {string} operationId Operation id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Operation>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDetailsWithHttpOperationResponse(operationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Operation>>; /** * @summary Gets details of a specific long running operation. * * @param {string} operationId Operation id. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Operation} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Operation} [result] - The deserialized result object if an error did not occur. * See {@link Operation} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDetails(operationId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Operation>; getDetails(operationId: string, callback: ServiceCallback<models.Operation>): void; getDetails(operationId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Operation>): void; }
the_stack